三、數(shù)據(jù)庫(kù)&listView

Android基礎(chǔ)第三天

1 Android下數(shù)據(jù)庫(kù)創(chuàng)建

什么情況下我們才用數(shù)據(jù)庫(kù)做數(shù)據(jù)存儲(chǔ)? 大量數(shù)據(jù)結(jié)構(gòu)相同的數(shù)據(jù)需要存儲(chǔ)時(shí)。
mysql sqlserver2000  sqlite 嵌入式 輕量級(jí)

SqliteOpenHelper

創(chuàng)建數(shù)據(jù)庫(kù)步驟:
1.創(chuàng)建一個(gè)類集成SqliteOpenHelper,需要添加一個(gè)構(gòu)造方法,實(shí)現(xiàn)兩個(gè)方法oncreate ,onupgrade
    構(gòu)造方法中的參數(shù)介紹:

    //context :上下文   , name:數(shù)據(jù)庫(kù)文件的名稱    factory:用來(lái)創(chuàng)建cursor對(duì)象,默認(rèn)為null 
    //version:數(shù)據(jù)庫(kù)的版本號(hào),從1開始,如果發(fā)生改變,onUpgrade方法將會(huì)調(diào)用,4.0之后只能升不能將
    super(context, "info.db", null,1);
    

2.創(chuàng)建這個(gè)幫助類的一個(gè)對(duì)象,調(diào)用getReadableDatabase()方法,會(huì)幫助我們創(chuàng)建打開一個(gè)數(shù)據(jù)庫(kù)

3.復(fù)寫oncreate和onupgrdate方法:
    oncreate方法是數(shù)據(jù)庫(kù)第一次創(chuàng)建的時(shí)候會(huì)被調(diào)用;  特別適合做表結(jié)構(gòu)的初始化,需要執(zhí)行sql語(yǔ)句;SQLiteDatabase db可以用來(lái)執(zhí)行sql語(yǔ)句
    
    //onUpgrade數(shù)據(jù)庫(kù)版本號(hào)發(fā)生改變時(shí)才會(huì)執(zhí)行; 特別適合做表結(jié)構(gòu)的修改



幫助類對(duì)象中的getWritableDatabase 和 getReadableDatabase都可以幫助我們獲取一個(gè)數(shù)據(jù)庫(kù)操作對(duì)象SqliteDatabase.

區(qū)別:
getReadableDatabase:
    先嘗試以讀寫方式打開數(shù)據(jù)庫(kù),如果磁盤空間滿了,他會(huì)重新嘗試以只讀方式打開數(shù)據(jù)庫(kù)。
getWritableDatabase:
    直接以讀寫方式打開數(shù)據(jù)庫(kù),如果磁盤空間滿了,就直接報(bào)錯(cuò)。

2 Android下數(shù)據(jù)庫(kù)第一種方式增刪改查

1.創(chuàng)建一個(gè)幫助類的對(duì)象,調(diào)用getReadableDatabase方法,返回一個(gè)SqliteDatebase對(duì)象

2.使用SqliteDatebase對(duì)象調(diào)用execSql()做增刪改,調(diào)用rawQuery方法做查詢。

******特點(diǎn):增刪改沒有返回值,不能判斷sql語(yǔ)句是否執(zhí)行成功。sql語(yǔ)句手動(dòng)寫,容易寫錯(cuò)



private MySqliteOpenHelper mySqliteOpenHelper;
public InfoDao(Context context){
    //創(chuàng)建一個(gè)幫助類對(duì)象
    mySqliteOpenHelper = new MySqliteOpenHelper(context);

    
}

