在Android开发中,使用SQLite嵌入式数据库时,你可以通过创建自定义`ContentProvider`来实现跨应用的数据共享
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyCustomContentProvider extends ContentProvider {
private SQLiteOpenHelper dbHelper;
@Override
public boolean onCreate() {
dbHelper = new SQLiteOpenHelper(getContext(), "myDatabase.db", null, 1) {
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE myTable (_id INTEGER PRIMARY KEY, name TEXT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 更新数据库的逻辑
}
};
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
return db.query("myTable", projection, selection, selectionArgs, null, null, sortOrder);
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
long id = db.insert("myTable", null, values);
return Uri.parse("content://com.example.authority/myTable/" + id);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
return db.delete("myTable", selection, selectionArgs);
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
return db.update("myTable", values, selection, selectionArgs);
}
@Override
public String getType(Uri uri) {
// 根据Uri返回MIME类型
return "vnd.android.cursor.dir/vnd.com.example.myTable";
}
}
这个示例代码展示了如何创建一个自定义的ContentProvider
,它使用SQLite数据库并提供了基本的CRUD操作。在实际的应用中,你需要根据具体的需求来实现这些方法。
评论已关闭