--------------------------------------------AndroidManifest.xml----------------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kawa.ch23"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<uses-library android:name="android.test.runner"/>
<activity
android:label="@string/app_name"
android:name=".MainActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:authorities="com.kawa.ch23.provider.myprovider"
android:name=".provider.MyProvider" >
</provider>
<activity android:name="com.kawa.ch23.ItemActivity"></activity>
</application>
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.kawa.ch23" android:label="Tests for My App" />
</manifest>
--------------------------------------------Layout activity_main.java----------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1" >
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名" />
<EditText
android:id="@+id/edtname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fy"/>
</TableRow>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="年龄" />
<EditText
android:id="@+id/edtage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="21"/>
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/btnadd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="新增" />
<Button
android:id="@+id/btnqueryall"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="查询所有" />
</LinearLayout>
<ListView
android:id="@+id/lvall"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
--------------------------------------------Layout 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" >
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1" >
<TableRow >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="ID" />
<EditText
android:id="@+id/edt_item_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</TableRow>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名" />
<EditText
android:id="@+id/edt_item_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</TableRow>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="年龄" />
<EditText
android:id="@+id/edt_item_age"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/btndel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="删除" />
<Button
android:id="@+id/btnupdate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="更新" />
</LinearLayout>
</LinearLayout>
--------------------------------------------Layout list_item.xml----------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/tvId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<TextView
android:id="@+id/tvname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<TextView
android:id="@+id/tvage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
--------------------------------------------MainActivity.java--------------------------------------
package com.kawa.ch23;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.kawa.ch23.model.Person;
import com.kawa.ch23.util.Const;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
/**
*
* 项目名称:com.kawa.ch23
* 类名称:MainActivity
* 类描述:
* 创建人:方勇
* 创建时间:2012-12-14 下午9:38:39
* Copyright (c) 方勇-版权所有
*/
public class MainActivity extends Activity {
private Button btn_add, btn_queryall;
private EditText field_name, field_age;
private ListView listview;
private List<Person> persons;
private SimpleAdapter simpleAdapter;
private Handler handler = new Handler() {//异步消息
@Override
public void handleMessage(Message msg) {
List<Map<String, Object>> data = (List<Map<String, Object>>) msg.obj;
System.out.println(data.size());
simpleAdapter = new SimpleAdapter(MainActivity.this, data,
R.layout.list_item, new String[] { "id", "name", "age" }, new int[] {
R.id.tvId, R.id.tvname, R.id.tvage });
listview.setAdapter(simpleAdapter);
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
persons = new ArrayList<Person>();
findViews();
setListeners();
}
private void findViews() {
btn_queryall = (Button) this.findViewById(R.id.btnqueryall);
btn_add = (Button) this.findViewById(R.id.btnadd);
field_name = (EditText) this.findViewById(R.id.edtname);
field_age = (EditText) this.findViewById(R.id.edtage);
listview = (ListView) this.findViewById(R.id.lvall);
}
private void setListeners() {
btn_add.setOnClickListener(addOnClickListener);
// 查询所有
btn_queryall.setOnClickListener(queryOnClickListener);
listview.setOnItemClickListener(onItemClickListener);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 2) {
MyThread thread = new MyThread(MainActivity.this);
thread.start();
}
}
private OnClickListener addOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentResolver contentResolver = MainActivity.this
.getContentResolver();
Uri url = Uri.parse("content://"+Const.PROVIDER_URL+"/person");
ContentValues values = new ContentValues();
values.put("name", field_name.getText().toString());
values.put("age", field_age.getText().toString());
Uri result = contentResolver.insert(url, values);
System.out.println(result.toString());
if (ContentUris.parseId(result) > 0) {
Toast.makeText(MainActivity.this, "添加成功",
Toast.LENGTH_LONG).show();
// 添加成功后再启动线程查询
MyThread thread = new MyThread(MainActivity.this);
thread.start();
}
}
};
private OnClickListener queryOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
MyThread thread = new MyThread(MainActivity.this);
thread.start();
}
};
private OnItemClickListener onItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
System.out.println("position:" + position);
Person person = persons.get(position);
Bundle bundle = new Bundle();
bundle.putInt("id", person.getId());
bundle.putString("name", person.getName());
bundle.putInt("age", person.getAge());
Intent intent = new Intent(MainActivity.this,
ItemActivity.class);
intent.putExtra("item", bundle);
startActivityForResult(intent, 1);
}
};
class MyThread extends Thread {
Context context;
public MyThread(Context context) {
// 一定要清空。否则会 有问题,每执行一次都会把之前的全部的item加进去
persons.clear();
listview.setAdapter(null);
this.context = context;
}
@Override
public void run() {
Uri url = Uri.parse("content://"+Const.PROVIDER_URL+"/person");
Cursor cursor = context.getContentResolver().query(url,
new String[] { "_id", "name", "age" }, null, null, "_id");
while (cursor.moveToNext()) {
Person person = new Person();
person.setId(cursor.getInt(cursor.getColumnIndex("_id")));
person.setName(cursor.getString(cursor.getColumnIndex("name")));
person.setAge(cursor.getInt(cursor.getColumnIndex("age")));
persons.add(person);
}
cursor.close();
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
Map<String, Object> map = null;
for (int i = 0; i < persons.size(); i++) {
map = new HashMap<String, Object>();
map.put("id", persons.get(i).getId());
map.put("name", persons.get(i).getName());
map.put("age", persons.get(i).getAge());
data.add(map);
}
Message msg = handler.obtainMessage();
msg.obj = data;
handler.sendMessage(msg);
}
}
}
--------------------------------------------ItemActivity.java--------------------------------------
package com.kawa.ch23;
import com.kawa.ch23.util.Const;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
*
* 项目名称:com.kawa.ch23
* 类名称:ItemActivity
* 类描述:
* 创建人:方勇
* 创建时间:2012-12-14 下午9:45:04
* Copyright (c) 方勇-版权所有
*/
public class ItemActivity extends Activity {
private EditText field_name;
private EditText field_age;
private EditText field_id;
private Button btn_del, btn_update;
// 传数据
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item);
findViews();
setListeners();
intent = getIntent();
Bundle bundle = intent.getBundleExtra("item");//选中的数据
int id = bundle.getInt("id");
String name = bundle.getString("name");
int age = bundle.getInt("age");
field_id.setText(String.valueOf(id));
field_name.setText(name);
field_age.setText(String.valueOf(age));
}
private void findViews() {
field_id = (EditText) this.findViewById(R.id.edt_item_id);
field_id.setEnabled(false);// 控制不可用
field_name = (EditText) this.findViewById(R.id.edt_item_name);
field_age = (EditText) this.findViewById(R.id.edt_item_age);
// 得到传过来的数据
btn_del = (Button) this.findViewById(R.id.btndel);
btn_update = (Button) this.findViewById(R.id.btnupdate);
}
private void setListeners() {
btn_del.setOnClickListener(delOnClickListener);
btn_update.setOnClickListener(updateOnClickListener);
}
private OnClickListener updateOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentResolver contentResolver = ItemActivity.this.getContentResolver();
// 构建Uri
String url = "content://"+Const.PROVIDER_URL+"/person/"
+ field_id.getText();
Uri uri = Uri.parse(url);
ContentValues values = new ContentValues();
values.put("name", field_name.getText().toString());
values.put("age", Integer.parseInt(field_age.getText().toString()));
int result = contentResolver.update(uri, values, null, null);
System.out.println("update result:" + result);
if (result >= 1) {
Toast.makeText(ItemActivity.this, "更新成功", Toast.LENGTH_LONG).show();
ItemActivity.this.setResult(2);//设置返回结果
ItemActivity.this.finish();//销毁
}
}
};
private OnClickListener delOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentResolver contentResolver = ItemActivity.this.getContentResolver();
// 构建Uri
String url = "content://"+Const.PROVIDER_URL+"/person/"
+ field_id.getText();
Uri uri = Uri.parse(url);
int result = contentResolver.delete(uri, null, null);
System.out.println("delete result:" + result);
if (result >= 1) {
Toast.makeText(ItemActivity.this, "删除成功", Toast.LENGTH_LONG).show();
ItemActivity.this.setResult(2);
ItemActivity.this.finish();//销毁
}
}
};
}
--------------------------------------------util目录 Const.java-----------------------------------
public class Const {
public static String PROVIDER_URL = "com.kawa.ch23.provider.myprovider";
}
--------------------------------------------provider目录 MyProvider.java-----------------------
package com.kawa.ch23.provider;
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 com.kawa.ch23.db.DBHelper;
import com.kawa.ch23.util.Const;
/**
*
* 项目名称:com.kawa.ch23
* 类名称:MyProvider
* 类描述:提供者
* 创建人:方勇
* 创建时间:2012-12-14 下午9:49:38
* Copyright (c) 方勇-版权所有
*/
public class MyProvider extends ContentProvider {
private DBHelper dbHelper;
// 定义一个UriMatcher类
private static final UriMatcher MATCHER = new UriMatcher(
UriMatcher.NO_MATCH);
private static final int PERSONS = 1;
private static final int PERSON = 2;
static {
MATCHER.addURI(Const.PROVIDER_URL, "person", PERSONS);
MATCHER.addURI(Const.PROVIDER_URL, "person/#", PERSON);
}
@Override
public boolean onCreate() {
System.out.println("---oncreate----");
dbHelper = new DBHelper(this.getContext());
dbHelper.open();
return false;
}
// 查询数据
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
switch (MATCHER.match(uri)) {
case PERSONS:
// 查询所有的数据
return dbHelper.findList("person", projection, selection, selectionArgs,
null, null, sortOrder);
case PERSON:
// 查询某个ID的数据
// 通过ContentUris这个工具类解释出ID
long id = ContentUris.parseId(uri);
String where = " _id=" + id;
if (!"".equals(selection) && selection != null) {
where = selection + " and " + where;
}
return dbHelper.findList("person", projection, where, selectionArgs, null,
null, sortOrder);
default:
throw new IllegalArgumentException("unknow uri" + uri.toString());
}
}
// 返回当前操作的数据的mimeType
@Override
public String getType(Uri uri) {
switch (MATCHER.match(uri)) {
case PERSONS:
return "vnd.android.cursor.dir/person";
case PERSON:
return "vnd.android.cursor.item/person";
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}
// 插入数据
@Override
public Uri insert(Uri uri, ContentValues values) {
Uri insertUri = null;
switch (MATCHER.match(uri)) {
case PERSONS:
long rowid = dbHelper.insert("person", values);
insertUri = ContentUris.withAppendedId(uri, rowid);
break;
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
return insertUri;
}
// 删除数据
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
switch (MATCHER.match(uri)) {
case PERSONS:
count = dbHelper.delete("person", selection, selectionArgs);
return count;
case PERSON:
long id = ContentUris.parseId(uri);
String where = "_id=" + id;
if (selection != null && !"".equals(selection)) {
where = selection + " and " + where;
}
count = dbHelper.delete("person", where, selectionArgs);
return count;
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}
// 更新数据
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int count = 0;
switch (MATCHER.match(uri)) {
case PERSONS:
count = dbHelper.update("person", values, selection, selectionArgs);
break;
case PERSON:
// 通过ContentUri工具类得到ID
long id = ContentUris.parseId(uri);
String where = "_id=" + id;
if (selection != null && !"".equals(selection)) {
where = selection + " and " + where;
}
count = dbHelper.update("person", values, where, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
return count;
}
}
--------------------------------------------provider目录 Test.java-------------------------------
package com.kawa.ch23.provider;
import com.kawa.ch23.util.Const;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.test.AndroidTestCase;
public class Test extends AndroidTestCase {
/*保存*/
public void testInsert() throws Exception {
ContentResolver contentResolver = this.getContext()
.getContentResolver();
Uri url = Uri.parse("content://"+Const.PROVIDER_URL+"/person");
ContentValues values = new ContentValues();
values.put("name", "jiahui2");
values.put("age", 20);
contentResolver.insert(url, values);
}
/*删除*/
public void testDelete() throws Exception{
ContentResolver contentResolver = this.getContext()
.getContentResolver();
Uri url = Uri.parse("content://"+Const.PROVIDER_URL+"/person/1");
//ContentValues values = new ContentValues();
contentResolver.delete(url, null, null);
}
/*更新*/
public void testUpdate() throws Exception {
ContentResolver contentResolver = this.getContext()
.getContentResolver();
Uri url = Uri.parse("content://"+Const.PROVIDER_URL+"/person/1");
ContentValues values = new ContentValues();
values.put("name", "jiahui2");
values.put("age", 20);
contentResolver.update(url, values, null,null);
}
/*查询*/
public void testQuery() throws Exception {
ContentResolver contentResolver = this.getContext()
.getContentResolver();
Uri url = Uri.parse("content://"+Const.PROVIDER_URL+"/person");
Cursor cursor = contentResolver.query(url, new String[] { "_id",
"name", "age" }, null, null, "_id");
while (cursor.moveToNext()) {
System.out.println("_id:"+cursor.getInt(cursor.getColumnIndex("_id")));
System.out.println("name:"+cursor.getString(cursor.getColumnIndex("name")));
System.out.println("age:"+cursor.getInt(cursor.getColumnIndex("age")));
}
}
}
--------------------------------------------model目录 Person.java-------------------------------
package com.kawa.ch23.model;
import java.io.Serializable;
public class Person implements Serializable{
private int id;
private String name;
private int 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 int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
--------------------------------------------db目录 DBHelper.java--------------------------------
package com.kawa.ch23.db;
import com.kawa.ch23.util.LogOut;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
*
* 项目名称:com.kawa.ch21
*
* 类名称:DBHelper
*
* 类描述:Sqlite3数据库操作工具类
*
* 创建人:fy
*
* 创建时间:2012-9-7 上午9:27:24
*
* Copyright (c) 方勇-版权所有
*/
public class DBHelper {
// DDL操作
private static DatabaseHelper dbHelper;
// DML操作
private static SQLiteDatabase db;
// 数据库名
private static final String DATABASE_NAME = "kawa.db";
// 数据库版本
private static final int DATABASE_VERSION = 1;
// 上下文环境
private final Context mCtx;
/* SQliteOpenHelper是一个抽象类,来管理数据库的创建和版本的管理 */
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table IF NOT EXISTS person (_id integer primary key autoincrement, name text,age integer)";
LogOut.out("fy", "sql[" + sql + "]");
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("upgrade a database");
}
}
public DBHelper(Context ctx) {
this.mCtx = ctx;
}
public DBHelper open() throws SQLException {
dbHelper = new DatabaseHelper(mCtx);
db = dbHelper.getWritableDatabase();
return this;
}
public void closeclose() {
db.close();
dbHelper.close();
}
/**
* 插入数据
* 参数:tableName 表名
* initialValues 要插入的列对应值
* */
public long insert(String tableName, ContentValues initialValues) {
return db.insert(tableName, null, initialValues);
}
/**
* 删除数据
* 参数:tableName 表名
* deleteCondition 删除的条件
* deleteArgs 如果deleteCondition中有“?”号,将用此数组中的值替换
* */
public int delete(String tableName, String deleteCondition,
String[] deleteArgs) {
return db.delete(tableName, deleteCondition, deleteArgs) ;
}
/**
* 更新数据
* 参数:tableName 表名
* initialValues 要更新的列
* selection 更新的条件
* selectArgs 如果selection中有“?”号,将用此数组中的值替换
* */
public int update(String tableName, ContentValues initialValues,
String selection, String[] selectArgs) {
int returnValue = db
.update(tableName, initialValues, selection, selectArgs);
return returnValue ;
}
/**
* 取得一个列表
* 参数:tableName 表名
* columns 返回的列
* selection 查询条件
* selectArgs 如果selection中有“?”号,将用此数组中的值替换
* */
public Cursor findList(String tableName, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having, String orderBy) {
return db.query(tableName, columns, selection, selectionArgs, groupBy,
having, orderBy);
}
}
--------------------------------------------结果----------------------------------------------------