Android SimpleCursorAdapter的使用

adapter 下的最後一個類,這個類就不介紹太多了,直接上實例代碼。

佈局文件,就一個listview

<span style="font-size:14px;">   <ListView
        android:id="@+id/lvcsdn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/spinner1"
        >
    </ListView></span>

activity:

public class SimpleCursorAdapterActivity extends Activity{
	private ListView  lv;
	MySQLiteHelper myHelper;
	MyCursorAdapter adapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		lv=(ListView) findViewById(R.id.lvcsdn);

		//先像數據庫插入數據
		//創建MySQLiteOpenHelper輔助類對象  
		myHelper = new MySQLiteHelper(this, "my.db", null, 1); 
		//獲取數據庫對象  
		SQLiteDatabase db = myHelper.getWritableDatabase();  
		//使用execSQL方法向表中插入數據  
		db.execSQL("insert into user(name,age) values('zhangsan',18)");  
		db.execSQL("insert into user(name,age) values('lisi',20)");  
		//使用insert方法向表中插入數據  
		ContentValues values = new ContentValues();  
		values.put("name", "wangwu");  
		values.put("age", 22);  
		//調用方法插入數據  
		db.insert("user",null, values);  
		db.close();
		//獲得數據庫對象  
		SQLiteDatabase db2 = myHelper.getReadableDatabase();  
		//查詢表中的數據  
		Cursor cursor = db2.query("user", null, null, null, null, null,null); 
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_expandable_list_item_1,cursor, new String[]{"name"}, new int[]{android.R.id.text1}); 
		lv.setAdapter(adapter);
	}

}
其中用到了SQLiteOpenHelper:

public class MySQLiteHelper extends SQLiteOpenHelper{

	public MySQLiteHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
	}
	//創建表
	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("create table if not exists user (_id integer primary key autoincrement,name varchar(20) ,age integer)");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		
	}

}
注意:查詢語句的主鍵必須要爲"_id"

效果圖:


好了,adapter的所有相關知識到這裏就介紹完了,有什麼寫的不好的地方,或者需要改進的地方,歡迎溝通交流。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章