1.实现一个ContentProvider.
public class DataProviders extends ContentProvider {
private static final String DATABASE_NAME = "UIDB";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "UITable"; public static String ID = "_id";
public static String NAME = "display_name";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
} @Override
public void onCreate(SQLiteDatabase db) {
Log.d("tag", "onCreate");
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT," + NAME + " TEXT" + ");");
} @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d("tag", "onUpgrade");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
}// ---------------------------------------------------------------------------------
private DatabaseHelper mOpenHelper;@Override
public boolean onCreate() {
mOpenHelper = new DatabaseHelper(getContext());
return true;
}@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Cursor c = db.query(TABLE_NAME, projection, selection, selectionArgs, null, null,
null);
return c;
}@Override
public String getType(Uri uri) {
return null;
}@Override
public Uri insert(Uri uri, ContentValues initialValues) {
Log.d("tag", "insert");
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
db.insert(TABLE_NAME, null, initialValues);
return uri;
}@Override
public int delete(Uri uri, String where, String[] whereArgs) {
Log.d("tag", "delete");
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
return db.delete(TABLE_NAME, where, whereArgs);
}@Override
public int update(Uri uri, ContentValues values, String where,
String[] whereArgs) {
Log.d("tag", "update");
getContext().getContentResolver().notifyChange(OServerActivity.CONTENT_URI, null);
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
return db.update(TABLE_NAME, values, where, whereArgs);
}2.Androidmanifest.xml文件中声明
<provider android:name=".DataProviders"
android:authorities="org.yihu.datachanage" />可定义provider权限
3.定义 Uri
4.在其它程序中访问
public class ShareDateActivity extends ListActivity {
public static final Uri CONTENT_URI = Uri.parse("content://org.yihu.datachanage");
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); Cursor c = getContentResolver().query(CONTENT_URI, null, null,
null, null); startManagingCursor(c);
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2, c,
new String[] { "_id", "display_name" },
new int[] { android.R.id.text1, android.R.id.text2 });
setListAdapter(adapter);
}
}
标签:String,NAME,db,数据共享,TABLE,android,null,public,ContentR
From: https://blog.51cto.com/u_3124497/6914308