public void add(InfoBean bean){

    //執(zhí)行sql語(yǔ)句需要sqliteDatabase對(duì)象
    //調(diào)用getReadableDatabase方法,來(lái)初始化數(shù)據(jù)庫(kù)的創(chuàng)建
    SQLiteDatabase  db = mySqliteOpenHelper.getReadableDatabase();
    //sql:sql語(yǔ)句,  bindArgs:sql語(yǔ)句中占位符的值
    db.execSQL("insert into info(name,phone) values(?,?);", new Object[]{bean.name,bean.phone});
    //關(guān)閉數(shù)據(jù)庫(kù)對(duì)象
    db.close();
}

public void del(String name){


    //執(zhí)行sql語(yǔ)句需要sqliteDatabase對(duì)象
    //調(diào)用getReadableDatabase方法,來(lái)初始化數(shù)據(jù)庫(kù)的創(chuàng)建
    SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
    //sql:sql語(yǔ)句,  bindArgs:sql語(yǔ)句中占位符的值
    db.execSQL("delete from info where name=?;", new Object[]{name});
    //關(guān)閉數(shù)據(jù)庫(kù)對(duì)象
    db.close();

}
public void update(InfoBean bean){

    //執(zhí)行sql語(yǔ)句需要sqliteDatabase對(duì)象
    //調(diào)用getReadableDatabase方法,來(lái)初始化數(shù)據(jù)庫(kù)的創(chuàng)建
    SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
    //sql:sql語(yǔ)句,  bindArgs:sql語(yǔ)句中占位符的值
    db.execSQL("update info set phone=? where name=?;", new Object[]{bean.phone,bean.name});
    //關(guān)閉數(shù)據(jù)庫(kù)對(duì)象
    db.close();

}
public void query(String name){
    
    //執(zhí)行sql語(yǔ)句需要sqliteDatabase對(duì)象
    //調(diào)用getReadableDatabase方法,來(lái)初始化數(shù)據(jù)庫(kù)的創(chuàng)建
    SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
    //sql:sql語(yǔ)句,  selectionArgs:查詢條件占位符的值,返回一個(gè)cursor對(duì)象
    Cursor cursor = db.rawQuery("select _id, name,phone from info where name = ?", new String []{name});
    //解析Cursor中的數(shù)據(jù)
    if(cursor != null && cursor.getCount() >0){//判斷cursor中是否存在數(shù)據(jù)
        
        //循環(huán)遍歷結(jié)果集,獲取每一行的內(nèi)容
        while(cursor.moveToNext()){//條件,游標(biāo)能否定位到下一行
            //獲取數(shù)據(jù)
            int id = cursor.getInt(0);
            String name_str = cursor.getString(1);
            String phone = cursor.getString(2);
            System.out.println("_id:"+id+";name:"+name_str+";phone:"+phone);
        }
        cursor.close();//關(guān)閉結(jié)果集
        
    }
    //關(guān)閉數(shù)據(jù)庫(kù)對(duì)象
    db.close();

}

3 Android下另外一種增刪改查方式

1.創(chuàng)建一個(gè)幫助類的對(duì)象,調(diào)用getReadableDatabase方法,返回一個(gè)SqliteDatebase對(duì)象

2.使用SqliteDatebase對(duì)象調(diào)用insert,update,delete ,query方法做增刪改查。

******特點(diǎn):增刪改有了返回值,可以判斷sql語(yǔ)句是否執(zhí)行成功,但是查詢不夠靈活,不能做多表查詢。所以在公司一般人增刪改喜歡用第二種方式,查詢用第一種方式。

        private MySqliteOpenHelper mySqliteOpenHelper;
public InfoDao(Context context){
    //創(chuàng)建一個(gè)幫助類對(duì)象
    mySqliteOpenHelper = new MySqliteOpenHelper(context);
}

