您的位置:首页 > 移动开发 > Android开发

Android中ContentProvider详解例程

2015-08-02 10:17 597 查看
一个很简单的ContentProvider详细例程,从定义到使用都有相应的代码,废话不多说,直接看代码!

点击这里下载完整代码!

MainActivity:

package com.example.contentproviderdemo;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import com.example.contentproviderdemo.R;

public class MainActivity extends Activity {

/** Called when the activity is first created. */
private   SimpleCursorAdapter adapter;
private   ListView listView;

@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

listView = (ListView) this.findViewById(R.id.listView);
ContentResolver contentResolver = getContentResolver();
Uri selectUri = Uri.parse("content://com.example.contentproviderdemo.database.studentProvider/student");
Cursor cursor = contentResolver.query(selectUri, null, null, null, null);
adapter = new SimpleCursorAdapter(this, R.layout.item, cursor,
new String[]{"_id", "name", "age"}, new int[]{R.id.id, R.id.name, R.id.age});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListView lView = (ListView)parent;
Cursor data = (Cursor)lView.getItemAtPosition(position);
int _id = data.getInt(data.getColumnIndex("_id"));
Toast.makeText(MainActivity.this, _id+"", 1).show();
}
});

Button button = (Button) this.findViewById(R.id.insertbutton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentResolver contentResolver = getContentResolver();
Uri insertUri = Uri.parse("content://com.example.contentproviderdemo.database.studentProvider/student");
ContentValues values = new ContentValues();
values.put("name", "zhangsan");
values.put("age", 23);
Uri uri = contentResolver.insert(insertUri, values);
Toast.makeText(MainActivity.this, "添加完成", 1).show();
}
});
}
}


DBOpenHelper:

package com.example.contentproviderdemo.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBOpenHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "student.db"; //数据库名称
private static final int DATABASE_VERSION = 1;//数据库版本

public DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {

db.execSQL("CREATE TABLE student (_id integer primary key autoincrement, name varchar(20), age varchar(10))");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS person");
onCreate(db);
}

}


StudentProvider:

package com.example.contentproviderdemo.database;

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;

public class StudentProvider extends ContentProvider {
private DBOpenHelper dbOpenHelper;
private static final UriMatcher MATCHER = new UriMatcher(
UriMatcher.NO_MATCH);
private static final int STUDENTS = 1;
private static final int STUDENT = 2;
static {
MATCHER.addURI("com.example.contentproviderdemo.database.studentProvider", "student", STUDENTS);
MATCHER.addURI("com.example.contentproviderdemo.database.studentProvider", "student/#", STUDENT);
}

@Override
public boolean onCreate() {
// TODO Auto-generated method stub
this.dbOpenHelper = new DBOpenHelper(this.getContext());
return false;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
switch (MATCHER.match(uri)) {
case STUDENTS:
return db.query("student", projection, selection, selectionArgs,
null, null, sortOrder);

case STUDENT:
long id = ContentUris.parseId(uri);
String where = "_id=" + id;
if (selection != null && !"".equals(selection)) {
where = selection + " and " + where;
}
return db.query("student", projection, where, selectionArgs, null,
null, sortOrder);

default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}

@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
switch (MATCHER.match(uri)) {
case STUDENTS:
return "vnd.android.cursor.dir/student";

case STUDENT:
return "vnd.android.cursor.item/student";

default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}

// 插入student表中的所有记录 /student
// 插入student表中指定id的记录 /student/10
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
switch (MATCHER.match(uri)) {
case STUDENTS:
// 特别说一下第二个参数是当name字段为空时,将自动插入一个NULL。
long rowid = db.insert("student", "name", values);
Uri insertUri = ContentUris.withAppendedId(uri, rowid);// 得到代表新增记录的Uri
this.getContext().getContentResolver().notifyChange(uri, null);
return insertUri;

default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
int count = 0;
switch (MATCHER.match(uri)) {
case STUDENTS:
count = db.delete("student", selection, selectionArgs);
return count;

case STUDENT:
long id = ContentUris.parseId(uri);
String where = "_id=" + id;
if (selection != null && !"".equals(selection)) {
where = selection + " and " + where;
}
count = db.delete("student", where, selectionArgs);
return count;

default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}

@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
int count = 0;
switch (MATCHER.match(uri)) {
case STUDENTS:
count = db.update("student", values, selection, selectionArgs);
return count;
case STUDENT:
long id = ContentUris.parseId(uri);
String where = "_id=" + id;
if (selection != null && !"".equals(selection)) {
where = selection + " and " + where;
}
count = db.update("student", values, where, selectionArgs);
return count;
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: