CursorLoader的進級實踐

CursorLoader的相關api,自行查詢官網android

實現效果: ContentPorvider狀況下的CurSorLoader自動刷新 官方規定:CursorLoader的API必須使用ContentProvider才能實現數據加載和自動刷新數據庫

自定義ContentProvier:api

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;
}

}ide

註冊contentProvider:this

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

自定義SQLiteOpenHelper:url

public class MySQLite extends SQLiteOpenHelper {code

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);
}

}rem

使用CursorLoader:get

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);
}

}

相關文章
相關標籤/搜索