ContentProviderTest01
AndroidManifest.xml
android:versionCode="1"
android:versionName="1.0" >
android:targetSdkVersion="21" />
android:targetPackage="com.example.contentprovidertest01" >
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:label="@string/app_name" >
android:authorities="com.example.contentprovidertest01.PersonContentProvider" >
MainActivity.java
package com.example.contentprovidertest01;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MyTest.java
package com.example.contentprovidertest01;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.test.AndroidTestCase;
import android.util.Log;
public class MyTest extends AndroidTestCase {
public MyTest() {
// TODO Auto-generated constructor stub
}
public void calltest() {
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.contentprovidertest01.PersonContentProvider/person");
Bundle bundle = contentResolver.call(uri, "method", null, null);
String returnCall = bundle.getString("returnCall");
Log.i("main", "-------------->" + returnCall);
}
//测试方法:向数据库中添加记录。如果之前没有数据库,则会自动创建
public void insert() {
// 使用内容解析者ContentResolver访问内容提供者ContentProvider
ContentResolver contentResolver = getContext().getContentResolver();
ContentValues values = new ContentValues();
values.put("name", "生命贰号");
values.put("address", "湖北");
// content://authorities/person
// http://
Uri uri = Uri
.parse("content://com.example.contentprovidertest01.PersonContentProvider/person");
contentResolver.insert(uri, values);
}
//测试方法:删除单条记录。如果要删除所有记录:content://com.example.contentprovidertest01.PersonContentProvider/person
public void delete() {
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.contentprovidertest01.PersonContentProvider/person/2");//删除id为1的记录
contentResolver.delete(uri, null, null);
}
//测试方法:根据条件删除记录。
public void deletes() {
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.contentprovidertest01.PersonContentProvider/person");
String where = "address=?";
String[] where_args = { "HK" };
contentResolver.delete(uri, where, where_args); //第二个参数表示查询的条件"address=?",第三个参数表示占位符中的具体内容
}
//方法:根据id修改记录。注:很少有批量修改的情况。
public void update() {
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.contentprovidertest01.PersonContentProvider/person/2");
ContentValues values = new ContentValues();
values.put("name", "李四");
values.put("address", "上海");
contentResolver.update(uri, values, null, null);
}
//方法:根据条件来修改记录。
public void updates() {
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.contentprovidertest01.PersonContentProvider/person/student");
ContentValues values = new ContentValues();
values.put("name", "王五");
values.put("address", "深圳");
String where = "address=?";
String[] where_args = { "beijing" };
contentResolver.update(uri, values, where, where_args);
}
//测试方法:查询所有记录。如果要查询单条记录:content://com.example.contentprovidertest01.PersonContentProvider/person/1
public void query() {
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.contentprovidertest01.PersonContentProvider/person");
Cursor cursor = contentResolver.query(uri, null, null, null, null);
while (cursor.moveToNext()) {
Log.i("MyTest",
"--->>"
+ cursor.getString(cursor.getColumnIndex("name")));
}
}
//测试方法:根据条件查询所有记录。
public void querys() {
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.contentprovidertest01.PersonContentProvider/person");
String where = "address=?";
String[] where_args = { "深圳" };
Cursor cursor = contentResolver.query(uri, null, where, where_args,
null);
while (cursor.moveToNext()) {
Log.i("main",
"-------------->"
+ cursor.getString(cursor.getColumnIndex("name")));
}
}
}
PersonContentProvider.java
package com.example.contentprovidertest01;
import com.example.contentprovidertest01.dao.PersonDao;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class PersonContentProvider extends ContentProvider {
private final String TAG = "PersonContentProvider";
private PersonDao personDao = null;
private static final UriMatcher URI_MATCHER = new UriMatcher(
UriMatcher.NO_MATCH);// 默认的规则是不匹配的
private static final int PERSON = 1; // 操作单行记录
private static final int PERSONS = 2; // 操作多行记录
// 往UriMatcher中添加匹配规则。注意,这里面的url不要写错了,我就是因为写错了,半天没调试出来。哎···
static {
// 添加两个URI筛选
URI_MATCHER.addURI("com.example.contentprovidertest01.PersonContentProvider",
"person", PERSONS);
// 使用通配符#,匹配任意数字
URI_MATCHER.addURI("com.example.contentprovidertest01.PersonContentProvider",
"person/#", PERSON);
}
public PersonContentProvider() {
}
@Override
public boolean onCreate() {
// 初始化一个数据持久层
personDao = new PersonDao(getContext());
//Log.i(TAG, "--->>onCreate()被调用");
return true;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
Uri resultUri = null;
// 解析Uri,返回Code
int flag = URI_MATCHER.match(uri);
switch (flag) {
case PERSONS:
//调用数据库的访问方法
long id = personDao.insertPerson(values); //执行插入操作的方法,返回插入当前行的行号
resultUri = ContentUris.withAppendedId(uri, id);
Log.i(TAG,"--->>插入成功, id=" + id);
Log.i(TAG,"--->>插入成功, resultUri=" + resultUri.toString());
System.out.println("insert success");
break;
}
return resultUri;
}
//方法:删除记录。注:参数:selection和selectionArgs是查询的条件,是由外部(另一个应用程序)传进来的
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = -1;
try {
int flag = URI_MATCHER.match(uri);
switch (flag) {
case PERSON:
// delete from student where id=?
// 单条数据,使用ContentUris工具类解析出结尾的Id
long id = ContentUris.parseId(uri);
String where_value = "id = ?";
String[] args = { String.valueOf(id) };
count = personDao.deletePerson(where_value, args);
break;
case PERSONS:
count = personDao.deletePerson(selection, selectionArgs);
break;
}
} catch (Exception e) {
e.printStackTrace();
}
Log.i(TAG, "--->>删除成功,count=" + count);
return count;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int count = -1;
try {
int flag = URI_MATCHER.match(uri);
switch (flag) {
case PERSON:
long id = ContentUris.parseId(uri);
String where_value = " id = ?";
String[] args = { String.valueOf(id) };
count = personDao.updatePerson(values, where_value, args);
break;
case PERSONS:
count = personDao
.updatePerson(values, selection, selectionArgs);
break;
}
} catch (Exception e) {
e.printStackTrace();
}
Log.i(TAG, "--->>更新成功,count=" + count);
return count;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
Cursor cursor = null;
try {
int flag = URI_MATCHER.match(uri);
switch (flag) {
case PERSON:
long id = ContentUris.parseId(uri);
String where_value = " id = ?";
String[] args = { String.valueOf(id) };
cursor = personDao.queryPersons(where_value, args);
break;
case PERSONS:
cursor = personDao.queryPersons(selection, selectionArgs);
break;
}
} catch (Exception e) {
e.printStackTrace();
}
Log.i(TAG, "--->>查询成功,Count=" + cursor.getCount());
return cursor;
}
@Override
public String getType(Uri uri) {
int flag = URI_MATCHER.match(uri);
switch (flag) {
case PERSON:
return "vnd.android.cursor.item/person"; // 如果是单条记录,则为vnd.android.cursor.item/
// + path
case PERSONS:
return "vnd.android.cursor.dir/persons"; // 如果是多条记录,则为vnd.android.cursor.dir/
// + path
}
return null;
}
@Override
public Bundle call(String method, String arg, Bundle extras) {
Log.i(TAG, "--->>" + method);
Bundle bundle = new Bundle();
bundle.putString("returnCall", "call被执行了");
return bundle;
}
}
PersonDao.java
package com.example.contentprovidertest01.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.contentprovidertest01.db.DBHelper;
public class PersonDao {
private DBHelper helper = null;
public PersonDao(Context context) {
helper = new DBHelper(context);
}
//方法:插入操作,返回的long类型为:插入当前行的行号
public long insertPerson(ContentValues values) {
long id = -1;
SQLiteDatabase database = null;
try {
database = helper.getWritableDatabase();
id = database.insert("person", null, values);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (database != null) {
database.close();
}
}
return id;
}
public int deletePerson(String whereClause, String[] whereArgs) {
int count = -1;
SQLiteDatabase database = null;
try {
database = helper.getWritableDatabase();
count = database.delete("person", whereClause, whereArgs);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (database != null) {
database.close();
}
}
return count;
}
public int updatePerson(ContentValues values, String whereClause,
String[] whereArgs) {
SQLiteDatabase database = null;
int count = -1;
try {
database = helper.getWritableDatabase();
count = database.update("person", values, whereClause, whereArgs);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != database) {
database.close();
}
}
return count;
}
public Cursor queryPersons(String selection, String[] selectionArgs) {
SQLiteDatabase database = null;
Cursor cursor = null;
try {
database = helper.getReadableDatabase();
cursor = database.query(true, "person", null, selection,
selectionArgs, null, null, null, null);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != database) {
// database.close();
}
}
return cursor;
}
}
DBHelper.java
package com.example.contentprovidertest01.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
private static String name = "mydb.db"; // 数据库的名字
private static int version = 1; // 数据库的版本
public DBHelper(Context context) {
super(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 只能支持基本数据类型:varchar int long float boolean text blob clob
// 建表语句执行
String sql = "create table person(id integer primary key autoincrement,name varchar(64),address varchar(64))";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
String sql = "alter table person add sex varchar(8)";
db.execSQL(sql);
}
}
ContentResolverTest
AndroidManifest.xml
android:versionCode="1"
android:versionName="1.0" >
android:targetSdkVersion="21" />
android:targetPackage="com.example.contentresolvertest" >
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:label="@string/app_name" >
MainActivity.java
package com.example.contentresolvertest;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MyTest.java
package com.example.contentresolvertest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.test.AndroidTestCase;
import android.util.Log;
public class MyTest extends AndroidTestCase {
public MyTest() {
// TODO Auto-generated constructor stub
}
public void calltest() {
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.contentprovidertest01.PersonContentProvider/person");
Bundle bundle = contentResolver.call(uri, "method", null, null);
String returnCall = bundle.getString("returnCall");
Log.i("main", "-------------->" + returnCall);
}
//测试方法:向数据库中添加记录。如果之前没有数据库,则会自动创建
public void insert() {
// 使用内容解析者ContentResolver访问内容提供者ContentProvider
ContentResolver contentResolver = getContext().getContentResolver();
ContentValues values = new ContentValues();
values.put("name", "生命贰号");
values.put("address", "湖北");
// content://authorities/person
// http://
Uri uri = Uri
.parse("content://com.example.contentprovidertest01.PersonContentProvider/person");
contentResolver.insert(uri, values);
}
//测试方法:删除单条记录。如果要删除所有记录:content://com.example.contentprovidertest01.PersonContentProvider/person
public void delete() {
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.contentprovidertest01.PersonContentProvider/person/2");//删除id为1的记录
contentResolver.delete(uri, null, null);
}
//测试方法:根据条件删除记录。
public void deletes() {
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.contentprovidertest01.PersonContentProvider/person");
String where = "address=?";
String[] where_args = { "HK" };
contentResolver.delete(uri, where, where_args); //第二个参数表示查询的条件"address=?",第三个参数表示占位符中的具体内容
}
//方法:根据id修改记录。注:很少有批量修改的情况。
public void update() {
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.contentprovidertest01.PersonContentProvider/person/2");
ContentValues values = new ContentValues();
values.put("name", "李四");
values.put("address", "上海");
contentResolver.update(uri, values, null, null);
}
//方法:根据条件来修改记录。
public void updates() {
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.contentprovidertest01.PersonContentProvider/person/student");
ContentValues values = new ContentValues();
values.put("name", "王五");
values.put("address", "深圳");
String where = "address=?";
String[] where_args = { "beijing" };
contentResolver.update(uri, values, where, where_args);
}
//测试方法:查询所有记录。如果要查询单条记录:
content://com.example.contentprovidertest01.PersonContentProvider/person/1
public void query() {
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.contentprovidertest01.PersonContentProvider/person");
Cursor cursor = contentResolver.query(uri, null, null, null, null);
while (cursor.moveToNext()) {
Log.i("MyTest",
"--->>"
+ cursor.getString(cursor.getColumnIndex("name")));
}
}
//测试方法:根据条件查询所有记录。
public void querys() {
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.contentprovidertest01.PersonContentProvider/person");
String where = "address=?";
String[] where_args = { "深圳" };
Cursor cursor = contentResolver.query(uri, null, where, where_args,
null);
while (cursor.moveToNext()) {
Log.i("main",
"-------------->"
+ cursor.getString(cursor.getColumnIndex("name")));
}
}
}