public boolean add(InfoBean bean){

    //執(zhí)行sql語(yǔ)句需要sqliteDatabase對(duì)象
    //調(diào)用getReadableDatabase方法,來(lái)初始化數(shù)據(jù)庫(kù)的創(chuàng)建
    SQLiteDatabase  db = mySqliteOpenHelper.getReadableDatabase();
    
    
    ContentValues values = new ContentValues();//是用map封裝的對(duì)象,用來(lái)存放值
    values.put("name", bean.name);
    values.put("phone", bean.phone);
    
    //table: 表名 , nullColumnHack:可以為空,標(biāo)示添加一個(gè)空行, values:數(shù)據(jù)一行的值 , 返回值:代表添加這個(gè)新行的Id ,-1代表添加失敗
    long result = db.insert("info", null, values);//底層是在拼裝sql語(yǔ)句

    //關(guān)閉數(shù)據(jù)庫(kù)對(duì)象
    db.close();
    
    if(result != -1){//-1代表添加失敗
        return true;
    }else{
        return false;
    }
}

public int del(String name){

    //執(zhí)行sql語(yǔ)句需要sqliteDatabase對(duì)象
    //調(diào)用getReadableDatabase方法,來(lái)初始化數(shù)據(jù)庫(kù)的創(chuàng)建
    SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
    
    //table :表名, whereClause: 刪除條件, whereArgs:條件的占位符的參數(shù) ; 返回值:成功刪除多少行
    int result = db.delete("info", "name = ?", new String[]{name});
    //關(guān)閉數(shù)據(jù)庫(kù)對(duì)象
    db.close();
    
    return result;

}
public int update(InfoBean bean){

    //執(zhí)行sql語(yǔ)句需要sqliteDatabase對(duì)象
    //調(diào)用getReadableDatabase方法,來(lái)初始化數(shù)據(jù)庫(kù)的創(chuàng)建
    SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
    ContentValues values = new ContentValues();//是用map封裝的對(duì)象,用來(lái)存放值
    values.put("phone", bean.phone);
    //table:表名, values:更新的值, whereClause:更新的條件, whereArgs:更新條件的占位符的值,返回值:成功修改多少行
    int result = db.update("info", values, "name = ?", new String[]{bean.name});
    //關(guān)閉數(shù)據(jù)庫(kù)對(duì)象
    db.close();
    return result;

}
public void query(String name){

    //執(zhí)行sql語(yǔ)句需要sqliteDatabase對(duì)象
    //調(diào)用getReadableDatabase方法,來(lái)初始化數(shù)據(jù)庫(kù)的創(chuàng)建
    SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
    
    //table:表名, columns:查詢的列名,如果null代表查詢所有列; selection:查詢條件, selectionArgs:條件占位符的參數(shù)值,
    //groupBy:按什么字段分組, having:分組的條件, orderBy:按什么字段排序
    Cursor cursor = db.query("info", new String[]{"_id","name","phone"}, "name = ?", new String[]{name}, null, null, "_id desc");
    //解析Cursor中的數(shù)據(jù)
    if(cursor != null && cursor.getCount() >0){//判斷cursor中是否存在數(shù)據(jù)
        
        //循環(huán)遍歷結(jié)果集,獲取每一行的內(nèi)容
        while(cursor.moveToNext()){//條件,游標(biāo)能否定位到下一行
            //獲取數(shù)據(jù)
            int id = cursor.getInt(0);
            String name_str = cursor.getString(1);
            String phone = cursor.getString(2);
            System.out.println("_id:"+id+";name:"+name_str+";phone:"+phone);
            
            
        }
        cursor.close();//關(guān)閉結(jié)果集
        
    }
    //關(guān)閉數(shù)據(jù)庫(kù)對(duì)象
    db.close();

}

4 數(shù)據(jù)庫(kù)的事務(wù)

事務(wù): 執(zhí)行多條sql語(yǔ)句,要么同時(shí)執(zhí)行成功,要么同時(shí)執(zhí)行失敗,不能有的成功,有的失敗

銀行轉(zhuǎn)賬


