1. 程式人生 > >【安卓9】SimpleCursorAdapter、在列表中展示數據

【安卓9】SimpleCursorAdapter、在列表中展示數據

color ner table exist spl 操作 onclick state activity

SimpleCursorAdapter

SimpleCursorAdaper與SimpleAdapter類似,但數據來源是Cursor。

操作步驟:

技術分享

技術分享

在列表中展示數據

技術分享
 1 public MySQLiteOpenHelper(Context context) {
 2      super(context,"person.db",null,1);
 3 }
 4 public void onCreate(SQLiteDatabase db) {
 5     db.execSQL("create table if not exists person(" 
 6         +"_id integer primary key autoincrement,"
 7
+"name varchar(20)"); 8 } 9 /** 查詢方法 10 * @return Cursor對象 11 */ 12 public Cursor query(){ 13 SQLiteDatabase db=getWritableDatabase(); 14 Cursor cursor=db.query("person", new String[]{"id _id ","name"}, null, null, null, null, null); 15 return cursor; 16 } 17 /**向數據庫插入數據
*/ 18 public void insert(String [] args){ 19 SQLiteDatabase db=this.getWritableDatabase(); 20 //該對象可操作鍵-值對數據 21 ContentValues values=new ContentValues(); 22 values.put("name",args[0]);//存放數據 23 //表名,強行插入null值得數據列的列名,記錄數據 24 db.insert("person",null,values);
25 }
MySQLiteOpenHelper代碼 技術分享
 1 Activity代碼
 2 public class Main extends Activity implements OnClickListener{
 3 private  Button  addBtn;
 4 private  Button  findBtn;
 5 private  EditText nameEt;
 6 private  EditText phoneEt;
 7 private  ListView listView;
 8 private  SimpleCursorAdapter  adapter;
 9 private  MySQLiteOpenHelper  helper;
10     public void onCreate(Bundle savedInstanceState) {
11         super.onCreate(savedInstanceState);
12         setContentView(R.layout.main);
13         addBtn=(Button)findViewById(R.id.addBtn);
14         findBtn=(Button)findViewById(R.id.findBtn);
15         nameEt=(EditText)findViewById(R.id.nameEt);
16         phoneEt=(EditText)findViewById(R.id.phoneEt);
17         listView=(ListView)findViewById(R.id.lv);
18         addBtn.setOnClickListener(this);
19         findBtn.setOnClickListener(this);
20 
21         helper=new MySQLiteOpenHelper(this);
22         Cursor  cursor=helper.query();
23         adapter=new SimpleCursorAdapter(this,R.layout.list_item, 
24         cursor,new String[]{"_id","name","phone"},
25         new int[]{R.id.idTv,R.id.nameTv,R.id.phoneTv});
26         listView.setAdapter(adapter);
27     } 
28 public void onClick(View v) {
29     MySQLiteOpenHelper  db=new MySQLiteOpenHelper(Main.this);
30     switch(v.getId()){
31     case R.id.addBtn:
32         String  name=nameEt.getText().toString();
33         String  phone=phoneEt.getText().toString();
34         db.insert(new String[]{name,phone});
35         Toast.makeText(this,"插入成功",3000).show();
36     break;
37    case R.id.findBtn:
38            Cursor  cur=helper.query();
39            adapter.changeCursor(cur);//更新遊標適配器對象
40            adapter.notifyDataSetChanged();//通知列表控件數據發生改變
41     break;
42 }
Activity 代碼

【安卓9】SimpleCursorAdapter、在列表中展示數據