ContentResolver和ContentProvider通过相同的URI联系,实现数据共享。我重写了public class MyAdapter extends BaseAdapter,putData(),然后listview.setAdapter(myAdapter)显示数据。edit layout用来安排显示数据的格式。主要代码来自《安卓编程兵书》p311。完整的URI如下,"content://"+AUTHORITY+"/books",books是图书信息表的名字,AUTHORITY定义如下:
public static final String AUTHORITY="lmy.com.bookinfo_provider"
1.CotentProvider
//《安卓变成兵书》p311
//sample_8_6.java
package lmy.com.sample_8_6;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;
public class Sample_8_6 extends ContentProvider{
private DB_helper dbhelper = null;
private static UriMatcher sUriMatcher =null;
private static final int BOOKS_RECORDS = 1;
private static final int BOOKS_RECORD =2;
static{
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(Bookinfo_provider.AUTHORITY,"books",BOOKS_RECORDS);
sUriMatcher.addURI(Bookinfo_provider.AUTHORITY,"books/#",BOOKS_RECORD);
}
@Override
public boolean onCreate(){
dbhelper = new DB_helper(this.getContext());
return true;
}
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.androidbook.book";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.androidbook.book";
@Override
public String getType(Uri uri){
//TODO Auto-generated method stub
switch(sUriMatcher.match(uri)) {
case BOOKS_RECORDS:
return Bookinfo_provider.Bookinfo.CONTENT_TYPE;
case BOOKS_RECORD:
return Bookinfo_provider.Bookinfo.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Uknown URI "+uri);
}
}
@Override
public Uri insert(Uri uri,ContentValues values){
if(sUriMatcher.match(uri)!=BOOKS_RECORDS){
throw new IllegalArgumentException("Unknown URI "+uri);
}
if(!values.containsKey(Bookinfo_provider.Bookinfo.BOOK_NAME)){
throw new SQLException("Failed to insert,please input Book name"+uri);
}
if(!values.containsKey(Bookinfo_provider.Bookinfo.BOOK_ISBN)){
values.put(Bookinfo_provider.Bookinfo.BOOK_ISBN,"Unknown ISBN");
}
if(!values.containsKey(Bookinfo_provider.Bookinfo.BOOK_AUTHOR)){
values.put(Bookinfo_provider.Bookinfo.BOOK_AUTHOR,"Unknown author");
}
SQLiteDatabase db = dbhelper.getWritableDatabase();
long rowID = db.insert(Bookinfo_provider.Bookinfo.TABLE_NAME,Bookinfo_provider.Bookinfo.BOOK_NAME,values);
if(rowID>0){
Uri insertBookedUri = ContentUris.withAppendedId(
Bookinfo_provider.Bookinfo.CONTENT_URI,rowID);
getContext().getContentResolver().notifyChange(insertBookedUri,null);
return insertBookedUri;
}
throw new SQLException("Failed to insert row int "+uri);
}
@Override
public int delete(Uri uri,String selection,String[] selectionArgs){
SQLiteDatabase db = dbhelper.getWritableDatabase();
int count = 0;
switch(sUriMatcher.match(uri)){
case BOOKS_RECORDS:
count = db.delete(Bookinfo_provider.Bookinfo.TABLE_NAME,selection,selectionArgs);
break;
case BOOKS_RECORD:
String rowID = uri.getPathSegments().get(1);
String where = Bookinfo_provider.Bookinfo._ID+"="+rowID
+(!TextUtils.isEmpty(selection)?" AND ("+selectionArgs+')':"");
count = db.delete(Bookinfo_provider.Bookinfo.TABLE_NAME,where,selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI"+uri);
}
db.close();
this.getContext().getContentResolver().notifyChange(uri,null);
return count;
}
@Override
public int update(Uri uri,ContentValues values,String selection,String[] selectionArgs){
SQLiteDatabase db = dbhelper.getWritableDatabase();
int count = 0;
switch (sUriMatcher.match(uri)){
case BOOKS_RECORDS:
count = db.update(Bookinfo_provider.BOOKS_TABLE_NAME,values,selection,selectionArgs);
break;
case BOOKS_RECORD:
String rowID = uri.getPathSegments().get(1);
String where = Bookinfo_provider.Bookinfo._ID+"="+rowID
+(!TextUtils.isEmpty(selection)?" AND("+selection+')':"");
count = db.update(Bookinfo_provider.BOOKS_TABLE_NAME,values,where,selectionArgs);
break;
default:
throw new IllegalArgumentException("Uknown URI "+uri);
}
getContext().getContentResolver().notifyChange(uri,null);
return count;
}
@Override
public Cursor query(Uri uri,String[] projection,String selection,String[] selectionArgs,String sortOrder){
Cursor cursor = null;
SQLiteDatabase db = dbhelper.getReadableDatabase();
switch(sUriMatcher.match(uri)){
case BOOKS_RECORDS:
cursor = db.query(Bookinfo_provider.BOOKS_TABLE_NAME,projection,selection,selectionArgs,null,null,sortOrder);
break;
case BOOKS_RECORD:
String id = uri.getPathSegments().get(1);
cursor = db.query(Bookinfo_provider.BOOKS_TABLE_NAME,projection,
Bookinfo_provider.Bookinfo._ID+"="+id+(!TextUtils.isEmpty(selection)?" AND ("
+selectionArgs+')':""),selectionArgs,null,null,sortOrder);
break;
default:
throw new IllegalArgumentException("Unknown URI "+uri);
}
ContentResolver cr = this.getContext().getContentResolver();
cursor.setNotificationUri(cr,uri);
return cursor;
}
}
//MainActivity.java
package lmy.com.sample_8_6;
import android.app.ListActivity;
import android.os.Bundle;
public class MainActivity extends ListActivity {
private Sample_8_6 mContentProvider=new Sample_8_6();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
//DB_helper.java
package lmy.com.sample_8_6;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
//创建数据库
public class DB_helper extends SQLiteOpenHelper {
public DB_helper(Context context){
super(context,Bookinfo_provider.DATABASE_NAME,null,Bookinfo_provider.DATABASE_VERSION);
}
//创建图书信息表
@Override
public void onCreate(SQLiteDatabase db){
String sql = "CREATE TABLE "+ Bookinfo_provider.Bookinfo.TABLE_NAME+" ("+ Bookinfo_provider.Bookinfo._ID+
" INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Bookinfo_provider.Bookinfo.BOOK_NAME+" TEXT,"+ Bookinfo_provider.Bookinfo.BOOK_ISBN+" TEXT,"
+ Bookinfo_provider.Bookinfo.BOOK_AUTHOR+" TEXT)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
String sql = "DROP TABLE IF EXISTS "+Bookinfo_provider.Bookinfo.TABLE_NAME;
db.execSQL(sql);
onCreate(db);
}
}
//Bookinfo_provider.java
package lmy.com.sample_8_6;
import android.net.Uri;
import android.provider.BaseColumns;
public class Bookinfo_provider {
public static final String DATABASE_NAME = "book.db";
public static final int DATABASE_VERSION = 1;
public static final String AUTHORITY="lmy.com.bookinfo_provider";
public static final String BOOKS_TABLE_NAME = "books";
public static final class Bookinfo implements BaseColumns {
public static final String TABLE_NAME = "books";
public static final String BOOK_NAME = "name";
public static final String BOOK_ISBN = "isbn";
public static final String BOOK_AUTHOR = "author";
public static final String _ID = "_id";
public static final Uri CONTENT_URI = Uri.parse("content://"+AUTHORITY+"/books");
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.androidbook.book";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.androidbook.book";
public static final String DEFAULT_SORT_ORD="id DESC";
}
}
<!--main.xml-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BookinfoProvider!"
/>
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="366dp" />
</LinearLayout>
<!--edit.xml-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/edit"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="书名" />
<EditText
android:id="@+id/name"
android:layout_width="325dp"
android:layout_height="wrap_content"
android:inputType="text" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="书号"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/isbn"
android:layout_width="323dp"
android:layout_height="wrap_content"
android:inputType="text" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="作者" />
<EditText
android:id="@+id/author"
android:layout_width="322dp"
android:layout_height="wrap_content"
android:inputType="text" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:text="取消"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/cancel"
/>
<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@+id/cancel"
android:text="确定" />
</LinearLayout>
</LinearLayout>
<!--AndroidManifest.xml-->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="lmy.com.sample_8_6">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<provider
android:authorities="lmy.com.bookinfo_provider"
android:name=".Sample_8_6"
android:exported="true" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
2.ContentResolver
//《安卓编程兵书》p311
//Sample_8_6.java
package lmy.com.sample_8_6_test;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Sample_8_6_test extends AppCompatActivity {
private ListView listview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listview = (ListView)findViewById(R.id.myListView);
MyAdapter myAdapter = new MyAdapter(this,putData());
listview.setAdapter(myAdapter);
try{
test_insert();
test_insert();
test_insert();
test_delete();
test_update();
test_find();
}catch (Throwable e){
System.out.println(e.toString());
e.printStackTrace();
}
}
public void test_insert() throws Throwable{
ContentResolver cr = this.getContentResolver();
//Uri inserturi = Uri.parse("content://lmy.com.bookinfo_provider/books");
Uri inserturi = Uri.parse("content://"+Bookinfo_provider.AUTHORITY+"/books");
ContentValues cv = new ContentValues();
cv.put("name","Android");
cv.put("isbn","123456");
Uri re_uri = cr.insert(inserturi,cv);
System.out.println("test_insert:"+re_uri);
}
public void test_delete() throws Throwable{
ContentResolver contentResolver = getContentResolver();
//Uri uri = Uri.parse("content://lmy.com.bookinfo_provider/books/1");
Uri uri = Uri.parse("content://"+Bookinfo_provider.AUTHORITY+"/books/1");
//"/books/1"表示books表中的第一条记录
contentResolver.delete(uri,null,null);
}
public void test_update() throws Throwable{
ContentResolver contentResolver = getContentResolver();
//Uri updateUri = Uri.parse("content://lmy.com.bookinfo_provider/books/2");
Uri updateUri = Uri.parse("content://"+Bookinfo_provider.AUTHORITY+"/books/2");
ContentValues values = new ContentValues();
values.put("name","Android示例");
contentResolver.update(updateUri,values,null,null);
System.out.println("修改完成");
}
public void test_find() throws Throwable{
ContentResolver contentResolver = getContentResolver();
//Uri uri = Uri.parse("content://lmy.com.bookinfo_provider/books");
Uri uri = Uri.parse("content://"+Bookinfo_provider.AUTHORITY+"/books");
Cursor cursor =contentResolver.query(uri,null,null,null,null);
while(((Cursor) cursor).moveToNext()){
String id = cursor.getString(0);
String name = cursor.getString(1);
String isbn = cursor.getString(2);
String author = cursor.getString(3);
System.out.println("_id="+id+",name="+name+",isbn="+isbn+",author="+author);
}
cursor.close();
}
public List<Map<String,Object>> putData(){
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
Map<String,Object> map1 ;
ContentResolver contentResolver = getContentResolver();
//Uri uri = Uri.parse("content://lmy.com.bookinfo_provider/books");
Uri uri = Uri.parse("content://"+Bookinfo_provider.AUTHORITY+"/books");
Cursor cursor =contentResolver.query(uri,null,null,null,null);
while(((Cursor) cursor).moveToNext()){
String id = cursor.getString(0);
String name = cursor.getString(1);
String isbn = cursor.getString(2);
String author = cursor.getString(3);
System.out.println("_id="+id+",name="+name+",isbn="+isbn+",author="+author);
map1 = new HashMap<String,Object>();
map1.put("_id",id);
map1.put("name",name);
map1.put("isbn",isbn);
map1.put("author",author);
list.add(map1);
}
return list;
}
}
//MyAdapter.java
package lmy.com.sample_8_6_test;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import java.util.List;
import java.util.Map;
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<Map<String,Object>> list;
public MyAdapter(Context context , List<Map<String,Object>> list){
this.mInflater = LayoutInflater.from(context);
this.list = list;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.edit, null);
holder._id = (EditText) convertView.findViewById(R.id._id);
holder.name = (EditText)convertView.findViewById(R.id.name);
holder.isbn=(EditText)convertView.findViewById(R.id.isbn);
holder.author=(EditText)convertView.findViewById(R.id.author);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder._id.setText((String)list.get(position).get("_id"));
holder.name.setText((String)list.get(position).get("name"));
holder.isbn.setText((String)list.get(position).get("isbn"));
holder.author.setText((String)list.get(position).get("author"));
return convertView;
}
public final class ViewHolder{
public EditText _id;
public EditText name;
public EditText isbn;
public EditText author;
}
}
//Bookinfo_provider.java
package lmy.com.sample_8_6_test;
import android.net.Uri;
import android.provider.BaseColumns;
public class Bookinfo_provider {
public static final String DATABASE_NAME = "book.db";
public static final int DATABASE_VERSION = 1;
public static final String AUTHORITY="lmy.com.bookinfo_provider";
public static final String BOOKS_TABLE_NAME = "books";
public static final class Bookinfo implements BaseColumns {
public static final String TABLE_NAME = "books";
public static final String BOOK_NAME = "name";
public static final String BOOK_ISBN = "isbn";
public static final String BOOK_AUTHOR = "author";
public static final String _ID = "_id";
public static final Uri CONTENT_URI = Uri.parse("content://"+AUTHORITY+"/books");
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.androidbook.book";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.androidbook.book";
public static final String DEFAULT_SORT_ORD="_id DESC";
}
}
<!--main.xml-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="序号"/>
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="书名" />
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="ISBN" />
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="作者" />
</LinearLayout>
<ListView
android:id="@+id/myListView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!--edit.xml-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/edit"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<EditText
android:id="@+id/_id"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:inputType="number" />
<EditText
android:id="@+id/name"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:inputType="text" />
<EditText
android:id="@+id/isbn"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:inputType="text" />
<EditText
android:id="@+id/author"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:inputType="text" />
</LinearLayout>
<!--AndroidManifest.xml-->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="lmy.com.sample_8_6_test">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".Sample_8_6_test">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>