//點(diǎn)擊按鈕執(zhí)行該方法
public void transtation(View v){
    //1.創(chuàng)建一個(gè)幫助類的對(duì)象
    BankOpenHelper bankOpenHelper = new BankOpenHelper(this);
    //2.調(diào)用數(shù)據(jù)庫(kù)幫助類對(duì)象的getReadableDatabase創(chuàng)建數(shù)據(jù)庫(kù),初始化表數(shù)據(jù),獲取一個(gè)SqliteDatabase對(duì)象去做轉(zhuǎn)賬(sql語(yǔ)句)
    SQLiteDatabase db = bankOpenHelper.getReadableDatabase();
    //3.轉(zhuǎn)賬,將李四的錢減200,張三加200
    db.beginTransaction();//開啟一個(gè)數(shù)據(jù)庫(kù)事務(wù)
    try {
        db.execSQL("update account set money= money-200 where name=?",new String[]{"李四"});
        int i = 100/0;//模擬一個(gè)異常
        db.execSQL("update account set money= money+200 where name=?",new String[]{"張三"});

        db.setTransactionSuccessful();//標(biāo)記事務(wù)中的sql語(yǔ)句全部成功執(zhí)行
    } finally {
        db.endTransaction();//判斷事務(wù)的標(biāo)記是否成功,如果不成功,回滾錯(cuò)誤之前執(zhí)行的sql語(yǔ)句 
    }
}

5 listview 入門

    ListView 是一個(gè)控件,一個(gè)在垂直滾動(dòng)的列表中顯示條目的一個(gè)控件,這些條目的內(nèi)容來(lái)自于一個(gè)ListAdapter 。EditText Button TextView ImageView Checkbox 五大布局。


    1.布局添加Listview
    
    2.找到listview

    3.創(chuàng)建一個(gè)Adapter適配器繼承BaseAdapter,封裝4個(gè)方法,其中g(shù)etcount,getview必須封裝
        getcount:告訴listview要顯示的條目數(shù)
        getview:告訴listview每個(gè)條目顯示的內(nèi)容。
    4.創(chuàng)建Adapter的一個(gè)對(duì)象,設(shè)置給listview。
            listview.setAdapter(ListAdapter adapter);

6 listview優(yōu)化

adapter中g(shù)etview方法會(huì)傳進(jìn)來(lái)一個(gè)convertView,convertView是指曾經(jīng)使用過的view對(duì)象,可以被重復(fù)使用,但是在使用前需要判斷是否為空,不為空直接復(fù)用,并作為getview方法的返回對(duì)象。
        TextView view = null;
        if(convertView != null){//判斷converView是否為空,不為空重新使用
            view = (TextView) convertView;
        }else{
            view = new TextView(mContext);//創(chuàng)建一個(gè)textView對(duì)象
        }
        return view;

7 listview---老虎機(jī)

javaweb mvc
m....mode....javabean
v....view....jsp
c....control...servlet

listview mvc
m....mode....Bean
v....view....listview
c....control...adapter

8 listview顯示原理 (了解)

1.要考慮listview顯示的條目數(shù)    getcount
2.考慮listview每個(gè)條目顯示的內(nèi)容   getview
3.考慮每個(gè)item的高度,因?yàn)槠聊坏亩鄻踊?4.還要考慮listview的滑動(dòng),監(jiān)聽一個(gè)舊的條目消失,一個(gè)新的條目顯示。

9 復(fù)雜listview界面顯示 ,新聞(***********重要***********)

1.布局寫listview

2.找到listview

3.獲取新聞數(shù)據(jù)封裝到list集合中(才用模擬數(shù)據(jù)),作為adapter的顯示數(shù)據(jù),怎么將獲取的新聞數(shù)據(jù)給adapter???

4.創(chuàng)建一個(gè)adapter繼承BaseAdapter,實(shí)現(xiàn)4個(gè)方法
    getcount: 有多少條新聞數(shù)據(jù),就有多少個(gè)條目。
    getView:將返回一個(gè)復(fù)雜的布局作為條目的內(nèi)容展示;并且顯示的數(shù)據(jù)是新聞的信息。 ?????
    
