Android组件之ContentProvider(二)

2/10/2017来源:ASP.NET技巧人气:341

一个共享生词本的应用以熟悉ContentPRovider和sqlite基本用法:

应用dictprovider

Word数据封装类:

public final class Words { // 定义该ContentProvider的Authorities public static final String AUTHORITY = "com.example.mrpeng.dictprovider"; // 定义一个静态内部类,定义该ContentProvider所包含的数据列的列名 public static final class Word implements BaseColumns { // 定义Content所允许操作的三个数据列 public final static String _ID = "_id"; public final static String WORD = "word"; public final static String DETAIL = "detail"; // 定义该Content提供服务的两个Uri public final static Uri DICT_CONTENT_URI = Uri .parse("content://" + AUTHORITY + "/words"); public final static Uri WORD_CONTENT_URI = Uri .parse("content://" + AUTHORITY + "/word"); } }

自定义的provider

public class DictProvider extends ContentProvider { private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); private static final int WORDS = 1; private static final int WORD = 2; private MyDataBaseHelper dbOpenHelper; static { // 为UriMatcher注册两个Uri matcher.addURI(Words.AUTHORITY, "words", WORDS); matcher.addURI(Words.AUTHORITY, "word/#", WORD); } // 第一次调用该DictProvider时,系统先创建DictProvider对象,并回调该方法 @Override public boolean onCreate() { dbOpenHelper = new MyDataBaseHelper(this.getContext(), "myDict.db3", 1); return true; } // 返回指定Uri参数对应的数据的MIME类型 @Override public String getType(Uri uri) { switch (matcher.match(uri)) { // 如果操作的数据是多项记录 case WORDS: return "vnd.android.cursor.dir/org.crazyit.dict"; // 如果操作的数据是单项记录 case WORD: return "vnd.android.cursor.item/org.crazyit.dict"; default: throw new IllegalArgumentException("未知Uri:" + uri); } } // 查询数据的方法 @Override public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs, String sortOrder) { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); switch (matcher.match(uri)) { // 如果Uri参数代表操作全部数据项 case WORDS: // 执行查询 return db.query("dict", projection, where, whereArgs, null, null, sortOrder); // 如果Uri参数代表操作指定数据项 case WORD: // 解析出想查询的记录ID long id = ContentUris.parseId(uri); String whereClause = Words.Word._ID + "=" + id; // 如果原来的where子句存在,拼接where子句 if (where != null && !"".equals(where)) { whereClause = whereClause + " and " + where; Log.e("mrpeng", "whereClause+=where::: " + whereClause); } return db.query("dict", projection, whereClause, whereArgs, null, null, sortOrder); default: throw new IllegalArgumentException("未知Uri:" + uri); } } // 插入数据方法 @Override public Uri insert(Uri uri, ContentValues values) { // 获得数据库实例 SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); switch (matcher.match(uri)) { // 如果Uri参数代表操作全部数据项 case WORDS: // 插入数据,返回插入记录的ID long rowId = db.insert("dict", Words.Word._ID, values); // 如果插入成功返回uri if (rowId > 0) { // 在已有的 Uri的后面追加ID Uri wordUri = ContentUris.withAppendedId(uri, rowId); // 通知数据已经改变 getContext().getContentResolver() .notifyChange(wordUri, null); return wordUri; } break; default: throw new IllegalArgumentException("未知Uri:" + uri); } return null; } // 修改数据的方法 @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); // 记录所修改的记录数 int num = 0; switch (matcher.match(uri)) { // 如果Uri参数代表操作全部数据项 case WORDS: num = db.update("dict", values, where, whereArgs); break; // 如果Uri参数代表操作指定数据项 case WORD: // 解析出想修改的记录ID long id = ContentUris.parseId(uri); String whereClause = Words.Word._ID + "=" + id; // 如果原来的where子句存在,拼接where子句 if (where != null && !where.equals("")) { whereClause = whereClause + " and " + where; } num = db.update("dict", values, whereClause, whereArgs); break; default: throw new IllegalArgumentException("未知Uri:" + uri); } // 通知数据已经改变 getContext().getContentResolver().notifyChange(uri, null); return num; } // 删除数据的方法 @Override public int delete(Uri uri, String where, String[] whereArgs) { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); // 记录所删除的记录数 int num = 0; // 对uri进行匹配 switch (matcher.match(uri)) { // 如果Uri参数代表操作全部数据项 case WORDS: num = db.delete("dict", where, whereArgs); break; // 如果Uri参数代表操作指定数据项 case WORD: // 解析出所需要删除的记录ID long id = ContentUris.parseId(uri); String whereClause = Words.Word._ID + "=" + id; // 如果原来的where子句存在,拼接where子句 if (where != null && !where.equals("")) { whereClause = whereClause + " and " + where; } num = db.delete("dict", whereClause, whereArgs); break; default: throw new IllegalArgumentException("未知Uri:" + uri); } // 通知数据已经改变 getContext().getContentResolver().notifyChange(uri, null); return num; } }

自定义SqliteOpentHelper

public class MyDataBaseHelper extends SQLiteOpenHelper { final String CREATE_TABLE_SQL = "create table dict(_id integer primary " + "key autoincrement , word , detail)"; public MyDataBaseHelper(Context context, String name, int version) { super(context, name, null, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_SQL); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.e("mrpeng", "onUpgrade: " + oldVersion + "---->" + newVersion); } }

主界面

public class MainActivity extends AppCompatActivity { private MyDataBaseHelper dbHelper; private Button insert; private Button search; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); File dir = Environment.getExternalStorageDirectory();//Gets the Android data directory String path = dir.getPath(); Log.e("mrpeng", "path: "+path ); dbHelper = new MyDataBaseHelper(this, "myDict.db3", 1); insert = (Button) findViewById(R.id.insert); search = (Button) findViewById(R.id.search); insert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String word = ((EditText) findViewById(R.id.word)).getText().toString(); String detail = ((EditText) findViewById(R.id.detail)).getText().toString(); SQLiteDatabase readableDatabase = dbHelper.getReadableDatabase(); // 执行插入语句 readableDatabase.execSQL("insert into dict values(null , ? , ?)" , new String[] {word, detail }); } }); search.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 获取用户输入 String key = ((EditText) findViewById(R.id.key)).getText() .toString(); // 执行查询 Cursor cursor = dbHelper.getReadableDatabase().rawQuery( "select * from dict where word like ? or detail like ?", new String[] { "%" + key + "%", "%" + key + "%" }); ArrayList<Map<String, String>> list = converCursorToList(cursor); Bundle bundle = new Bundle(); bundle.putSerializable("data",list); Intent intent = new Intent(MainActivity.this, ResultActivity.class); intent.putExtras(bundle); startActivity(intent); } }); } private ArrayList<Map<String,String>> converCursorToList(Cursor cursor) { ArrayList<Map<String, String>> list= new ArrayList<>(); while (cursor.moveToNext()){ HashMap<String, String> map = new HashMap<>(); map.put("word",cursor.getString(1)); map.put("detail",cursor.getString(2)); list.add(map); } return list; } }

结果展示页

public class ResultActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.popup); ListView listView = (ListView) findViewById(R.id.show); Intent intent = getIntent(); Bundle data = intent.getExtras(); List<Map<String,String>> list = (List<Map<String, String>>) data.getSerializable("data"); // 将List封装成SimpleAdapter SimpleAdapter adapter = new SimpleAdapter(ResultActivity.this , list, R.layout.line, new String[] { "word", "detail" } , new int[] {R.id.word, R.id.detail }); listView.setAdapter(adapter); } }

manifests

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.mrpeng.dictprovider"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/APPTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ResultActivity" android:theme="@android:style/Theme.Material.Dialog" /> <provider android:authorities="com.example.mrpeng.dictprovider" android:name=".DictProvider" android:exported="true"/> </application> </manifest>

dictResolver应用

数据封装类 Word 结果展示类ResultActivity同应用dictprovider

主界面

public class MainActivity extends AppCompatActivity { private ContentResolver contentResolver; private Button insert; private Button search; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contentResolver = getContentResolver(); insert = (Button) findViewById(R.id.insert); search = (Button) findViewById(R.id.search); insert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 获取用户输入 String word = ((EditText) findViewById(R.id.word)) .getText().toString(); String detail = ((EditText) findViewById(R.id.detail)) .getText().toString(); //插入生词记录 ContentValues values = new ContentValues(); values.put(Words.Word.WORD,word); values.put(Words.Word.DETAIL,detail); contentResolver.insert(Words.Word.DICT_CONTENT_URI,values); Toast.makeText(MainActivity.this,"添加生词成功",Toast.LENGTH_SHORT).show(); } }); // 为search按钮的单击事件绑定事件监听器 search.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View source) { // 获取用户输入 String key = ((EditText) findViewById(R.id.key)) .getText().toString(); // 执行查询 Cursor cursor = contentResolver.query( Words.Word.DICT_CONTENT_URI, null, "word like ? or detail like ?", new String[] { "%" + key + "%", "%" + key + "%" }, null); // 创建一个Bundle对象 Bundle data = new Bundle(); data.putSerializable("data", converCursorToList(cursor)); // 创建一个Intent Intent intent = new Intent(MainActivity.this, ResultActivity.class); intent.putExtras(data); // 启动Activity startActivity(intent); } }); } private ArrayList<Map<String, String>> converCursorToList(Cursor cursor) { ArrayList<Map<String, String>> result = new ArrayList<>(); // 遍历Cursor结果集 while (cursor.moveToNext()) { // 将结果集中的数据存入ArrayList中 Map<String, String> map = new HashMap<>(); // 取出查询记录中第2列、第3列的值 map.put(Words.Word.WORD, cursor.getString(1)); map.put(Words.Word.DETAIL, cursor.getString(2)); result.add(map); } return result; } }