ContentProvider是我学习安卓这几个月以来碰到最难理解的一块,感觉很难掌握,不知道如何使用这一块内容,有些方法的参数使用起来真的是令人发指,我也不打算一下子把全部内容都运用自如,那是不可能的事情,下面是学习ContentProvider所实现的一个实例:
实例:使用ContentProvider共享生词本数据
这个实例可以简单实现添加生词和查询生词的功能,我原本想扩展一下这个应用程序的功能,但却不知道从何做起,只是简简单单换了了界面背景就是了。
创建项目:DictProvider
项目运行效果:
下面只给出主要代码布局文件和string资源文件均不给出
运行以上项目需要在Menifest文件注册相关信息,和设置相关权限
1. <activity Android:name=".ResultActivity" 2.android:theme="@android:style/Theme.Dialog" 3.android:label="找到的单词"> 4. </activity> 5. <provider android:name=".DictProvider" 6. android:authorities="org.crazyit.providers.dictprovider"/> 定义的工具类:Words.java
1.package wwj.dictprovider;
2.
3.import android.net.Uri; 4.
5.import android.provider.BaseColumns; 6.public final class Words 7.{
8. // 定义该ContentProvider的Authority 9. public static final String AUTHORITY 10. = "org.crazyit.providers.dictprovider"; 11. //定义一个静态内部类 12. public static final class Word implements BaseColumns 13. {
14. // 定义Content所允许操作的3个数据列 15. public final static String _ID = "_id"; 16. public final static String WORD = "word"; 17. public final static String DETAIL = "detail"; 18. // 定义该Content提供服务的两个Uri 19. public final static Uri DICT_CONTENT_URI = 20. Uri.parse("content://" + AUTHORITY + "/words"); 21. public final static Uri WORD_CONTENT_URI = 22. Uri.parse("content://" + AUTHORITY + "/word"); 23. }
24.}
因为要用到SQLite数据库,所以需要继承SQLiteOpenHelper类
==>MyDatabaseHelper.java
1.package wwj.dictprovider;
2.
3.import android.content.Context; 4.import android.database.sqlite.SQLiteDatabase; 5.import android.database.sqlite.SQLiteOpenHelper; 6.
7.public class MyDatabaseHelper extends SQLiteOpenHelper 8.{
9. final String CREATE_TABLE_SQL = 10. "create table dict(_id integer primary key autoincrement , word , detail)"; 11. /** 12. * @param context
13. * @param name
14. * @param version
15. */
16. public MyDatabaseHelper(Context context, String name, int version) 17. {
18. super(context, name, null, version); 19. }
20.
21. @Override 22. public void onCreate(SQLiteDatabase db) 23. {
24. // 第一个使用数据库时自动建表 25. db.execSQL(CREATE_TABLE_SQL);
26. }
27.
28. @Override 29. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 30. {
31. System.out.println("--------onUpdate Called--------" 32. + oldVersion + "--->" + newVersion); 33. }
34.}
实现ContentProvider类:DictProvider.java
1.package wwj.dictprovider;
2.
3.import android.content.ContentProvider; 4.import android.content.ContentUris; 5.import android.content.ContentValues; 6.import android.content.UriMatcher; 7.import android.database.Cursor; 8.import android.database.sqlite.SQLiteDatabase; 9.import android.net.Uri; 10.
11.public class DictProvider extends ContentProvider 12.{
13. private static UriMatcher matcher 14. = new UriMatcher(UriMatcher.NO_MATCH); 15. private static final int WORDS = 1; 16. private static final int WORD = 2; 17. private MyDatabaseHelper dbOpenHelper; 18. static 19. {
20. // 为UriMatcher注册两个Uri 21. matcher.addURI(Words.AUTHORITY, "words", WORDS); 22. matcher.addURI(Words.AUTHORITY, "word/#", WORD); 23. }
24. // 第一次调用该DictProvider时,系统先创建DictProvider对象,并回调该方法 25. @Override 26. public boolean onCreate() 27. {
28. dbOpenHelper = new MyDatabaseHelper(this.getContext(), "myDict.db3", 1); 29. return true; 30. }
31. // 插入数据方法 32. @Override 33. public Uri insert(Uri uri, ContentValues values) 34. {
35. // 获得数据库实例 36. SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
37. // 插入数据,返回行ID 38. long rowId = db.insert("dict", Words.Word._ID, values); 39. // 如果插入成功返回uri 40. if (rowId > 0) 41. {
42. // 在已有的 Uri的后面追加ID数据 43. Uri wordUri = ContentUris.withAppendedId(uri, rowId);
44. // 通知数据已经改变 45. getContext().getContentResolver().notifyChange(wordUri, null); 46. return wordUri; 47. }
48. return null; 49. }
50. // 删除数据的方法 51. @Override 52. public int delete(Uri uri, String selection, String[] selectionArgs) 53. {
54. SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
55. // 记录所删除的记录数 56. int num = 0; 57. // 对于uri进行匹配。 58. switch (matcher.match(uri)) 59. {
60. case WORDS: 61. num = db.delete("dict", selection, selectionArgs); 62. break; 63. case WORD: 64. // 解析出所需要删除的记录ID 65. long id = ContentUris.parseId(uri); 66. String where = Words.Word._ID + "=" + id; 67. // 如果原来的where子句存在,拼接where子句 68. if (selection != null && !selection.equals("")) 69. {
70. where = where + " and " + selection; 71. }
72. num = db.delete("dict", where, selectionArgs); 73. break; 74. default: 75. throw new IllegalArgumentException("未知Uri:" + uri); 76. }
77. // 通知数据已经改变 78. getContext().getContentResolver().notifyChange(uri, null); 79. return num; 80. }
81. // 修改数据的方法 82. @Override 83. public int update(Uri uri, ContentValues values, String selection, 84. String[] selectionArgs)
85. {
86. SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
87. // 记录所修改的记录数 88. int num = 0; 89. switch (matcher.match(uri)) 90. {
91. case WORDS: 92. num = db.update("dict", values, selection, selectionArgs); 93. break; 94. case WORD: 95. // 解析出想修改的记录ID 96. long id = ContentUris.parseId(uri); 97. String where = Words.Word._ID + "=" + id; 98. // 如果原来的where子句存在,拼接where子句 99. if (selection != null && !selection.equals("")) 100. {
101. where = where + " and " + selection; 102. }
103. num = db.update("dict", values, where, selectionArgs); 104. break; 105. default: 106. throw new IllegalArgumentException("未知Uri:" + uri); 107. }
108. // 通知数据已经改变 109. getContext().getContentResolver().notifyChange(uri, null); 110. return num; 111. }
112. // 查询数据的方法 113. @Override 114. public Cursor query(Uri uri, String[] projection, String selection, 115. String[] selectionArgs, String sortOrder)
116. {
117. SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
118. switch (matcher.match(uri)) 119. {
120. case WORDS: 121. // 执行查询 122. return db.query("dict", projection, selection, selectionArgs, 123. null, null, sortOrder); 124. case WORD: 125. // 解析出想查询的记录ID 126. long id = ContentUris.parseId(uri); 127. String where = Words.Word._ID + "=" + id; 128. // 如果原来的where子句存在,拼接where子句 129. if (selection != null && !"".equals(selection)) 130. {
131. where = where + " and " + selection; 132. }
133. return db.query("dict", projection, where, selectionArgs, null, 134. null, sortOrder); 135. default: 136. throw new IllegalArgumentException("未知Uri:" + uri); 137. }
138. }
139. // 返回指定uri参数对应的数据的MIME类型 140. @Override 141. public String getType(Uri uri) 142. {
143. switch(matcher.match(uri)) 144. {
145. // 如果操作的数据是多项记录 146. case WORDS: 147. return "vnd.android.cursor.dir/org.crazyit.dict"; 148. // 如果操作的数据是单项记录 149. case WORD: 150. return "vnd.android.cursor.item/org.crazyit.dict"; 151. default: 152. throw new IllegalArgumentException("未知Uri:" + uri); 153. }
154. }
155.}
主Activity文件:DictResolver.java
1.package wwj.dictprovider;
2.
3.import java.util.ArrayList; 4.import java.util.HashMap; 5.import java.util.Map; 6.
7.import android.app.Activity; 8.import android.content.ContentResolver; 9.import android.content.ContentValues; 10.import android.content.Intent; 11.import android.database.Cursor; 12.import android.os.Bundle; 13.import android.view.View; 14.import android.view.View.OnClickListener; 15.import android.widget.Button; 16.import android.widget.EditText; 17.import android.widget.Toast; 18.
19.public class DictResolver extends Activity 20.{
21. ContentResolver contentResolver;
22. Button insert = null; 23. Button search = null; 24. @Override 25. public void onCreate(Bundle savedInstanceState) 26. {
27. super.onCreate(savedInstanceState); 28. setContentView(R.layout.main);
29. // 获取系统的ContentResolver对象 30. contentResolver = getContentResolver();
31. insert = (Button)findViewById(R.id.insert);
32. search = (Button)findViewById(R.id.search);
33. // 为insert按钮的单击事件绑定事件监听器 34. insert.setOnClickListener(new OnClickListener() 35. {
36. @Override 37. public void onClick(View source) 38. {
39. //获取用户输入 40. String word = ((EditText)findViewById(R.id.word))
41. .getText().toString();
42. String detail = ((EditText)findViewById(R.id.detail))
43. .getText().toString();
44. //插入生词记录 45. ContentValues values = new ContentValues(); 46. values.put(Words.Word.WORD , word);
47. values.put(Words.Word.DETAIL , detail);
48. contentResolver.insert(Words.Word.DICT_CONTENT_URI, values);
49. //显示提示信息 50. Toast.makeText(DictResolver.this, "添加生词成功!" , 8000) 51. .show();
52. }
53. });
54. // 为search按钮的单击事件绑定事件监听器 55. search.setOnClickListener(new OnClickListener() 56. {
57. @Override 58. public void onClick(View source) 59. {
60. // 获取用户输入 61. String key = ((EditText) findViewById(R.id.key)).getText()
62. .toString();
63. // 执行查询 64. Cursor cursor = contentResolver.query(
65. Words.Word.DICT_CONTENT_URI, null 66. , "word like ? or detail like ?" 67. , new String[]{"%" + key + "%" , "%" + key + "%"} 68. , null); 69. //创建一个Bundle对象 70. Bundle data = new Bundle(); 71. data.putSerializable("data", converCursorToList(cursor)); 72. //创建一个Intent 73. Intent intent = new Intent(DictResolver.this 74. , ResultActivity.class); 75. intent.putExtras(data);
76. //启动Activity 77. startActivity(intent);
78. }
79. });
80. }
81.
82. private ArrayList<Map<String, String>> converCursorToList( 83. Cursor cursor)
84. {
85. ArrayList<Map<String, String>> result
86. = new ArrayList<Map<String, String>>(); 87. // 遍历Cursor结果集 88. while (cursor.moveToNext()) 89. {
90. // 将结果集中的数据存入ArrayList中 91. Map<String, String> map = new HashMap<String, String>(); 92. // 取出查询记录中第2列、第3列的值 93. map.put(Words.Word.WORD, cursor.getString(1)); 94. map.put(Words.Word.DETAIL, cursor.getString(2)); 95. result.add(map);
96. }
97. return result; 98. }
99.}
ResultActivity.java
1.package wwj.dictprovider;
2.
3.import java.util.List; 4.import java.util.Map; 5.
6.import android.app.Activity; 7.import android.content.Intent; 8.import android.os.Bundle; 9.import android.widget.ListView; 10.import android.widget.SimpleAdapter; 11.
12.public class ResultActivity extends Activity{ 13. @Override 14. protected void onCreate(Bundle savedInstanceState) { 15. // TODO Auto-generated method stub 16. super.onCreate(savedInstanceState); 17. setContentView(R.layout.popup);
18. ListView listView = (ListView)findViewById(R.id.show);
19. Intent intent = getIntent();
20. //获取该intent所携带的数据 21. Bundle data = intent.getExtras();
22. //从Bundle数据包中取出数据 23. @SuppressWarnings("unchecked") 24. List<Map<String, String>> list =
25. (List<Map<String, String>>)data.getSerializable("data"); 26. //将List封装成SimpleAdapter 27. SimpleAdapter adapter = new SimpleAdapter(ResultActivity.this, list, R.layout.line 28. , new String[]{"word", "detail"} 29. , new int[]{R.id.word, R.id.detail}); 30. //填充ListView 31. listView.setAdapter(adapter);
32. }
33.}
本篇文章来源于 Linux公社网站(www.linuxidc.com) 原文链接:http://www.linuxidc.com/Linux/2012-08/67203.htm