編輯:關於Android編程
ContentProvider為存儲和讀取數據提供了統一的接口,使用ContentProvider,應用程序可以實現數據共享,android內置的許多數據都是使用ContentProvider形式,供開發者調用的(如視頻,音頻,圖片,通訊錄等)。
本實例將SQLite作為存儲數據的方式。
Activity代碼:<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+CjwvcD4KPHByZSBjbGFzcz0="brush:java;">protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content_provider);
insertButton = (Button) findViewById(R.id.insertButton);
updateButton = (Button) findViewById(R.id.updateButton);
deleteButton = (Button) findViewById(R.id.deleteButton);
queryButton = (Button) findViewById(R.id.queryButton);
insertButton.setOnClickListener(new InsertListener());
updateButton.setOnClickListener(new UpdateListener());
deleteButton.setOnClickListener(new DeleteListener());
queryButton.setOnClickListener(new QueryListener());
}
class InsertListener implements OnClickListener {
@Override
public void onClick(View v) {
ContentValues[] values = new ContentValues[2];
ContentValues value = new ContentValues();
value.put(CPMetadata.users.NAME, "張三");
value.put(CPMetadata.users.AGE, 12);
values[0] = value;
value = new ContentValues();
value.put(CPMetadata.users.NAME, "李四");
value.put(CPMetadata.users.AGE, 11);
values[1] = value;
//多條插入,調用DemoProvider的insert(),每條調用一次,結果返回成功行數
int count = getContentResolver().bulkInsert(CPMetadata.users.CONTENT_URI, values);
// 插入單條數據
// Uri uri =
// getContentResolver().insert(CPMetadata.users.CONTENT_URI, values);
// Log.d("ContentProvider", "uri : " + uri);
Log.d("ContentProvider", "count : " + count);
}
}
class UpdateListener implements OnClickListener {
@Override
public void onClick(View v) {
//要更新的數據
ContentValues values = new ContentValues();
values.put(CPMetadata.users.NAME, "趙六");
values.put(CPMetadata.users.AGE, 22);
//根據ID更新,ContentUris.withAppendedId() 方法在URI的結尾追加一個1
Uri uri = ContentUris.withAppendedId(CPMetadata.users.CONTENT_URI, 1);
int count = getContentResolver().update(uri, values, null, null);
Log.d("ContentProvider", "update rows : " + count);
}
}
class DeleteListener implements OnClickListener {
@Override
public void onClick(View v) {
//根據ID刪除,ContentUris.withAppendedId() 方法在URI的結尾追加一個2
Uri uri = ContentUris.withAppendedId(CPMetadata.users.CONTENT_URI, 2);
int count = getContentResolver().delete(uri, null, null);
Log.d("ContentProvider", "delete rows : " + count);
}
}
class QueryListener implements OnClickListener {
@Override
public void onClick(View v) {
//根據ID查詢使用此uri,ContentUris.withAppendedId() 方法在URI的結尾追加一個1
//Uri uri = ContentUris.withAppendedId(CPMetadata.users.CONTENT_URI, 1);
//更新和刪除數據使用where子句方法同理
Cursor cursor = getContentResolver().query(CPMetadata.users.CONTENT_URI, null
, CPMetadata.users.NAME + "=?", new String[]{"張三"}, CPMetadata.users._ID + " desc");
//根據游標打印查詢結果
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(CPMetadata.users._ID));
String name = cursor.getString(cursor.getColumnIndex(CPMetadata.users.NAME));
String age = cursor.getString(cursor.getColumnIndex(CPMetadata.users.AGE));
Log.d("ContentProvider", "ID : " + id + " NAME : " + name + " AGE : " + age);
}
cursor.close();
}
}
CPMetadata代碼:
public class CPMetadata { public static final String AUTHORITY = "com.example.olds1_contentprovider.DemoProvider"; public static final String DATABASE_NAME = "DemoProviderDB"; public static final int DATABASE_VERSION = 1; public static final int CONTENT = 1; public static final int CONTENT_ITEM = 2; public static final class users implements BaseColumns { public static final String TABLE_NAME = "users"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/users"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.demoprovider.user"; public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/vnd.demoprovider.user"; public static final String NAME = "name"; public static final String AGE = "age"; } }
public class DBHelper extends SQLiteOpenHelper{ public DBHelper(Context context) { super(context, CPMetadata.DATABASE_NAME, null, CPMetadata.DATABASE_VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { StringBuffer sql = new StringBuffer(); sql.append("create table " + CPMetadata.users.TABLE_NAME + "("); sql.append(CPMetadata.users._ID + " integer primary key autoincrement,"); sql.append(CPMetadata.users.NAME + " varchar(20),"); sql.append(CPMetadata.users.AGE + " integer);"); db.execSQL(sql.toString()); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } }
public class DemoProvider extends ContentProvider { private DBHelper helper; private SQLiteDatabase db; private static final UriMatcher uriMatcher; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(CPMetadata.AUTHORITY, CPMetadata.users.TABLE_NAME, CPMetadata.CONTENT); uriMatcher.addURI(CPMetadata.AUTHORITY, CPMetadata.users.TABLE_NAME + "/#", CPMetadata.CONTENT_ITEM); } @Override public boolean onCreate() { helper = new DBHelper(getContext()); db = helper.getWritableDatabase(); return true; } @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case CPMetadata.CONTENT: return CPMetadata.users.CONTENT_TYPE; case CPMetadata.CONTENT_ITEM: return CPMetadata.users.CONTENT_TYPE_ITEM; default: throw new IllegalArgumentException("unknown URI:" + uri); } } /** * 整理where子句 * 條件分為有ID和無ID兩種,ID為主鍵具有唯一性,不用添加其他條件 * 無ID則使用傳入的條件處理 * @param uri * @param selection * @return */ public String getWhereStr(Uri uri, String selection){ String whereStr; switch (uriMatcher.match(uri)) { case CPMetadata.CONTENT: whereStr = selection; break; case CPMetadata.CONTENT_ITEM: whereStr = CPMetadata.users._ID + "=" + uri.getPathSegments().get(1); break; default: throw new IllegalArgumentException("unknown URI :" + uri); } return whereStr; } @Override public Uri insert(Uri uri, ContentValues values) { long rowid = db.insert(CPMetadata.users.TABLE_NAME, null, values); if (rowid > 0) { Uri insertUri = ContentUris.withAppendedId(CPMetadata.users.CONTENT_URI, rowid); getContext().getContentResolver().notifyChange(insertUri, null); Log.d("ContentProvider", "Insert Success :" + insertUri); return insertUri; } throw new IllegalArgumentException("unknown URI: " + uri); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { int count = 0; String whereStr = getWhereStr(uri, selection); Log.d("ContentProvider", "Delete Where :" + whereStr); count = db.delete(CPMetadata.users.TABLE_NAME, whereStr, selectionArgs); getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int count = 0; String whereStr = getWhereStr(uri, selection); Log.d("ContentProvider", "Update Where :" + whereStr); count = db.update(CPMetadata.users.TABLE_NAME, values, whereStr, selectionArgs); getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { Cursor cursor; String whereStr = getWhereStr(uri, selection); Log.d("ContentProvider", "Query Where :" + whereStr); cursor = db.query(CPMetadata.users.TABLE_NAME, projection, whereStr, selectionArgs, null, null, sortOrder); cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; }
android:exported="true"表示是否允許外部應用訪問,必須設置
效果:
Activity代碼如下:
private Button button; private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button)findViewById(R.id.button); textView = (TextView)findViewById(R.id.textView); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String uriStr = "content://com.example.olds1_contentprovider.DemoProvider/users"; Uri uri = Uri.parse(uriStr); Cursor cursor = getContentResolver().query(uri, null, "name=?", new String[]{"張三"}, null); StringBuffer show = new StringBuffer(); //根據游標打印查詢結果 while (cursor.moveToNext()) { String id = cursor.getString(cursor.getColumnIndex("_id")); String name = cursor.getString(cursor.getColumnIndex("name")); String age = cursor.getString(cursor.getColumnIndex("age")); show.append("ID : " + id + " NAME : " + name + " AGE : " + age + "\n"); } cursor.close(); textView.setText(show.toString()); } }); }
完整代碼下載地址:
點我下載實例
百學須先立志—學前須知:在我們平時加載圖片(不管是下載還是加載本地圖片…..)的時候,我們經常會遇到這樣一個需求,那就是當圖片正在加載時應該呈現
1.android為什麼要簽名 所有的Android應用程序都要求開發人員用一個證書進行數字簽名,anroid系統不會安裝沒有進行簽名的由於程序。平時我們的程序可
Auticompelete TextView動態匹配輸入的內容:目的,動態匹配輸入的內容,如百度搜索引擎當輸入文本時可以根據內容顯示匹配的熱門信息。一.目的效果圖:實驗效
通常,我們在開發過程中,總是需要兩套以上的環境進行測試、生產發布。如果只是簡簡單單的進行一個API的切換,那麼只是進行不同的宏定義即可,但是要求應用的不同版本將使用相同的