内容提供者 ContentResolver 数据库 示例 -1
Posted 白乾涛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了内容提供者 ContentResolver 数据库 示例 -1相关的知识,希望对你有一定的参考价值。
MainActivity
public class MainActivity extends ListActivity {private TextView tv_info;private EditText editText;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);List<String> mData = new ArrayList<String>(Arrays.asList("获取所有数据", "插入", "删除", "查找", "更新"));ListAdapter mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mData);editText = new EditText(this);editText.setHint("请输入要增删改查数据的Name");editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);editText.setPadding(0, 30, 0, 30);editText.setGravity(Gravity.CENTER);getListView().addFooterView(editText);tv_info = new TextView(this);// 将内容显示在TextView中tv_info.setTextColor(Color.BLUE);tv_info.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);tv_info.setPadding(20, 10, 20, 10);getListView().addFooterView(tv_info);setListAdapter(mAdapter);}@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) {PersonDao2 dao = new PersonDao2(this);String content = editText.getText().toString().trim();switch (position) {case 0:ArrayList<Person> list = dao.findAll();tv_info.setText(list.toString());break;case 1:tv_info.setText(dao.add(content, new Random().nextInt(10) + "") + "");break;case 2:tv_info.setText(dao.delete(content) + "");break;case 3:tv_info.setText(dao.find(content) + "");break;case 4:tv_info.setText(dao.update(content, "呵呵") + "");break;}}}
ContentProvider
/** 提供一些public的方法,让其他应用访问自己私有的文件。我们很少会自己来定义ContentProvider,因为我们很多时候都不希望自己应用的数据暴露给*/public class MyContentProvider extends ContentProvider {private SQLiteDatabase db;private static final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);// 参数表示匹配不成功时的返回值,这里为-1// 主机名称public static final String authority = "com.bqt.contentprovider.person";// 定义一些静态全局常量public static final int QUERY = 0;public static final int INSERT = 1;public static final int DELETE = 2;public static final int UPDATE = 3;// 给匹配器添加一些【匹配规则】,放在静态代码块中的作用:随类加载而优先加载,且只加载一次static {// 参数: authority 主机名 ,path 路径名, code 匹配码,匹配成功时的返回值matcher.addURI(authority, "query", QUERY);// 可以使用限定符*和#。* may be used as a wild card for any text, and # may be used as a wild card for numbers.matcher.addURI(authority, "insert", INSERT);//即Uri格式为【content://com.bqt.contentprovider.person/insert】matcher.addURI(authority, "delete", DELETE);matcher.addURI(authority, "update", UPDATE);}@Overridepublic boolean onCreate() {mysqliteOpenHelper helper = new MySQLiteOpenHelper(getContext());db = helper.getWritableDatabase();return true;//true if the provider was successfully loaded, false otherwise}@Overridepublic Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {if (matcher.match(uri) == QUERY) {//表名,要查询的列名数组,选择条件,选择条件对应的参数,分组,分组条件,排序Cursor cursor = db.query(MySQLiteOpenHelper.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);return cursor;//Returns:A Cursor object, which is positioned before the first entry.} else return null;}@Overridepublic int delete(Uri uri, String selection, String[] selectionArgs) {if (matcher.match(uri) == DELETE) {return db.delete(MySQLiteOpenHelper.TABLE_NAME, selection, selectionArgs);//Returns: the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause} else throw new IllegalArgumentException("非法uri");}@Overridepublic Uri insert(Uri uri, ContentValues values) {if (matcher.match(uri) == INSERT) {long id = db.insert(MySQLiteOpenHelper.TABLE_NAME, null, values);//Returns: the row ID of the newly inserted row, or -1 if an error occurredreturn ContentUris.withAppendedId(uri, id);//a new URI with the given ID appended to the end of the path} else throw new IllegalArgumentException("非法uri");}@Overridepublic int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {if (matcher.match(uri) == UPDATE) {return db.update(MySQLiteOpenHelper.TABLE_NAME, values, selection, selectionArgs);//Returns:the number of rows affected} else throw new IllegalArgumentException("非法uri");}@Override/**MIME类型*/public String getType(Uri uri) {return "";//a MIME type string, or null if there is no type.}}
SQLiteOpenHelper
/** 数据库【创建】或【打开】辅助类 */public class MySQLiteOpenHelper extends SQLiteOpenHelper {public static final String DB_NAME = "person.db";public static int DB_VERSION = 2;//所有的表名及SQL語句都放到一個單獨的類中,这里图方便放到了这里public static final String TABLE_NAME = "person";public static final String CREATE_TABLE = "create table if not exists " + TABLE_NAME + " (id integer primary key autoincrement," + "name varchar,"+ "number varchar)";public MySQLiteOpenHelper(Context context) {super(context, DB_NAME, null, DB_VERSION);}@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL(CREATE_TABLE);// db.execSQL(DBConstants.CREATE_PHOTO_TABLE);// db.execSQL(DBConstants.CREATE_DOWNLOAD_TABLE);// db.execSQL(DBConstants.CREATE_USER_TABLE);// db.execSQL(DBConstants.CREATE_GIFTS_TABLE);// db.execSQL(DBConstants.CREATE_ZIP_TABLE);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {db.execSQL("drop table if exists " + TABLE_NAME);// db.execSQL("drop table if exists " + DBConstants.DB_PHOTO_TABLE);// db.execSQL("drop table if exists " + DBConstants.DB_DOWNLOAD_TABLE);// db.execSQL("drop table if exists " + DBConstants.DB_USER_TABLE);// db.execSQL("drop table if exists " + DBConstants.DB_GIFTS_TABLE);// db.execSQL("drop table if exists " + DBConstants.DB_ZIP_TABLE);onCreate(db);}}
DAO1
/** DAO(Data Access Object) 数据访问对象,是一个面向对象的数据库接口,夹在业务逻辑与数据库资源中间。相当于是数据库的【工具类】*/public class PersonDao {private MySQLiteOpenHelper helper;public PersonDao(Context context) {helper = new MySQLiteOpenHelper(context);}public ArrayList<Person> findAll() {SQLiteDatabase db = helper.getWritableDatabase();ArrayList<Person> persons = new ArrayList<Person>();Cursor cursor = db.rawQuery("select * from person", null);//Returns:A Cursor object, which is positioned before the first entry.while (cursor.moveToNext()) {int id = cursor.getInt(cursor.getColumnIndex("id"));//获取指定列的值String name = cursor.getString(cursor.getColumnIndex("name"));String number = cursor.getString(cursor.getColumnIndex("number"));Person p = new Person(id, name, number);persons.add(p);}cursor.close();db.close();return persons;}public boolean find(String name) {SQLiteDatabase db = helper.getWritableDatabase();Cursor cursor = db.rawQuery("select * from person where name=?", new String[] { name });boolean result = cursor.moveToNext();//结果集最初始时是指向表的最前面的,moveToNext时指向的才是【第一条】数据cursor.close();db.close();return result;}public void add(String name, String number) {SQLiteDatabase db = helper.getWritableDatabase();db.execSQL("insert into person(name,number) values(?,?)", new Object[] { name, number });//Returns: the row ID of the newly inserted row, or -1 if an error occurreddb.close();}public void update(String name, String newNumber) {SQLiteDatabase db = helper.getWritableDatabase();db.execSQL("update person set number=? where name=?", new Object[] { newNumber, name });//Returns:the number of rows affecteddb.close();}public void delete(String name) {SQLiteDatabase db = helper.getWritableDatabase();db.execSQL("delete from person where name=?", new Object[] { name });//Returns: the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClausedb.close();}}