public View getView(int position, View convertView, ViewGroup parent) {
    View view = null;
    //1.復(fù)用converView優(yōu)化listview,創(chuàng)建一個(gè)view作為getview的返回值用來(lái)顯示一個(gè)條目
    if(convertView != null){
        view = convertView;
    }else {
        //context:上下文, resource:要轉(zhuǎn)換成view對(duì)象的layout的id, root:將layout用root(ViewGroup)包一層作為getview的返回值,一般傳null
        view = View.inflate(context, R.layout.item_news_layout, null);//將一個(gè)布局文件轉(zhuǎn)換成一個(gè)view對(duì)象
    }
    //2.獲取view上的子控件對(duì)象
    ImageView item_img_icon = (ImageView) view.findViewById(R.id.item_img_icon);
    TextView item_tv_des = (TextView) view.findViewById(R.id.item_tv_des);
    TextView item_tv_title = (TextView) view.findViewById(R.id.item_tv_title);
    //3.獲取postion位置條目對(duì)應(yīng)的list集合中的新聞數(shù)據(jù),Bean對(duì)象
    NewsBean newsBean = list.get(position);
    //4.將數(shù)據(jù)設(shè)置給這些子控件做顯示
    item_img_icon.setImageDrawable(newsBean.icon);//設(shè)置imageView的圖片
    item_tv_title.setText(newsBean.title);
    item_tv_des.setText(newsBean.des);
    
    return view;
}
    
5.創(chuàng)建一個(gè)adapter對(duì)象設(shè)置給listview

6.設(shè)置listview的條目的點(diǎn)擊事件,并封裝點(diǎn)擊事件,去查看新聞詳情。 ?????????
    //設(shè)置listview條目的點(diǎn)擊事件
    lv_news.setOnItemClickListener(this);

        //listview的條目點(diǎn)擊時(shí)會(huì)調(diào)用該方法 parent:代表listviw  view:點(diǎn)擊的條目上的那個(gè)view對(duì)象   position:條目的位置  id: 條目的id

public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    
    //需要獲取條目上bean對(duì)象中url做跳轉(zhuǎn)
    NewsBean bean = (NewsBean) parent.getItemAtPosition(position);
    
    String url = bean.news_url;
    
    //跳轉(zhuǎn)瀏覽器
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setData(Uri.parse(url));
    startActivity(intent);
}

    

1.布局寫listview ok

2.找到listview ok 

3.封裝新聞數(shù)據(jù)到list集合中 ,目的是為adapter提供數(shù)據(jù)展示。 ok 

4.封裝一個(gè)Adapter類繼承BaseAdatper,寫一個(gè)構(gòu)造方法接受list集合數(shù)據(jù),復(fù)寫四個(gè)方法
    a.創(chuàng)建一個(gè)構(gòu)造方法  ok 
    b.封裝getCount方法   ok 
    c.getView方法:   不ok
        1.復(fù)用convertview,模板代碼,如果不都能空,需要將一個(gè)布局文件轉(zhuǎn)換為view對(duì)象作為getview的返回對(duì)象。
            view = View.inflater(Context context, int resuorceId,ViewGroup root)
        2.找到view上的這些子控件,目的是將list集合中的bean數(shù)據(jù)一一對(duì)應(yīng)設(shè)置給這些子控件

        3.從list集合中獲取postion條目上要顯示的數(shù)據(jù)Bean
        
        4.將獲取的bean中的數(shù)據(jù)設(shè)置給這些子控件
    d.getItem方法:將list集合中指定postion上的bean對(duì)象返回
    e.getItemId,直接返回postion

5.創(chuàng)建一個(gè)封裝的Adapter對(duì)象,設(shè)置給listview   ok
6.設(shè)置listview條目的點(diǎn)擊事件  ok
    listview.setOnItem....

