manifest配置provider
<provider
android:name="CatProvider"
android:authorities="com.zeolite.contentprovider.data.Cat"
android:exported="true" />
继承content provider
public class CatProvider extends ContentProvider {
public static final String AUTHORITY = "com.zeolite.contentprovider.data.Cat";
private static final UriMatcher uriMatcher;
private static final int QUERY = 1;
private static final int INSERT = 1;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, "query", QUERY);
uriMatcher.addURI(AUTHORITY, "insert", INSERT);
}
@Override
public boolean onCreate() {
return true;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] strings1, @Nullable String s1) {
if (uriMatcher.match(uri) == QUERY)
return CatDataBase.getInstance(getContext()).catDao().query();
return null;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
if (uriMatcher.match(uri) == INSERT) {
if (contentValues.get("name") != null && contentValues.get("color") != null)
CatDataBase.getInstance(getContext()).catDao().add(new Cat(String.valueOf(contentValues.get("name")),
String.valueOf(contentValues.get("color"))));
}
return null;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
//省略...
return 0;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
//省略...
return 0;
}
}
数据库实体
@Entity
public class Cat {
@PrimaryKey(autoGenerate = true)
private long id;
@ColumnInfo(name = "name")
private String name;
@ColumnInfo(name = "color")
private String color;
public Cat(String name, String color) {
this.name = name;
this.color = color;
}
}
数据库操作
@Dao
public interface CatDao {
@Query("SELECT * FROM CAT")
Cursor query();
@Insert
void add(Cat cat);
@Delete
void delete(Cat cat);
@Update
void update(Cat cat);
}
数据库初始化
@Database(entities = {Cat.class}, version = 1)
public abstract class CatDataBase extends RoomDatabase {
private static CatDataBase instance;
public abstract CatDao catDao();
private static CatDataBase buildDataBase(Context context) {
return Room.databaseBuilder(context.getApplicationContext(),
CatDataBase.class, "cats.db")
.allowMainThreadQueries()
.build();
}
public static CatDataBase getInstance(Context context) {
if (instance == null) {
synchronized (CatDataBase.class) {
if (instance == null)
return buildDataBase(context);
}
}
return instance;
}
}
ContentResolver通过Uri查询数据
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.parse("content://com.zeolite.contentprovider.data.Cat/query");
Cursor cursor = contentResolver.query(uri, null, null, null, null);
while (cursor.moveToNext()) {
Log.d("name", cursor.getString(cursor.getColumnIndex("name")));
}
网友评论