一、用到CursorAdapter首先要用到数据库了
1、我们先来创建数据库,首先去官方找下资料
https://developer.android.com/training/basics/data-storage/databases.html
我就照着这个敲了下
/**
* Created by Administrator on 2016/7/29.
* 该代码段定义了单个表格的表格名称和列名称:
*/
public class FeedReaderContract {
public FeedReaderContract() {
}
/* Inner class that defines the table contents */
public static abstract class FeedEntry implements BaseColumns {
public static final String TABLE_NAME = "entry";
public static final String COULUMN_NAME_ENTRY_ID = "entryid";
public static final String COLUMN_NAME_TITILE = "title";
public static final String COLUMN_NAME_SUBTITLE = "subtitle";
}
}
这样写方便不少,然后就是建个数据库工具类
/**
* Created by Administrator on 2016/7/29.
* 使用 SQL 辅助工具创建数据库
*/
public class FeedReaderDbHelper extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "FeedReader.db";
private static final String TEXT_TYPE = " TEXT"; //千万注意 引号后面的空格,这样系统才知道这个是表示数据类型的
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + FeedReaderContract.FeedEntry.TABLE_NAME + " (" +
FeedReaderContract.FeedEntry._ID + " INTEGER PRIMARY KEY," +
FeedReaderContract.FeedEntry.COULUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
FeedReaderContract.FeedEntry.COLUMN_NAME_TITILE + TEXT_TYPE + ")";
private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + FeedReaderContract.FeedEntry.TABLE_NAME;
public FeedReaderDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
}
代码里有个注意的地方,数据库就Ok了
接着就是对数据库的增删改查了,后面会给代码
2、开始用CursorAdapter
代码搬家
public class TodoCursorAdapter extends CursorAdapter {
public TodoCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.item_todo, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.tvBody);
TextView tvPriority = (TextView) view.findViewById(R.id.tvPriority);
// Extract properties from cursor
String title = cursor.getString(cursor.getColumnIndexOrThrow(FeedReaderContract.FeedEntry.COLUMN_NAME_TITILE));
tvBody.setText(title);
}
}
使用的地方
public class MainActivity extends AppCompatActivity {
private boolean isShow;
private RelativeLayout view;
private SQLiteDatabase db;//修改工具类对象
private TodoCursorAdapter todoAdaapter;
/**
* 将信息输入到数据库
*
* @param v
*/
public void addDb(View v) {
ContentValues values = null;
for (int i = 1; i < 5; i++) {
values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COULUMN_NAME_ENTRY_ID, i);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITILE, "heh" + i);
long newRowId = db.insert(FeedReaderContract.FeedEntry.TABLE_NAME, FeedReaderContract.FeedEntry.TABLE_NAME, values);
todoAdaapter.changeCursor(queryDb()); //Cursor改变调用chanageCursor()方法
if (newRowId != -1)
Toast.makeText(MainActivity.this, "插入成功", Toast.LENGTH_SHORT).show();
}
}
/**
* 从数据库删除信息
*
* @param v
*/
public void deleteDb(View v) {
//Define 'where' part of query
String selection = FeedReaderContract.FeedEntry.COULUMN_NAME_ENTRY_ID + " like ?";
//Specify arguments in placeholder order.
// String[] selectionArgs = {String.valueOf(FeedReaderContract.FeedEntry._ID)};
String[] selectionArgs = {String.valueOf(2)};
//Issue SQL statement.
int i = db.delete(FeedReaderContract.FeedEntry.TABLE_NAME, selection, selectionArgs);
}
/**
* 从数据库读取信息
*
* @param
*/
public Cursor queryDb() {
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {FeedReaderContract.FeedEntry._ID,
FeedReaderContract.FeedEntry.COULUMN_NAME_ENTRY_ID,
FeedReaderContract.FeedEntry.COLUMN_NAME_TITILE};
// How you want the results sorted in the resulting Cursor
String sortOrder = FeedReaderContract.FeedEntry._ID + "DESC";
Cursor c = db.query(FeedReaderContract.FeedEntry.TABLE_NAME, // The table to query
projection, //The columns to return
null, // selection : The columns for the WHERE clause
null, //selectionArgs : The values for the WHERE clause
null,
null,
null/* sortOrder //The sort order*/
);
// while (c.moveToNext()) {
// String titleName = c.getString(c.getColumnIndexOrThrow(FeedReaderContract.FeedEntry.COLUMN_NAME_TITILE));
// Log.i("MainActivity", titleName);
// }
return c;
}
/**
* 更新数据库
*
* @param v
*/
public void updateDb(View v) {
// New value for one column
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITILE, "jahlajfajfjjfjf");
// Which row to update, based on the ID
String selection = FeedReaderContract.FeedEntry.COULUMN_NAME_ENTRY_ID + " LIKE ?";
String[] selectionArgs = {String.valueOf(3)};
int i = db.update(FeedReaderContract.FeedEntry.TABLE_NAME, values, selection, selectionArgs);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化工具类实例
FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(this);
db = mDbHelper.getWritableDatabase();
// initWindow();
ListView lvCur = (ListView) findViewById(R.id.lv_cur);
todoAdaapter = new TodoCursorAdapter(this, queryDb());
lvCur.setAdapter(todoAdaapter);
}
要注意的就是 //Cursor改变调用chanageCursor()方法
和notifyDataSetChanged()类似
2、在生命周期destroy(),调用close()关闭数据库
参考 :https://github.com/codepath/android_guides/wiki/Populating-a-ListView-with-a-CursorAdapter