CursorLoader的进级实践

原创
2016/01/28 17:34
阅读数 82

CursorLoader的相关api,自行查询官网

实现效果: ContentPorvider情况下的CurSorLoader自动刷新 官方规定:CursorLoader的API必须使用ContentProvider才能实现数据加载和自动刷新

自定义ContentProvier:

public class MyContentProvider extends ContentProvider {

/*	 * 
 * 数据库发生改变时如何自动更新UI
 *  过程:数据库---contentprovider/contentresolver
 *             ---cursor的观察者-数据源发生改变
 *             ---cursorloader重新加载数据
 *             ---cursoradapter的changercursor提换数据
 *  做法:
 *  1. 对cursor数据设置监听的url,即在contentprovider中query()调用
                                   (或者loader的loadeingbackground())调用cursor.setNotificationUri()
 *  2.ContentProvider的insert()、update()、delete()等方法中调用ContentResolver的notifyChange()方法
 */

public static final int TABLE1_DIR = 0;
public static final int TABLE1_ITEM = 1;
public static final String AUTHORITY = "com.example.datebasedemo.provider";
private static UriMatcher uriMatcher;
private MySQLite dbHelper;
static {
	uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
	uriMatcher.addURI(AUTHORITY, MySQLite.TABLENAME, TABLE1_DIR);
	uriMatcher.addURI(AUTHORITY, MySQLite.TABLENAME + "/#", TABLE1_ITEM);
}

@Override
public boolean onCreate() {
	dbHelper = new MySQLite(getContext());
	return true;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection,
		String[] selectionArgs, String sortOrder) {
	SQLiteDatabase db = dbHelper.getReadableDatabase();
	Cursor cursor = null;
	switch (uriMatcher.match(uri)) {
	case TABLE1_DIR:
		cursor = db.query(MySQLite.TABLENAME, projection, selection,
				selectionArgs, null, null, sortOrder);
		break;
	case TABLE1_ITEM:
		String bookId = uri.getPathSegments().get(1);
		cursor = db.query(MySQLite.TABLENAME, projection,
				MySQLite.COLUMN_ID + "= ?", new String[] { bookId }, null,
				null, sortOrder);
		break;

	default:
		break;
	}
	/*
	 * 在query()设置NotificationUri监听
	 * 缺点:上千次并发调用会造成gc操作
	 * 
	 */
	if (cursor != null) {
		cursor.setNotificationUri(getContext().getContentResolver(), uri);
	}
	return cursor;
}

@Override
public Uri insert(Uri uri, ContentValues values) {
	SQLiteDatabase db = dbHelper.getWritableDatabase();
	Uri uriReturn = null;
	switch (uriMatcher.match(uri)) {
	case TABLE1_DIR:
	case TABLE1_ITEM:
		long newTableId = db.insert(MySQLite.TABLENAME, null, values);
		uriReturn = Uri.parse("content://" + AUTHORITY + "/"
				+ MySQLite.TABLENAME + "/" + newTableId);
		break;

	default:
		break;
	}
	getContext().getContentResolver().notifyChange(uri, null);
	return uriReturn;
}

@Override
public int update(Uri uri, ContentValues values, String selection,
		String[] selectionArgs) {
	SQLiteDatabase db = dbHelper.getWritableDatabase();
	int updatedRows = 0;
	switch (uriMatcher.match(uri)) {
	case TABLE1_DIR:
		updatedRows = db.update(MySQLite.TABLENAME, values, selection,
				selectionArgs);
		break;
	case TABLE1_ITEM:
		String bookId = uri.getPathSegments().get(1);
		updatedRows = db.update(MySQLite.TABLENAME, values,
				MySQLite.COLUMN_ID + "= ?", new String[] { bookId });
		break;
	}
	if (updatedRows > 0) {
		getContext().getContentResolver().notifyChange(uri, null);
	}
	return updatedRows;
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {

	SQLiteDatabase db = dbHelper.getWritableDatabase();
	int deletedRows = 0;
	switch (uriMatcher.match(uri)) {
	case TABLE1_DIR:
		deletedRows = db.delete(MySQLite.TABLENAME, selection,
				selectionArgs);
		break;
	case TABLE1_ITEM:
		String bookId = uri.getPathSegments().get(1);
		deletedRows = db.delete(MySQLite.TABLENAME, MySQLite.COLUMN_ID
				+ "= ?", new String[] { bookId });
		break;
	}
	getContext().getContentResolver().notifyChange(uri, null);
	return deletedRows;
}

@Override
public String getType(Uri uri) {

	switch (uriMatcher.match(uri)) {
	case TABLE1_DIR:
		return "vnd.android.cursor.dir/vnd." + AUTHORITY
				+ MySQLite.TABLENAME;

	case TABLE1_ITEM:
		return "vnd.android.cursor.item/vnd." + AUTHORITY
				+ MySQLite.TABLENAME;
	default:
		break;
	}
	return null;
}

}

注册contentProvider:

 <provider 
        android:name="com.example.datebasedemo.db.MyContentProvider"
        android:authorities="com.example.datebasedemo.provider">
    </provider>

自定义SQLiteOpenHelper:

public class MySQLite extends SQLiteOpenHelper {

public static final String DATABASENAME = "Book.db";
public static final String TABLENAME = "Book";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_ID = "_id";
public static final String CRATETABLE_SQL = "create table " + MySQLite.TABLENAME
		+ "(" + MySQLite.COLUMN_ID + " integer primary key autoincrement, "
		+ MySQLite.COLUMN_NAME + " text" + ")";

public MySQLite(Context context) {
	super(context, MySQLite.DATABASENAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
	db.execSQL(CRATETABLE_SQL);
	Log.i("database", "create");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVerson, int newVerson) {
                  db.execSQL("drop  table if exists "+TABLENAME);
                  onCreate(db);
}

}

使用CursorLoader:

public class Zixuan_Fragment extends Fragment implements LoaderCallbacks<Cursor> {

private List<String> list = new ArrayList<String>();
private ListView listView;
private LinearLayout lin;
private ImageView img_add;
private SimpleCursorAdapter mCursorAdapter;
private View view;



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
		Bundle savedInstanceState) {
	getLoaderManager().initLoader(0, null, this);
	view = inflater.inflate(R.layout.zixuan_fragment, null);
	initViews(view);
	initListview(view);
	return view;
}

private void initListview(View view) {
	listView = (ListView) view.findViewById(R.id.zixuan_listview);
	mCursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.item,
			null, new String[] { MySQLite.COLUMN_NAME },
			new int[] { R.id.item }, 0);
	listView.setAdapter(mCursorAdapter);

}

private void initViews(View v) {
	lin = (LinearLayout) v.findViewById(R.id.add_content);
	img_add = (ImageView) v.findViewById(R.id.addImg);
	img_add.setOnClickListener(new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			startActivity(new Intent(getActivity(), Manager.class));
		}
	});
}



@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
	return new android.support.v4.content.CursorLoader(getActivity(),ContentController.uri,
		new String[]{MySQLite.COLUMN_ID,MySQLite.COLUMN_NAME}, null, null, null);
}

@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
	mCursorAdapter.swapCursor(cursor);

}

@Override
public void onLoaderReset(Loader<Cursor> arg0) {
	mCursorAdapter.swapCursor(null);
}

}

展开阅读全文
打赏
1
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
1
分享
返回顶部
顶部