7.復(fù)寫OnItemClicklistener方法,獲取相應(yīng)條目上的bean對(duì)象,最終獲取到url,做Intent跳轉(zhuǎn);  不ok

10 常用獲取inflate的寫法

        1.
        //context:上下文, resource:要轉(zhuǎn)換成view對(duì)象的layout的id, root:將layout用root(ViewGroup)包一層作為codify的返回值,一般傳null
            //view = View.inflate(context, R.layout.item_news_layout, null);//將一個(gè)布局文件轉(zhuǎn)換成一個(gè)view對(duì)象

        2.
        //通過LayoutInflater將布局轉(zhuǎn)換成view對(duì)象
        //view =  LayoutInflater.from(context).inflate(R.layout.item_news_layout, null);
        
        3.
        //通過context獲取系統(tǒng)服務(wù)得到一個(gè)LayoutInflater,通過LayoutInflater將一個(gè)布局轉(zhuǎn)換為view對(duì)象
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.item_news_layout, null);

11 arrayadapter (不用看,知道有這個(gè)玩意就行)

    //找到控件
    ListView lv_array = (ListView) findViewById(R.id.lv_array);
    ListView lv_simple = (ListView) findViewById(R.id.lv_simple);
    
    //創(chuàng)建一個(gè)arrayAdapter
//context  , resource:布局id, textViewResourceId:條目布局中 textview控件的id, objects:條目上texitview顯示的內(nèi)容
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.item_listview_layout, R.id.item_tv_class, classz);
    lv_array.setAdapter(arrayAdapter);

12 simpleadapter (不用看,知道有這個(gè)玩意就行)

    //創(chuàng)建一個(gè)simpleAdapter,封裝simpleAdapter的數(shù)據(jù)
    ArrayList<Map<String, String>> arrayList = new ArrayList<Map<String,String>>();
    HashMap<String, String> hashMap = new HashMap<String, String>();
    hashMap.put("class", "C++");
    arrayList.add(hashMap);
    
    HashMap<String, String> hashMap1 = new HashMap<String, String>();
    hashMap1.put("class", "android");
    arrayList.add(hashMap1);
    
    
    HashMap<String, String> hashMap2 = new HashMap<String, String>();
    hashMap2.put("class", "javaEE");
    arrayList.add(hashMap2);
    
    //context, data:顯示的數(shù)據(jù), resource:item布局id, from: map中的key, to:布局中的控件id
    SimpleAdapter simpleAdapter = new SimpleAdapter(this, arrayList, R.layout.item_listview_layout, new String[]{"class"}, new int[]{R.id.item_tv_class});
    
    lv_simple.setAdapter(simpleAdapter);

13 數(shù)據(jù)庫(kù)的listview的界面顯示 (新聞會(huì)了,這個(gè)就會(huì)了)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,139評(píng)論 25 708
  • 用兩張圖告訴你,為什么你的 App 會(huì)卡頓? - Android - 掘金 Cover 有什么料? 從這篇文章中你...
    hw1212閱讀 14,039評(píng)論 2 59
  • 一、上節(jié)回顧: (一)、三大表單控件中需要記憶的核心方法: 1、RadioButton: RadioGroup類中...
    白話徐文濤閱讀 2,250評(píng)論 1 7
  • 外在的一切都是你內(nèi)在思想的反應(yīng),為什么一直覺得自己是孤單的呢?這個(gè)孤單的感覺從何而來(lái)? 昨天不知道...
    lily北媽閱讀 156評(píng)論 0 0
  • 肚皮舞中有各種不同的西米,區(qū)別在于其運(yùn)動(dòng)軌跡和發(fā)力點(diǎn)的不同,很多動(dòng)作看上去并沒有太大區(qū)別,但實(shí)質(zhì)相差甚遠(yuǎn),而細(xì)微的...
    蘇秀A閱讀 2,749評(píng)論 0 0

友情鏈接更多精彩內(nèi)容