码迷,mamicode.com
首页 > 移动开发 > 详细

Android_数据库_异步操作封装

时间:2014-10-11 18:06:15      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:数据库   数据   android   thread   异步   

/**
 * A particular {@link AsyncQueryHandler} allowing clients to be notified via a
 * listener. The {@link NotifyingAsyncQueryHandler} also make sure no strong
 * reference is kept on the given listener (as it is often a Context).
 * 
 */
public class DBAsyncHandler extends AsyncQueryHandler {

	private WeakReference<DBAsyncListener> mListener;

	/**
	 * Client may use this to listen to completed query operations. run on UI
	 * Thread
	 */
	public static class DBAsyncListener {
		public DBAsyncListener() {
		}

		/**
		 * run on UI Thread <br />
		 * <b>cursor close() method needn't be called</b>
		 */
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
		}

		protected void onInsertComplete(int token, Object cookie, Uri uri) {
		}

		protected void onUpdateComplete(int token, Object cookie, int result) {
		}

		protected void onDeleteComplete(int token, Object cookie, int result) {
		}
	}

	/**instance in UI Thread*/
	public DBAsyncHandler(ContentResolver resolver, DBAsyncListener listener) {
		super(resolver);
		setDBListener(listener);
	}

	/**
	 * Assign the given {@link DBAsyncListener}.
	 */
	public void setDBListener(DBAsyncListener listener) {
		mListener = (listener != null) ? new WeakReference<DBAsyncListener>(listener) : null;
	}

	private DBAsyncListener getDBListener() {
		return (mListener == null) ? null : mListener.get();
	}

	/** such as Activity-onDestory(), this method is called */
	public void clearDBListener() {
		mListener = null;
	}

	public void startQuery(int token, Object cookie, Uri uri, String[] projection, String selection, String[] selectionArgs, String orderBy) {
		super.startQuery(token, cookie, uri, projection, selection, selectionArgs, orderBy);
	}

	@Override
	protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
		DBAsyncListener listener = getDBListener();
		if (listener != null) {
			listener.onQueryComplete(token, cookie, cursor);
			if (cursor != null && !cursor.isClosed())
				cursor.close();
		} else if (cursor != null) {
			cursor.close();
		}
	}

	@Override
	protected void onDeleteComplete(int token, Object cookie, int result) {
		DBAsyncListener listener = getDBListener();
		if (listener != null) {
			listener.onDeleteComplete(token, cookie, result);
		}
	}

	@Override
	protected void onInsertComplete(int token, Object cookie, Uri uri) {
		DBAsyncListener listener = getDBListener();
		if (listener != null) {
			listener.onInsertComplete(token, cookie, uri);
		}
	}

	@Override
	protected void onUpdateComplete(int token, Object cookie, int result) {
		DBAsyncListener listener = getDBListener();
		if (listener != null) {
			listener.onUpdateComplete(token, cookie, result);
		}
	}
}
public class MyProvider extends ContentProvider {
	private final static String TAG = MyProvider.class.getSimpleName();

	private final static int Person = 1;

	public final static String BASE = "com.baidu.my.provider";
	public final static Uri URI_Person = Uri.parse("content://com.baidu.my.provider/Person");

	private final static UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH); // 如果都匹配不成功,则返回构造函数中指定的参数值,默认为-1
	private SQLiteDatabase db;
	static {
		MATCHER.addURI(BASE, "Person", Person);
	}

	@Override
	public boolean onCreate() {
		MyDBHelper dbHelper = new MyDBHelper(this.getContext());
		db = dbHelper.getWritableDatabase();
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		Cursor c = null;
		switch (MATCHER.match(uri)) {
		case Person:
			c = db.query(DBPerson.TableName, projection, selection, selectionArgs, null, null, sortOrder);
			c.setNotificationUri(getContext().getContentResolver(), URI_Person);
			break;
		default:
			break;
		}
		return c;
	}

	@Override
	public String getType(Uri uri) {
		switch (MATCHER.match(uri)) {
		case Person:
			return "vnd.android.cursor.dir/vnd." + BASE + ".request";
		default:
			break;
		}
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		long id = 0;
		switch (MATCHER.match(uri)) {
		case Person:
			id = db.insert(DBPerson.TableName, null, values);
			if (id > 0) {
				// 数据发生改变,发出通知
				getContext().getContentResolver().notifyChange(URI_Person, null);
			}
			return ContentUris.withAppendedId(uri, id);
		}
		return null;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}
}
public class MyDBHelper extends SQLiteOpenHelper {
	private static final String TAG = "DBHelper";

	private static final String DB_NAME = "my.db";
	
	private static final int DB_VERSION = /**/ 57 /**/;/****谨慎修改,否则将导致用户历史数据被删除****/

	public MyDBHelper(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(getRequestCreateStr());
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS " + DBPerson.TableName);
		onCreate(db);
	}

	private String getRequestCreateStr() {
		StringBuffer sb = new StringBuffer();
		sb.append("CREATE TABLE ").append(DBPerson.TableName);
		sb.append(" (");
		sb.append(BaseColumns._ID).append(" INTEGER PRIMARY KEY,");
		sb.append(DBPerson.MetaDate.Name).append(" TEXT,");
		sb.append(DBPerson.MetaDate.Age).append(" TEXT)");

		return sb.toString();
	}

}
public interface DBPerson extends BaseDB{
	public interface MetaDate {
		String Name = "Name";
		String Age = "Age";
	}

	public String TableName = "Person";
	
	public String[] PROJECTION = { 
			MetaDate.Name, MetaDate.Age
	};
	
	public String SORT_ORDER = MetaDate.Age + " ASC";
}
public class MainActivity extends Activity {
	private DBAsyncHandler dbAsyncHandler;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		//
		dbAsyncHandler = new DBAsyncHandler(getContentResolver(), dbListener);
	}

	private DBAsyncHandler.DBAsyncListener dbListener = new DBAsyncListener() {
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			Toast.makeText(getApplicationContext(), "ok = " + cursor.getCount(), 1).show();
		}
		protected void onInsertComplete(int token, Object cookie, android.net.Uri uri) {
			Toast.makeText(getApplicationContext(), "插入ok!", 1).show();
		}
	};
	public void query(View view) {
		//query
		dbAsyncHandler.startQuery(100, null, MyProvider.URI_Person, DBPerson.PROJECTION, null, null, DBPerson.SORT_ORDER);
	}

	public void insert(View view) {
		//insert
		ContentValues initialValues = new ContentValues();
		initialValues.put(DBPerson.MetaDate.Name, "baidu");
		initialValues.put(DBPerson.MetaDate.Age, System.currentTimeMillis());
		dbAsyncHandler.startInsert(100, null, MyProvider.URI_Person, initialValues);
	}
	@Override
	protected void onDestroy() {
		//clear
		dbAsyncHandler.clearDBListener();
		super.onDestroy();
	}
}

源码下载》》

Android_数据库_异步操作封装

标签:数据库   数据   android   thread   异步   

原文地址:http://blog.csdn.net/zimo2013/article/details/39993373

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!