一個共享生詞本的應(yīng)用以熟悉ContentPRovider和sqlite基本用法:
應(yīng)用dictprovider
Word數(shù)據(jù)封裝類:
public final class Words{ // 定義該ContentProvider的Authorities public static final String AUTHORITY = "com.example.mrpeng.dictprovider"; // 定義一個靜態(tài)內(nèi)部類,定義該ContentProvider所包含的數(shù)據(jù)列的列名 public static final class Word implements BaseColumns { // 定義Content所允許操作的三個數(shù)據(jù)列 public final static String _ID = "_id"; public final static String WORD = "word"; public final static String DETAIL = "detail"; // 定義該Content提供服務(wù)的兩個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); } // 第一次調(diào)用該DictProvider時,系統(tǒng)先創(chuàng)建DictProvider對象,并回調(diào)該方法 @Override public boolean onCreate() { dbOpenHelper = new MyDataBaseHelper(this.getContext(), "myDict.db3", 1); return true; } // 返回指定Uri參數(shù)對應(yīng)的數(shù)據(jù)的MIME類型 @Override public String getType(Uri uri) { switch (matcher.match(uri)) { // 如果操作的數(shù)據(jù)是多項記錄 case WORDS: return "vnd.android.cursor.dir/org.crazyit.dict"; // 如果操作的數(shù)據(jù)是單項記錄 case WORD: return "vnd.android.cursor.item/org.crazyit.dict"; default: throw new IllegalArgumentException("未知Uri:" + uri); } } // 查詢數(shù)據(jù)的方法 @Override public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs, String sortOrder) { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); switch (matcher.match(uri)) { // 如果Uri參數(shù)代表操作全部數(shù)據(jù)項 case WORDS: // 執(zhí)行查詢 return db.query("dict", projection, where, whereArgs, null, null, sortOrder); // 如果Uri參數(shù)代表操作指定數(shù)據(jù)項 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); } } // 插入數(shù)據(jù)方法 @Override public Uri insert(Uri uri, ContentValues values) { // 獲得數(shù)據(jù)庫實例 SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); switch (matcher.match(uri)) { // 如果Uri參數(shù)代表操作全部數(shù)據(jù)項 case WORDS: // 插入數(shù)據(jù),返回插入記錄的ID long rowId = db.insert("dict", Words.Word._ID, values); // 如果插入成功返回uri if (rowId > 0) { // 在已有的 Uri的后面追加ID Uri wordUri = ContentUris.withAppendedId(uri, rowId); // 通知數(shù)據(jù)已經(jīng)改變 getContext().getContentResolver() .notifyChange(wordUri, null); return wordUri; } break; default: throw new IllegalArgumentException("未知Uri:" + uri); } return null; } // 修改數(shù)據(jù)的方法 @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); // 記錄所修改的記錄數(shù) int num = 0; switch (matcher.match(uri)) { // 如果Uri參數(shù)代表操作全部數(shù)據(jù)項 case WORDS: num = db.update("dict", values, where, whereArgs); break; // 如果Uri參數(shù)代表操作指定數(shù)據(jù)項 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); } // 通知數(shù)據(jù)已經(jīng)改變 getContext().getContentResolver().notifyChange(uri, null); return num; } // 刪除數(shù)據(jù)的方法 @Override public int delete(Uri uri, String where, String[] whereArgs) { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); // 記錄所刪除的記錄數(shù) int num = 0; // 對uri進行匹配 switch (matcher.match(uri)) { // 如果Uri參數(shù)代表操作全部數(shù)據(jù)項 case WORDS: num = db.delete("dict", where, whereArgs); break; // 如果Uri參數(shù)代表操作指定數(shù)據(jù)項 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); } // 通知數(shù)據(jù)已經(jīng)改變 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(); // 執(zhí)行插入語句 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(); // 執(zhí)行查詢 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; }}結(jié)果展示頁
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="@mdictResolver應(yīng)用數(shù)據(jù)封裝類 Word 結(jié)果展示類ResultActivity同應(yīng)用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按鈕的單擊事件綁定事件監(jiān)聽器 search.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View source) { // 獲取用戶輸入 String key = ((EditText) findViewById(R.id.key)) .getText().toString(); // 執(zhí)行查詢 Cursor cursor = contentResolver.query( Words.Word.DICT_CONTENT_URI, null, "word like ? or detail like ?", new String[] { "%" + key + "%", "%" + key + "%" }, null); // 創(chuàng)建一個Bundle對象 Bundle data = new Bundle(); data.putSerializable("data", converCursorToList(cursor)); // 創(chuàng)建一個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結(jié)果集 while (cursor.moveToNext()) { // 將結(jié)果集中的數(shù)據(jù)存入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; }}新聞熱點
疑難解答
圖片精選