天天看點

Android ContentProvider 和 SQLite 資料庫的簡單使用

這裡隻是簡單記錄一下怎麼使用ContentProvider 和 SQLite 資料庫.

多程序通信的時候也可以利用 ContentResolver 的query()/delete()/insert()/insert() 來擷取資料,也可以通過call()傳遞不同的參數實作不同的意義.

1.建立資料庫

public class NameListDBHelper extends SQLiteOpenHelper {
	private final static String TAG = "NameListDataBaseHelper";
	
	private static NameListDBHelper mInstance;
	private final String CREATE_NAME_LIST_TABLE = "create table " + TABLE_NAME + " (" +
             "id integer primary key autoincrement, " +
             "pkg text, " +
             "type text)";
	private final static int DB_VERSION = 1;
	
	public final static String TABLE_NAME = "smallwindow";
	
	private NameListDBHelper(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
	}
	
	public static synchronized NameListDBHelper getInstance(Context context) {
		if(mInstance == null) {
			mInstance = new NameListDBHelper(context, "name_list.db", null, DB_VERSION);
		}
		return mInstance;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		Log.i(TAG, "onCreate DB , DB_VERSION=" + DB_VERSION);
		db.execSQL(CREATE_NAME_LIST_TABLE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.i(TAG, "onUpgrade , oldVersion=" + oldVersion + " newVersion=" + newVersion);

	}

	public void add(List<AppInfo> infos) {
		if(infos != null) {
			SQLiteDatabase db = mInstance.getWritableDatabase();
			db.delete(TABLE_NAME, null, null);
			for (AppInfo info : infos) {
				ContentValues values = new ContentValues();
				values.clear();
				values.put("pkg", info.getPkg());
				values.put("type", info.getType());
				db.insert(TABLE_NAME, null, values);
			} 
		}
	}
}
           

2.實作ContentProvider 

public class NameListProvider extends ContentProvider {
	private final static String TAG = "NameListProvider";
	
	private SQLiteDatabase db = null;
	private static UriMatcher MATCHER =  new UriMatcher(UriMatcher.NO_MATCH);
	private final static String AUTHORITY = "cn.nubia.smallwindow.provider";
	private final static  int APPINFO = 1;
	private final static int APPINFOS = 2;
	private final static String TABLE = NameListDBHelper.TABLE_NAME;
	
	public final static Uri all_name_uri = Uri.parse("content://" + AUTHORITY + "/appinfo");

	static {
		MATCHER.addURI(AUTHORITY, "appinfo/#", APPINFO);
		MATCHER.addURI(AUTHORITY, "appinfo", APPINFOS);
	}

	@Override
	public boolean onCreate() {
		db = NameListDBHelper.getInstance(getContext()).getWritableDatabase();
		return db != null;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		int matchType = MATCHER.match(uri);
		Cursor cursor = null;
		switch (matchType) {
		case APPINFO:
			String queryPkg = uri.getPathSegments().get(1);
			cursor = db.query(TABLE, projection, "pkg=?", new String[] {queryPkg}, null, null, null);
			break;
		case APPINFOS:
			cursor = db.query(TABLE, projection, selection, selectionArgs, null, null, null);
			break;

		default:
			break;
		}
		return cursor;
	}

	@Override
	public String getType(Uri uri) {
		switch(MATCHER.match(uri)){
		case APPINFO:
			return "vnd.android.cursor.dir/appinfo";
		case APPINFOS:
			return "vnd.android.cursor.item/appinfo";
		default:
			throw new IllegalArgumentException("Unknow Uri:"+uri.toString());
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		Log.i(TAG, "insert");
		int matchType = MATCHER.match(uri);
		Log.i(TAG, "insert matchType=" + matchType);
		switch (matchType) {
		case APPINFO:
		case APPINFOS:
			long rowId = db.insert(TABLE, null, values);
			if(rowId == -1) {
				Log.i(TAG, "insert failed");
			}
			break;
		default:
			break;
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return null;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		int matchType = MATCHER.match(uri);
		int rowId = 0;
		switch (matchType) {
		case APPINFO:
		case APPINFOS:
			rowId = db.delete(TABLE, selection, selectionArgs);
			if(rowId == -1) {
				Log.i(TAG, "delete failed");
			}
			break;
		default:
			break;
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return rowId;
	}

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

}
           

3.測試

public class TestNameActivity extends Activity implements OnClickListener {
	private final static String TAG = "TestNameActivity";
	
	private Button mQueryAll;
	private Button mRemoveAll;
	private Button mInitAll;
	private Button mAddOne;
	private Button mRemoveOne;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.namelist);
		mQueryAll = this.findViewById(R.id.query_all);
		mQueryAll.setOnClickListener(this);
		
		mRemoveAll = this.findViewById(R.id.remove_all);
		mRemoveAll.setOnClickListener(this);
		
		mInitAll = this.findViewById(R.id.init_all);
		mInitAll.setOnClickListener(this);
		
		mAddOne = this.findViewById(R.id.add_one);
		mAddOne.setOnClickListener(this);
		
		mRemoveOne = this.findViewById(R.id.remove_one);
		mRemoveOne.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		ContentResolver resolver = getContentResolver();
		if(v.getId() == R.id.query_all) {
			Cursor cursor = resolver.query(NameListProvider.all_name_uri, null, null, null);
			boolean hasFirst = cursor.moveToFirst();
			try {
				if(hasFirst) {
					do {
						String pkg = cursor.getString(cursor.getColumnIndex("pkg"));
						String type = cursor.getString(cursor.getColumnIndex("type"));
						Log.i(TAG, " pkg=" + pkg + " type=" + type);
					} while (cursor.moveToNext());
				}else {
					Log.i(TAG, "無資料,請先初始化資料");
				}
			} finally {
				cursor.close();
			}

			try {
				Thread.currentThread().sleep(10 * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}else if(v.getId() == R.id.remove_all) {
			int rowId = resolver.delete(NameListProvider.all_name_uri, null, null);
		}else if(v.getId() == R.id.init_all) {
			Intent i = new Intent();
			i.setAction("cn.nubia.small_window_namelist_update");
			sendBroadcast(i);
		}else if(v.getId() == R.id.add_one) {//add_one
			ContentValues values = new ContentValues();
			values.put("pkg", "test_add_one");
			values.put("type", "test_add_one" + Math.random());
			resolver.insert(NameListProvider.all_name_uri, values);
		}else if(v.getId() == R.id.remove_one) {//add_one
			String where = "pkg = ?";
			String[] args = new String[] {"test_add_one"};
			int rowId = resolver.delete(NameListProvider.all_name_uri, where, args);
		}
	}
}