例子展示
代码块
DatabaseAdapter
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class DatabaseAdapter {
private DatabaseHelper dbHelper;
public DatabaseAdapter(Context context){
dbHelper=new DatabaseHelper(context);
}
public void save(Person person){
SQLiteDatabase db=dbHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(PersonMetadata.Person.NAME,person.getName());
values.put(PersonMetadata.Person.AGE,person.getAge());
db.insert(PersonMetadata.Person.TABLE_NAME,null,values);
db.close();
}
public void delete(int id){
SQLiteDatabase db=dbHelper.getWritableDatabase();
db.delete(PersonMetadata.Person.TABLE_NAME, PersonMetadata.Person._ID+"=?",new String[]{String.valueOf(id)});
db.close();
}
public void update(Person person){
SQLiteDatabase db=dbHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(PersonMetadata.Person.NAME,person.getName());
values.put(PersonMetadata.Person.AGE,person.getAge());
String where=PersonMetadata.Person._ID+"=?";
String[] args={String.valueOf(person.getId())};
db.update(PersonMetadata.Person.TABLE_NAME,values,where,args);
db.close();
}
public ArrayList<Person> findAll(){
SQLiteDatabase db= dbHelper.getReadableDatabase();
Cursor c= db.query(PersonMetadata.Person.TABLE_NAME,null,null,null,null,null,null);
ArrayList<Person> list=new ArrayList<>();
Person person=null;
while (c.moveToNext()){
person=new Person();
person.setId(c.getInt(c.getColumnIndex(PersonMetadata.Person._ID)));
person.setName(c.getString(c.getColumnIndex(PersonMetadata.Person.NAME)));
person.setAge(c.getInt(c.getColumnIndex(PersonMetadata.Person.AGE)));
list.add(person);
}
c.close();
db.close();
return list;
}
public Cursor list(){
SQLiteDatabase db= dbHelper.getReadableDatabase();
Cursor c= db.query(PersonMetadata.Person.TABLE_NAME,null,null,null,null,null,null);
return c;
}
public Person findById(int id){
SQLiteDatabase db= dbHelper.getReadableDatabase();
Cursor c= db.query(PersonMetadata.Person.TABLE_NAME,null,PersonMetadata.Person._ID+"=?",new String[]{String.valueOf(id)},null,null,null);
Person person=null;
if (c.moveToNext()){
person=new Person();
person.setId(c.getInt(c.getColumnIndex(PersonMetadata.Person._ID)));
person.setName(c.getString(c.getColumnIndex(PersonMetadata.Person.NAME)));
person.setAge(c.getInt(c.getColumnIndex(PersonMetadata.Person.AGE)));
}
c.close();
db.close();
return person;
}
public static class DatabaseHelper extends SQLiteOpenHelper{
private static final String DB_NAME="cp.db";
private static final int VERSION=1;
private static final String CREATE_TABLE="CREATE TABLE person(_id integer primary key autoincrement,name text,age int)";
private static final String DROP_TABLE="DROP TABLE IF EXISTS person";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
db.execSQL(CREATE_TABLE);
}
}
}
HelloContentProvider
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
/**
* 自定义ContentProvider
*/
public class HelloContentProvider extends ContentProvider {
private static final String authority="com.example.HelloContentProvider";
//创建一个URI的匹配器,
private static UriMatcher uriMatcher=new UriMatcher(UriMatcher.NO_MATCH);
private static final int single_code=2;//返回单个记录的匹配码
private static final int mutiple_code=1;//返回多个记录的匹配码
//text/plain image/jpg
private static final String SINGLE_TYPE="vnd.android.cursor.item/person";
private static final String MUTIPLE_TYPE="vnd.android.cursor.dir/person";
static {
uriMatcher.addURI(authority,"person",mutiple_code);
uriMatcher.addURI(authority,"person/#",single_code);
}
private DatabaseAdapter.DatabaseHelper dbHelper;
@Override
public boolean onCreate() {
dbHelper=new DatabaseAdapter.DatabaseHelper(getContext());
return false;
}
@Override
public Cursor query(Uri uri, String[] projection,String selection,String[] selectionArgs,String sortOrder) {
switch (uriMatcher.match(uri)){
case single_code:
SQLiteDatabase db=dbHelper.getReadableDatabase();
long id=ContentUris.parseId(uri);
selection= PersonMetadata.Person._ID+"=?";
selectionArgs=new String[]{String.valueOf(id)};
return db.query(PersonMetadata.Person.TABLE_NAME,projection,selection,selectionArgs,null,null,sortOrder);
case mutiple_code:
db=dbHelper.getReadableDatabase();
return db.query(PersonMetadata.Person.TABLE_NAME,projection,selection,selectionArgs,null,null,sortOrder);
}
return null;
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)){
case single_code:
return SINGLE_TYPE;
case mutiple_code:
return MUTIPLE_TYPE;
}
return null;
}
@Override
public Uri insert(Uri uri,ContentValues values) {
switch (uriMatcher.match(uri)){
case mutiple_code:
SQLiteDatabase db=dbHelper.getWritableDatabase();
long id=db.insert(PersonMetadata.Person.TABLE_NAME,null,values);
uri=ContentUris.withAppendedId(uri,id);
db.close();
break;
}
return uri;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
switch (uriMatcher.match(uri)){
case single_code:
SQLiteDatabase db=dbHelper.getWritableDatabase();
long id=ContentUris.parseId(uri);
selection= PersonMetadata.Person._ID+"=?";
selectionArgs=new String[]{String.valueOf(id)};
int row=db.delete(PersonMetadata.Person.TABLE_NAME,selection,selectionArgs);
db.close();
return row;
case mutiple_code:
db=dbHelper.getWritableDatabase();
row=db.delete(PersonMetadata.Person.TABLE_NAME,selection,selectionArgs);
db.close();
return row;
}
return 0;
}
@Override
public int update( Uri uri, ContentValues values, String selection, String[] selectionArgs) {
switch (uriMatcher.match(uri)){
case single_code:
SQLiteDatabase db=dbHelper.getWritableDatabase();
long id=ContentUris.parseId(uri);
selection= PersonMetadata.Person._ID+"=?";
selectionArgs=new String[]{String.valueOf(id)};
int row=db.update(PersonMetadata.Person.TABLE_NAME,values,selection,selectionArgs);
db.close();
return row;
case mutiple_code:
db=dbHelper.getWritableDatabase();
row=db.update(PersonMetadata.Person.TABLE_NAME,values,selection,selectionArgs);
db.close();
return row;
}
return 0;
}
}
Person
public class Person {
private int id;
private String name;
private int age;
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
PersonMetadata
import android.provider.BaseColumns;
public final class PersonMetadata {
public static abstract class Person implements BaseColumns {
public static final String TABLE_NAME="person";
public static final String NAME="name";
public static final String AGE="age";
}
}
MainActivity
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private DatabaseAdapter dbAdapter;
SimpleCursorAdapter dataAdapter;
CursorLoader loader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbAdapter=new DatabaseAdapter(this);
ListView lv=findViewById(R.id.listView);
dataAdapter=new SimpleCursorAdapter(this,R.layout.list_item,
dbAdapter.list(),
new String[]{PersonMetadata.Person._ID, PersonMetadata.Person.NAME, PersonMetadata.Person.AGE},
new int[]{R.id.textView_id,R.id.textView2_name,R.id.textView3_age},
SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
lv.setAdapter(dataAdapter);
//初始化一个Loader(id,bundler参数,回调接口)
getSupportLoaderManager().initLoader(0,null,this);
}
public void addClick(View v){
dbAdapter.save(new Person("ck",18));
//重启加载器
// getSupportLoaderManager().restartLoader(0,null,this);
// loader.commitContentChanged();api 18可用
loader.onContentChanged();//内容发生变化,通知加载器
}
@NonNull
@Override
public Loader<Cursor> onCreateLoader(int i, @Nullable Bundle bundle) {
System.out.println("onCreateLoader");
Uri uri=Uri.parse("content://com.example.HelloContentProvider/person");
//创建一个游标加载器(上下文,CP的URI,要查询的列数组,查询条件,查询条件的值,排序条件)
loader=new CursorLoader(this,uri,null,null,null,null);
return loader;
}
@Override
public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor data) {
System.out.println("onLoadFinished");
dataAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(@NonNull Loader<Cursor> loader) {
System.out.println("onLoaderReset");
dataAdapter.swapCursor(null);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:onClick="addClick"
android:layout_marginStart="0dp"
android:layout_marginTop="0dp"
android:text="add" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:id="@+id/listView"
android:layout_marginStart="0dp"
android:layout_marginTop="64dp" />
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />
<TextView
android:id="@+id/textView2_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />
<TextView
android:id="@+id/textView3_age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />
</LinearLayout>