新建一个DbHelper类
package com.example.contentprovider;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class DbHelper extends SQLiteOpenHelper {
private static String name="student.db";
private static int version=1;
public DbHelper(Context context) {
super(context, name, null, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql="create table student(id integer primary key autoincrement,name varchar(64),address varchar(64),sex varchar(8) )";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
一个StudentProvider
内容提供者类
package com.example.contentprovider;
import java.util.Currency;
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;
import android.util.Log;
public class StudentProvider extends ContentProvider {
private DbHelper dbHelper=null;
private final String TAG="StudentProvider";
private final static int STUDENT=1;//操作单条记录
private final static int STUDENTS=2;//操作多条记录
private final static UriMatcher uriMatcher=new UriMatcher(UriMatcher.NO_MATCH);
static{
uriMatcher.addURI("com.example.contentprovider.StudentProvider", "student/#", STUDENT);
uriMatcher.addURI("com.example.contentprovider.StudentProvider", "student", STUDENTS);
}
@Override
public boolean onCreate() {
// TODO Auto-generated method stub
dbHelper=new DbHelper(getContext());
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
Log.i(TAG, "query:1");
// TODO Auto-generated method stub
int flg=uriMatcher.match(uri);
int count=-1;
SQLiteDatabase db=null;
Cursor cursor=null;
switch (flg) {
case STUDENT:
Log.i(TAG, "query:2");
long id=ContentUris.parseId(uri);
try {
db=dbHelper.getWritableDatabase();
String whereClause="id = "+id;
if (selection!=null && !selection.equals("")) {
whereClause+="and "+selection;
}
cursor=db.query("student", null, whereClause, selectionArgs, null, null, null);
String name="";
while (cursor.moveToNext()) {
name=cursor.getString(cursor.getColumnIndex("name"));
}
Log.i(TAG, "name---->"+name);
} catch (Exception e) {
Log.i(TAG, "excepton-->"+e.getMessage());
// TODO: handle exception
}finally{
if (db!=null) {
db.close();
}
}
break;
case STUDENTS:
Log.i(TAG, "query:3");
db=dbHelper.getWritableDatabase();
try {
cursor=db.query("student", projection, selection, selectionArgs, null, null, null);
String name="";
while (cursor.moveToNext()) {
name=cursor.getString(cursor.getColumnIndex("name"));
Log.i(TAG, "name---->"+name);
}
} catch (Exception e) {
Log.i(TAG, "message-->"+e.getMessage());
// TODO: handle exception
}finally{
if (db!=null) {
db.close();
}
}
break;
}
Log.i(TAG, "query:end");
return cursor;
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
int code=uriMatcher.match(uri);
switch (code) {
case STUDENT:
return "vnd.android.cursor.item/student";
case STUDENTS:
return"vnd.android.cursor.dir/students";
}
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
Uri requestUri=null;
SQLiteDatabase db=dbHelper.getWritableDatabase();
long id=db.insert("student", null, values);
requestUri=ContentUris.withAppendedId(uri, id);
Log.i(TAG, "--->"+requestUri);
return requestUri;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
Log.i(TAG, "1");
// TODO Auto-generated method stub
int flg=uriMatcher.match(uri);
int count=-1;
SQLiteDatabase db=null;
switch (flg) {
case STUDENT:
Log.i(TAG, "2");
long id=ContentUris.parseId(uri);
try {
db=dbHelper.getWritableDatabase();
String whereClause="id = "+id;
if (selection!=null && !selection.equals("")) {
whereClause+="and "+selection;
}
count=db.delete("student", whereClause, selectionArgs);
Log.i(TAG, "count---->"+count);
} catch (Exception e) {
Log.i(TAG, "excepton-->"+e.getMessage());
// TODO: handle exception
}finally{
if (db!=null) {
db.close();
}
}
break;
case STUDENTS:
Log.i(TAG, "3");
db=dbHelper.getWritableDatabase();
try {
count=db.delete("student", selection, selectionArgs);
Log.i(TAG, "count---->"+count);
} catch (Exception e) {
// TODO: handle exception
}finally{
if (db!=null) {
db.close();
}
}
break;
}
return count;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
Log.i(TAG, "1");
// TODO Auto-generated method stub
int flg=uriMatcher.match(uri);
int count=-1;
SQLiteDatabase db=null;
switch (flg) {
case STUDENT:
Log.i(TAG, "2");
long id=ContentUris.parseId(uri);
try {
db=dbHelper.getWritableDatabase();
String whereClause="id = "+id;
if (selection!=null && !selection.equals("")) {
whereClause+="and "+selection;
}
count=db.update("student", values, whereClause, selectionArgs);
Log.i(TAG, "count---->"+count);
} catch (Exception e) {
Log.i(TAG, "excepton-->"+e.getMessage());
// TODO: handle exception
}finally{
if (db!=null) {
db.close();
}
}
break;
case STUDENTS:
Log.i(TAG, "3");
db=dbHelper.getWritableDatabase();
try {
count=db.update("student", values, selection, selectionArgs);
Log.i(TAG, "count---->"+count);
} catch (Exception e) {
// TODO: handle exception
}finally{
if (db!=null) {
db.close();
}
}
break;
}
return count;
}
}
MainActivity类:
package com.example.contentprovider;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.Dialog;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
private String TAG="MainActivity";
private LoaderManager manager=null;
private ListView listView;
private String tempName;
private MyAdapter adapter;
public String getTempName() {
return tempName;
}
public void setTempName(String tempName) {
this.tempName = tempName;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
listView=(ListView) findViewById(R.id.listView);
manager=getLoaderManager();//加载LoaderManager,完成异步加载数据的操作
manager.initLoader(1001, null, callbacks);
registerForContextMenu(listView);
adapter=new MyAdapter(MainActivity.this);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.main, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.add:
// Toast.makeText(MainActivity.this, "add", 1).show();
final Dialog dialog=getAddDialog();
Button button=(Button) dialog.findViewById(R.id.add);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ContentResolver resolver=getContentResolver();
Uri url=Uri.parse("content://com.example.contentprovider.StudentProvider/student");
ContentValues values=new ContentValues();
EditText text=(EditText) dialog.findViewById(R.id.stuName);
String name=text.getText().toString();
values.put("name", name);
Uri returUri=resolver.insert(url, values);
if (returUri!=null) {
manager.restartLoader(1001, null, callbacks);
dialog.dismiss();
Toast.makeText(MainActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
}
}
});
dialog.show();
break;
case R.id.delete:
AdapterContextMenuInfo info=(AdapterContextMenuInfo) item.getMenuInfo();
// Toast.makeText(MainActivity.this, "position-->"+info.position+" id--->"+
// info.id, Toast.LENGTH_SHORT).show();
String name=(String) adapter.getItem(info.position);
// String name=MainActivity.this.getTempName();
// Toast.makeText(MainActivity.this, "name--->"+MainActivity.this.getTempName(), 1).show();
ContentResolver resolver=getContentResolver();
Uri url=Uri.parse("content://com.example.contentprovider.StudentProvider/student");
int count=resolver.delete(url, "name=?", new String[]{name});
if (count>=1) {
manager.restartLoader(1001, null, callbacks);
Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
}
break;
}
return super.onContextItemSelected(item);
}
public Dialog getAddDialog(){
Dialog dialog=new Dialog(MainActivity.this);
dialog.setContentView(R.layout.add);
return dialog;
}
private LoaderCallbacks<Cursor> callbacks=new LoaderCallbacks<Cursor>() {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle arg1) {
// TODO Auto-generated method stub
CursorLoader loader=new CursorLoader(MainActivity.this);
Uri uri=Uri.parse("content://com.example.contentprovider.StudentProvider/student");
loader.setUri(uri);
return loader;
}
//完成对UI的数据提取,更新UI的操作
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
// TODO Auto-generated method stub
//把数据提取出来,放到适配器中完成对UI的更新操作
List<String> list=null;
String name="";
if (cursor.moveToFirst()) {
list=new ArrayList<String>();
name=cursor.getString(cursor.getColumnIndex("name"));
list.add(name);
while(cursor.moveToNext()){
name=cursor.getString(cursor.getColumnIndex("name"));
list.add(name);
}
}
Log.i(TAG, "list.size----->"+list.size());
//使用BaseAdater
adapter.setList(list);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
//使用ArrayAdapter
// ArrayAdapter< String> arrayAdapter=new ArrayAdapter<String>(MainActivity.this,
// R.layout.fragment_main,R.id.textView1, list);
// listView.setAdapter(arrayAdapter);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO Auto-generated method stub
}
};
public class MyAdapter extends BaseAdapter{
private List<String> list=null;
private Context context;
public MyAdapter(Context context){
this.context=context;
}
public void setList(List<String> list){
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
TextView textView=null;
if (convertView==null) {
textView=new TextView(context);
}else{
textView=(TextView) convertView;
}
textView.setText(list.get(position).toString());
return textView;
}
}
@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;
}
}
xml布局文件:fragment_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.contentprovider.MainActivity$PlaceholderFragment" >
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/listView"
android:layout_alignParentTop="true"
android:text="TextView" />
</LinearLayout>
弹出的对话框的布局文件:add.xml
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="@+id/stuName"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="113dp"
android:layout_y="65dp"
android:text="添加" />
</AbsoluteLayout>
menu文件:main.xml
<menu 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"
tools:context="com.example.contentprovider.MainActivity" >
<item
android:id="@+id/add"
android:orderInCategory="100"
android:title="添加"
app:showAsAction="never"/>
<item
android:id="@+id/delete"
android:orderInCategory="101"
android:title="删除"
app:showAsAction="never"/>
</menu>