标签:ima key hid set onclick display code 插入 成功
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 }
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 }
【安卓9】SimpleCursorAdapter、在列表中展示数据
标签:ima key hid set onclick display code 插入 成功
原文地址:http://www.cnblogs.com/leelee/p/7045158.html