当前位置: 编程技术>移动开发
本页文章导读:
▪ContentProvider-四多表 ContentProvider-4多表
我的理解:其实ContentProvider的机制很随意,它就类似于一个服务器一样,你把uri传来,只要按照特定的方式,它就能给你特定的功能,我觉得这个机制自由又方便。其实.........
▪ 运用ActivityGroup来切换Activity和Layout 使用ActivityGroup来切换Activity和Layout
在一个主界面中做Activity切换一般都会用TabActivity,使用方便,Activity互相之间相对独立,但是可定制性不强,而且修改起来很麻烦。当然也可以把layout分.........
▪ ContentProvider-一查询 ContentProvider-1查询
今天看了android的官方文档中ContentProvider的那部分,因为数据库使用我一直很晕乎,我想要完成自己写一个provider,再写一个工程来使用它读数据,建数据,所以今天先学.........
[1]ContentProvider-四多表
来源: 互联网 发布时间: 2014-02-18
ContentProvider-4多表
我的理解:其实ContentProvider的机制很随意,它就类似于一个服务器一样,你把uri传来,只要按照特定的方式,它就能给你特定的功能,我觉得这个机制自由又方便。
其实这两个功能主要通过修改query就可以,完整的ContentProvider代码如下:
view plaincopy to clipboardprint?
1. package com.ianc.lilyprovider;
2. import android.content.ContentProvider;
3. import android.content.ContentValues;
4. import android.content.Context;
5. import android.content.UriMatcher;
6. import android.database.Cursor;
7. import android.database.sqlite.SQLiteDatabase;
8. import android.database.sqlite.SQLiteOpenHelper;
9. import android.net.Uri;
10. import android.util.Log;
11. public class LilyProvider extends ContentProvider {
12. final static String TABLE_NAME = "customer";
13. final static String PRODUCT_TABLE = "shoplist";
14. private static final String DATABASE_NAME = "lily.db";
15. private static String AUTHORITY = "com.ianc.lilyprovider";
16. private static final int DATABASE_VERSION = 1;
17.
18. DatabaseHelper mDbHelper;
19. static UriMatcher sUriMatcher;
20. private static final int USER = 1;
21. private static final int USER_NAME = 2;
22. private static final int MULITABLE = 3;
23. private static final int SHOPLIST = 4;
// 传入匹配码如果大于0表示匹配根路径或传入-1,即常量UriMatcher.NO_MATCH表示不匹配根路径
// addURI()方法是用来增加其他URI匹配路径的:
// 第一个参数代表传入标识ContentProvider的AUTHORITY字符串
// 第二个参数是要匹配的路径,#代表任意数字,另外还可以用*来匹配任意文本
// 第三个参数必须传入一个大于零的匹配码,用于match()方法对相匹配的URI返回相对应的匹配码
24. static{
25. sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
26. sUriMatcher.addURI(AUTHORITY, TABLE_NAME, USER);
27. sUriMatcher.addURI(AUTHORITY, PRODUCT_TABLE, SHOPLIST);
28. sUriMatcher.addURI(AUTHORITY, TABLE_NAME+"/"+LilyUser.UserColumns.NAME+"/*", USER_NAME);//search special user by name
29. sUriMatcher.addURI(AUTHORITY, TABLE_NAME+"/*", MULITABLE);
30. }
31. //内部类
32. class DatabaseHelper extends SQLiteOpenHelper {
33. public DatabaseHelper(Context context) {
34. super(context, DATABASE_NAME, null, DATABASE_VERSION);
35. }
36. @Override
37. public void onCreate(SQLiteDatabase db) {
38. Log.i("lily","LilyProvider-->DatabaseHelper-->onCreate");
39. db.execSQL("Create table " + TABLE_NAME + "( " +
40. LilyUser.UserColumns._ID+ " INTEGER PRIMARY KEY AUTOINCREMENT, " +
41. LilyUser.UserColumns._COUNT + " INTEGER,"+
42. LilyUser.UserColumns.NAME + " TEXT," +
43. LilyUser.UserColumns.PASSWORD +" TEXT" +
44. ");");
45. db.execSQL("Create table " + PRODUCT_TABLE + "( " +
46. LilyUser.ShopListColumns._ID+ " INTEGER PRIMARY KEY AUTOINCREMENT, " +
47. LilyUser.ShopListColumns._COUNT + " INTEGER,"+
48. LilyUser.ShopListColumns.USER_ID+" INTEGER,"+
49. LilyUser.ShopListColumns.PRODUCT + " TEXT," +
50. LilyUser.ShopListColumns.DATE +" TEXT" +
51. ");");
52. }
53. @Override
54. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
55. Log.i("lily","LilyProvider-->DatabaseHelper-->onUpgrade");
56. db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME+";");
57. db.execSQL("DROP TABLE IF EXISTS "+PRODUCT_TABLE+";");
58. onCreate(db);
59. }
60.
61. }
62. @Override
63. public int delete(Uri arg0, String arg1, String[] arg2) {
64. Log.i("lily","LilyProvider-->delete");
65. SQLiteDatabase db = mDbHelper.getWritableDatabase();
66. int rownum = db.delete(TABLE_NAME, arg1, arg2);
67. return rownum;
68. }
69. @Override
70. public String getType(Uri uri) {
71. Log.i("lily","LilyProvider-->getType");
72. return null;
73. }
74. @Override
75. public Uri insert(Uri uri, ContentValues values) {
76. Log.i("lily","LilyProvider-->insert");
77. if (sUriMatcher.match(uri) == USER){
78. SQLiteDatabase db = mDbHelper.getWritableDatabase();
79. db.insert(TABLE_NAME, null, values);
80. }
81. else if (sUriMatcher.match(uri) == SHOPLIST){
82. SQLiteDatabase db = mDbHelper.getWritableDatabase();
83. db.insert(PRODUCT_TABLE, null, values);
84. }
85.
86. return null;
87. }
88. @Override
89. public boolean onCreate() {
90. Log.i("lily","LilyProvider-->onCreate");
91. mDbHelper = new DatabaseHelper(this.getContext());
92. return false;
93. }
94. @Override
95. public Cursor query(Uri uri, String[] projection, String selection,
96. String[] selectionArgs, String sortOrder) {
97. Log.i("lily","LilyProvider-->query");
98. Log.i("lily","uri = "+uri);
99. Log.i("lily","sUriMatcher.match(uri)="+sUriMatcher.match(uri));
100. Cursor c = null;
101. if (sUriMatcher.match(uri) == USER){
102. SQLiteDatabase db = mDbHelper.getReadableDatabase();
103. c = db.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
104. }else if (sUriMatcher.match(uri) == USER_NAME){
105.
106. // format:authority/table/column/value-->0:table 1:column 2:value
107. String name = uri.getPathSegments().get(2);// get name value
108. Log.i("lily","query table:"+uri.getPathSegments().get(0)+" column:"+uri.getPathSegments().get(1)+" value:"+uri.getPathSegments().get(2));
109. SQLiteDatabase db = mDbHelper.getReadableDatabase();
110. if (selection != null){
111. if (selection.length()>0){
112. selection += "AND "+LilyUser.UserColumns.NAME+" like "+name;
113. }
114. }
115. c = db.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
116. }else if (sUriMatcher.match(uri) == MULITABLE){
117. // format:authority/table1/table2 *******
118. String table1 = uri.getPathSegments().get(0);
119. String table2 = uri.getPathSegments().get(1);
120.
121. Log.i("lily","table1 = "+table1);
122. Log.i("lily","table2 = "+table2);
123.
124. if (table1.equalsIgnoreCase(TABLE_NAME)){
125. if (table2.equals(PRODUCT_TABLE)){
126. SQLiteDatabase db = mDbHelper.getReadableDatabase();
127. if (selection != null){
128. if (selection.length()>0){
129. selection += "AND "+LilyUser.UserColumns._ID+" = "+LilyUser.ShopListColumns.USER_ID;
130. }
131. else{
132. selection = LilyUser.UserColumns._ID+" = "+LilyUser.ShopListColumns.USER_ID;
133. }
134. }
135. else
136. {
137. selection = TABLE_NAME + "." +LilyUser.UserColumns._ID+" = "+PRODUCT_TABLE + "." + LilyUser.ShopListColumns.USER_ID;
138. }
139. c = db.query(table1+" cross join "+table2, projection, null, selectionArgs, null, null, sortOrder);
140. }
141. }
142. }
143.
144. return c;
145. }
146. @Override
147. public int update(Uri uri, ContentValues values, String selection,
148. String[] selectionArgs) {
149. Log.i("lily","LilyProvider-->update");
150. SQLiteDatabase db = mDbHelper.getWritableDatabase();
151. int rownum = db.update(TABLE_NAME, values, selection, selectionArgs);
152. return rownum;
153. }
154. }
这个里面定义Uri格式的时候一定要小心,不然出错了死都查不出来。
下面是使用查询的方法:
view plaincopy to clipboardprint?
1. private void queryNameUri() {
2. Uri uri = Uri.withAppendedPath(LilyUser.User.CONTENT_URI, "name/lily");//content://com.ianc.lilyprovider/customer/name/lily
3. String[] projection = {LilyUser.UserColumns._ID, LilyUser.UserColumns.NAME, LilyUser.UserColumns.PASSWORD};
4. String selection = null;
5. String [] selectionArgs = null;
6. String sortOrder = null;
7. Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
8. if (cursor == null){
9. Log.i("lily","cursor == null");
10. return;
11. }
12. if (cursor.moveToFirst()){
13. Log.i("lily","*********************************************");
14. String id;
15. String name;
16. String password;
17. do{
18. id = cursor.getString(cursor.getColumnIndex(LilyUser.UserColumns._ID));
19. Log.i("lily","id = "+id);
20.
21. name = cursor.getString(cursor.getColumnIndex(LilyUser.UserColumns.NAME));
22. Log.i("lily","name = "+name);
23.
24. password = cursor.getString(cursor.getColumnIndex(LilyUser.UserColumns.PASSWORD));
25. Log.i("lily","password = "+password);
26.
27. Log.i("lily","*********************************************");
28. }while(cursor.moveToNext());
29. }
30. else{
31. Log.i("lily","no result");
32. }
33. cursor.close();
34. }
多表查询:
view plaincopy to clipboardprint?
1. private void queryMultiTable() {
2. String[] projection = {"customer."+LilyUser.UserColumns._ID, "customer."+LilyUser.UserColumns.NAME, "customer."+LilyUser.UserColumns.PASSWORD,
3. "shoplist."+LilyUser.ShopListColumns.USER_ID, "shoplist."+LilyUser.ShopListColumns.PRODUCT, "shoplist."+LilyUser.ShopListColumns.DATE};
4. String selection = null;
5. String [] selectionArgs = null;
6. String sortOrder = null;
7. Uri uri = Uri.withAppendedPath(LilyUser.User.CONTENT_URI, "shoplist");
8. Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
9. if (cursor == null){
10. Log.i("lily","queryMultiTable()-->cursor == null");
11. return;
12. }
13. if (cursor.moveToFirst()){
14. Log.i("lily","*********************************************");
15. String id;
16. String name;
17. String password;
18. String user_id;
19. String product;
20. String date;
21. do{
22. id = cursor.getString(cursor.getColumnIndex(LilyUser.UserColumns._ID));
23. Log.i("lily","id = "+id);
24.
25. name = cursor.getString(cursor.getColumnIndex(LilyUser.UserColumns.NAME));
26. Log.i("lily","name = "+name);
27.
28. password = cursor.getString(cursor.getColumnIndex(LilyUser.UserColumns.PASSWORD));
29. Log.i("lily","password = "+password);
30.
31. user_id = cursor.getString(cursor.getColumnIndex(LilyUser.ShopListColumns.USER_ID));
32. Log.i("lily","user_id = "+user_id);
33.
34. product = cursor.getString(cursor.getColumnIndex(LilyUser.ShopListColumns.PRODUCT));
35. Log.i("lily","product = " + product);
36.
37. date = cursor.getString(cursor.getColumnIndex(LilyUser.ShopListColumns.DATE));
38. Log.i("lily","date = " + date);
39.
40. Log.i("lily","*********************************************");
41. }while(cursor.moveToNext());
42. }
43. else{
44. Log.i("lily","no result");
45. }
46. cursor.close();
47. }
接下来是LilyUser这个说明类的代码:
view plaincopy to clipboardprint?
1. package com.ianc.lilyprovider;
2. import android.net.Uri;
3. import android.provider.BaseColumns;
4. public class LilyUser {
5.
6. public static class User{
7. public static final Uri CONTENT_URI = Uri.parse("content://com.ianc.lilyprovider/" + "customer");
8. }
9. public static class UserColumns implements BaseColumns{
10. public static String NAME = "name";
11. public static String PASSWORD = "password";
12. }
13.
14. public static class ShopList{
15. public static final Uri CONTENT_URI = Uri.parse("content://com.ianc.lilyprovider/" + "shoplist");
16. }
17. public static class ShopListColumns implements BaseColumns{
18. public static String USER_ID = "user_id";
19. public static String PRODUCT = "product";
20. public static String DATE = "date";
21. }
22. }
我的理解:其实ContentProvider的机制很随意,它就类似于一个服务器一样,你把uri传来,只要按照特定的方式,它就能给你特定的功能,我觉得这个机制自由又方便。
其实这两个功能主要通过修改query就可以,完整的ContentProvider代码如下:
view plaincopy to clipboardprint?
1. package com.ianc.lilyprovider;
2. import android.content.ContentProvider;
3. import android.content.ContentValues;
4. import android.content.Context;
5. import android.content.UriMatcher;
6. import android.database.Cursor;
7. import android.database.sqlite.SQLiteDatabase;
8. import android.database.sqlite.SQLiteOpenHelper;
9. import android.net.Uri;
10. import android.util.Log;
11. public class LilyProvider extends ContentProvider {
12. final static String TABLE_NAME = "customer";
13. final static String PRODUCT_TABLE = "shoplist";
14. private static final String DATABASE_NAME = "lily.db";
15. private static String AUTHORITY = "com.ianc.lilyprovider";
16. private static final int DATABASE_VERSION = 1;
17.
18. DatabaseHelper mDbHelper;
19. static UriMatcher sUriMatcher;
20. private static final int USER = 1;
21. private static final int USER_NAME = 2;
22. private static final int MULITABLE = 3;
23. private static final int SHOPLIST = 4;
// 传入匹配码如果大于0表示匹配根路径或传入-1,即常量UriMatcher.NO_MATCH表示不匹配根路径
// addURI()方法是用来增加其他URI匹配路径的:
// 第一个参数代表传入标识ContentProvider的AUTHORITY字符串
// 第二个参数是要匹配的路径,#代表任意数字,另外还可以用*来匹配任意文本
// 第三个参数必须传入一个大于零的匹配码,用于match()方法对相匹配的URI返回相对应的匹配码
24. static{
25. sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
26. sUriMatcher.addURI(AUTHORITY, TABLE_NAME, USER);
27. sUriMatcher.addURI(AUTHORITY, PRODUCT_TABLE, SHOPLIST);
28. sUriMatcher.addURI(AUTHORITY, TABLE_NAME+"/"+LilyUser.UserColumns.NAME+"/*", USER_NAME);//search special user by name
29. sUriMatcher.addURI(AUTHORITY, TABLE_NAME+"/*", MULITABLE);
30. }
31. //内部类
32. class DatabaseHelper extends SQLiteOpenHelper {
33. public DatabaseHelper(Context context) {
34. super(context, DATABASE_NAME, null, DATABASE_VERSION);
35. }
36. @Override
37. public void onCreate(SQLiteDatabase db) {
38. Log.i("lily","LilyProvider-->DatabaseHelper-->onCreate");
39. db.execSQL("Create table " + TABLE_NAME + "( " +
40. LilyUser.UserColumns._ID+ " INTEGER PRIMARY KEY AUTOINCREMENT, " +
41. LilyUser.UserColumns._COUNT + " INTEGER,"+
42. LilyUser.UserColumns.NAME + " TEXT," +
43. LilyUser.UserColumns.PASSWORD +" TEXT" +
44. ");");
45. db.execSQL("Create table " + PRODUCT_TABLE + "( " +
46. LilyUser.ShopListColumns._ID+ " INTEGER PRIMARY KEY AUTOINCREMENT, " +
47. LilyUser.ShopListColumns._COUNT + " INTEGER,"+
48. LilyUser.ShopListColumns.USER_ID+" INTEGER,"+
49. LilyUser.ShopListColumns.PRODUCT + " TEXT," +
50. LilyUser.ShopListColumns.DATE +" TEXT" +
51. ");");
52. }
53. @Override
54. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
55. Log.i("lily","LilyProvider-->DatabaseHelper-->onUpgrade");
56. db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME+";");
57. db.execSQL("DROP TABLE IF EXISTS "+PRODUCT_TABLE+";");
58. onCreate(db);
59. }
60.
61. }
62. @Override
63. public int delete(Uri arg0, String arg1, String[] arg2) {
64. Log.i("lily","LilyProvider-->delete");
65. SQLiteDatabase db = mDbHelper.getWritableDatabase();
66. int rownum = db.delete(TABLE_NAME, arg1, arg2);
67. return rownum;
68. }
69. @Override
70. public String getType(Uri uri) {
71. Log.i("lily","LilyProvider-->getType");
72. return null;
73. }
74. @Override
75. public Uri insert(Uri uri, ContentValues values) {
76. Log.i("lily","LilyProvider-->insert");
77. if (sUriMatcher.match(uri) == USER){
78. SQLiteDatabase db = mDbHelper.getWritableDatabase();
79. db.insert(TABLE_NAME, null, values);
80. }
81. else if (sUriMatcher.match(uri) == SHOPLIST){
82. SQLiteDatabase db = mDbHelper.getWritableDatabase();
83. db.insert(PRODUCT_TABLE, null, values);
84. }
85.
86. return null;
87. }
88. @Override
89. public boolean onCreate() {
90. Log.i("lily","LilyProvider-->onCreate");
91. mDbHelper = new DatabaseHelper(this.getContext());
92. return false;
93. }
94. @Override
95. public Cursor query(Uri uri, String[] projection, String selection,
96. String[] selectionArgs, String sortOrder) {
97. Log.i("lily","LilyProvider-->query");
98. Log.i("lily","uri = "+uri);
99. Log.i("lily","sUriMatcher.match(uri)="+sUriMatcher.match(uri));
100. Cursor c = null;
101. if (sUriMatcher.match(uri) == USER){
102. SQLiteDatabase db = mDbHelper.getReadableDatabase();
103. c = db.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
104. }else if (sUriMatcher.match(uri) == USER_NAME){
105.
106. // format:authority/table/column/value-->0:table 1:column 2:value
107. String name = uri.getPathSegments().get(2);// get name value
108. Log.i("lily","query table:"+uri.getPathSegments().get(0)+" column:"+uri.getPathSegments().get(1)+" value:"+uri.getPathSegments().get(2));
109. SQLiteDatabase db = mDbHelper.getReadableDatabase();
110. if (selection != null){
111. if (selection.length()>0){
112. selection += "AND "+LilyUser.UserColumns.NAME+" like "+name;
113. }
114. }
115. c = db.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
116. }else if (sUriMatcher.match(uri) == MULITABLE){
117. // format:authority/table1/table2 *******
118. String table1 = uri.getPathSegments().get(0);
119. String table2 = uri.getPathSegments().get(1);
120.
121. Log.i("lily","table1 = "+table1);
122. Log.i("lily","table2 = "+table2);
123.
124. if (table1.equalsIgnoreCase(TABLE_NAME)){
125. if (table2.equals(PRODUCT_TABLE)){
126. SQLiteDatabase db = mDbHelper.getReadableDatabase();
127. if (selection != null){
128. if (selection.length()>0){
129. selection += "AND "+LilyUser.UserColumns._ID+" = "+LilyUser.ShopListColumns.USER_ID;
130. }
131. else{
132. selection = LilyUser.UserColumns._ID+" = "+LilyUser.ShopListColumns.USER_ID;
133. }
134. }
135. else
136. {
137. selection = TABLE_NAME + "." +LilyUser.UserColumns._ID+" = "+PRODUCT_TABLE + "." + LilyUser.ShopListColumns.USER_ID;
138. }
139. c = db.query(table1+" cross join "+table2, projection, null, selectionArgs, null, null, sortOrder);
140. }
141. }
142. }
143.
144. return c;
145. }
146. @Override
147. public int update(Uri uri, ContentValues values, String selection,
148. String[] selectionArgs) {
149. Log.i("lily","LilyProvider-->update");
150. SQLiteDatabase db = mDbHelper.getWritableDatabase();
151. int rownum = db.update(TABLE_NAME, values, selection, selectionArgs);
152. return rownum;
153. }
154. }
这个里面定义Uri格式的时候一定要小心,不然出错了死都查不出来。
下面是使用查询的方法:
view plaincopy to clipboardprint?
1. private void queryNameUri() {
2. Uri uri = Uri.withAppendedPath(LilyUser.User.CONTENT_URI, "name/lily");//content://com.ianc.lilyprovider/customer/name/lily
3. String[] projection = {LilyUser.UserColumns._ID, LilyUser.UserColumns.NAME, LilyUser.UserColumns.PASSWORD};
4. String selection = null;
5. String [] selectionArgs = null;
6. String sortOrder = null;
7. Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
8. if (cursor == null){
9. Log.i("lily","cursor == null");
10. return;
11. }
12. if (cursor.moveToFirst()){
13. Log.i("lily","*********************************************");
14. String id;
15. String name;
16. String password;
17. do{
18. id = cursor.getString(cursor.getColumnIndex(LilyUser.UserColumns._ID));
19. Log.i("lily","id = "+id);
20.
21. name = cursor.getString(cursor.getColumnIndex(LilyUser.UserColumns.NAME));
22. Log.i("lily","name = "+name);
23.
24. password = cursor.getString(cursor.getColumnIndex(LilyUser.UserColumns.PASSWORD));
25. Log.i("lily","password = "+password);
26.
27. Log.i("lily","*********************************************");
28. }while(cursor.moveToNext());
29. }
30. else{
31. Log.i("lily","no result");
32. }
33. cursor.close();
34. }
多表查询:
view plaincopy to clipboardprint?
1. private void queryMultiTable() {
2. String[] projection = {"customer."+LilyUser.UserColumns._ID, "customer."+LilyUser.UserColumns.NAME, "customer."+LilyUser.UserColumns.PASSWORD,
3. "shoplist."+LilyUser.ShopListColumns.USER_ID, "shoplist."+LilyUser.ShopListColumns.PRODUCT, "shoplist."+LilyUser.ShopListColumns.DATE};
4. String selection = null;
5. String [] selectionArgs = null;
6. String sortOrder = null;
7. Uri uri = Uri.withAppendedPath(LilyUser.User.CONTENT_URI, "shoplist");
8. Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
9. if (cursor == null){
10. Log.i("lily","queryMultiTable()-->cursor == null");
11. return;
12. }
13. if (cursor.moveToFirst()){
14. Log.i("lily","*********************************************");
15. String id;
16. String name;
17. String password;
18. String user_id;
19. String product;
20. String date;
21. do{
22. id = cursor.getString(cursor.getColumnIndex(LilyUser.UserColumns._ID));
23. Log.i("lily","id = "+id);
24.
25. name = cursor.getString(cursor.getColumnIndex(LilyUser.UserColumns.NAME));
26. Log.i("lily","name = "+name);
27.
28. password = cursor.getString(cursor.getColumnIndex(LilyUser.UserColumns.PASSWORD));
29. Log.i("lily","password = "+password);
30.
31. user_id = cursor.getString(cursor.getColumnIndex(LilyUser.ShopListColumns.USER_ID));
32. Log.i("lily","user_id = "+user_id);
33.
34. product = cursor.getString(cursor.getColumnIndex(LilyUser.ShopListColumns.PRODUCT));
35. Log.i("lily","product = " + product);
36.
37. date = cursor.getString(cursor.getColumnIndex(LilyUser.ShopListColumns.DATE));
38. Log.i("lily","date = " + date);
39.
40. Log.i("lily","*********************************************");
41. }while(cursor.moveToNext());
42. }
43. else{
44. Log.i("lily","no result");
45. }
46. cursor.close();
47. }
接下来是LilyUser这个说明类的代码:
view plaincopy to clipboardprint?
1. package com.ianc.lilyprovider;
2. import android.net.Uri;
3. import android.provider.BaseColumns;
4. public class LilyUser {
5.
6. public static class User{
7. public static final Uri CONTENT_URI = Uri.parse("content://com.ianc.lilyprovider/" + "customer");
8. }
9. public static class UserColumns implements BaseColumns{
10. public static String NAME = "name";
11. public static String PASSWORD = "password";
12. }
13.
14. public static class ShopList{
15. public static final Uri CONTENT_URI = Uri.parse("content://com.ianc.lilyprovider/" + "shoplist");
16. }
17. public static class ShopListColumns implements BaseColumns{
18. public static String USER_ID = "user_id";
19. public static String PRODUCT = "product";
20. public static String DATE = "date";
21. }
22. }
[2] 运用ActivityGroup来切换Activity和Layout
来源: 互联网 发布时间: 2014-02-18
使用ActivityGroup来切换Activity和Layout
在一个主界面中做Activity切换一般都会用TabActivity,使用方便,Activity互相之间相对独立,但是可定制性不强,而且修改起来很麻烦。当然也可以把layout分开,把逻辑代码全写在主界面的逻辑代码中,但是很明显可维护性相当差,这里通过ActivityGroup来解决这个问题。
要求点击底部不同图片按钮切换不同的Activity,并在中间显示Activity对应的ContentView
二、 实现代码
2.1 layout.xml
Java代码
1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:layout_width="fill_parent" android:orientation="vertical"
4. android:layout_height="fill_parent">
5. <LinearLayout android:gravity="center_horizontal"
6. android:background="@drawable/myinfor2" android:layout_width="fill_parent"
7. android:layout_height="wrap_content">
8. <TextView android:id="@+id/cust_title" android:textColor="@android:color/white"
9. android:textSize="28sp" android:text="模块1" android:layout_width="wrap_content"
10. android:layout_height="wrap_content"></TextView>
11. </LinearLayout>
12. <!-- 中间动态加载View -->
13. <ScrollView android:measureAllChildren="true" android:id="@+id/containerBody"
14. android:layout_weight="1" android:layout_height="fill_parent"
15. android:layout_width="fill_parent">
16. </ScrollView>
17. <LinearLayout android:background="@android:color/black"
18. android:layout_gravity="bottom" android:orientation="horizontal"
19. android:layout_width="fill_parent" android:layout_height="wrap_content">
20. <!-- 功能模块按钮1 -->
21. <ImageView android:id="@+id/btnModule1" android:src="/blog_article/@android_drawable/ic_dialog_dialer/index.html"
22. android:layout_marginLeft="7dp" android:layout_marginTop="3dp"
23. android:layout_marginBottom="3dp" android:layout_width="wrap_content"
24. android:layout_height="wrap_content" />
25. <!-- 功能模块按钮2 -->
26. <ImageView android:id="@+id/btnModule2" android:src="/blog_article/@android_drawable/ic_dialog_info/index.html"
27. android:layout_marginLeft="7dp" android:layout_marginTop="3dp"
28. android:layout_marginBottom="3dp" android:layout_width="wrap_content"
29. android:layout_height="wrap_content" />
30. <!-- 功能模块按钮3 -->
31. <ImageView android:id="@+id/btnModule3" android:src="/blog_article/@android_drawable/ic_dialog_alert/index.html"
32. android:layout_marginLeft="7dp" android:layout_marginTop="3dp"
33. android:layout_marginBottom="3dp" android:layout_width="wrap_content"
34. android:layout_height="wrap_content" />
35. </LinearLayout>
36. </LinearLayout>
2.2 TestView.java
Java代码
1. /**
2. * 使用ActivityGroup来切换Activity和Layout
3. * @author 农民伯伯
4. * @version 2010-9-7
5. *
6. */
7. public class TestView extends ActivityGroup {
8.
9. private ScrollView container = null;
10.
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. // 隐藏标题栏
15. requestWindowFeature(Window.FEATURE_NO_TITLE);
16. // 设置视图
17. setContentView(R.layout.layout);
18.
19. container = (ScrollView) findViewById(R.id.containerBody);
20.
21. // 模块1
22. ImageView btnModule1 = (ImageView) findViewById(R.id.btnModule1);
23. btnModule1.setOnClickListener(new OnClickListener() {
24. @Override
25. public void onClick(View v) {
26. container.removeAllViews();
27. container.addView(getLocalActivityManager().startActivity(
28. "Module1",
29. new Intent(TestView.this, ModuleView1.class)
30. .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
31. .getDecorView());
32. }
33. });
34.
35. // 模块2
36. ImageView btnModule2 = (ImageView) findViewById(R.id.btnModule2);
37. btnModule2.setOnClickListener(new OnClickListener() {
38. @Override
39. public void onClick(View v) {
40. container.removeAllViews();
41. container.addView(getLocalActivityManager().startActivity(
42. "Module2",
43. new Intent(TestView.this, ModuleView2.class)
44. .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
45. .getDecorView());
46. }
47. });
48.
49. // 模块3
50. ImageView btnModule3 = (ImageView) findViewById(R.id.btnModule3);
51. btnModule3.setOnClickListener(new OnClickListener() {
52. @Override
53. public void onClick(View v) {
54. container.removeAllViews();
55. container.addView(getLocalActivityManager().startActivity(
56. "Module3",
57. new Intent(TestView.this, ModuleView3.class)
58. .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
59. .getDecorView());
60. }
61. });
62. }
63. }
在一个主界面中做Activity切换一般都会用TabActivity,使用方便,Activity互相之间相对独立,但是可定制性不强,而且修改起来很麻烦。当然也可以把layout分开,把逻辑代码全写在主界面的逻辑代码中,但是很明显可维护性相当差,这里通过ActivityGroup来解决这个问题。
要求点击底部不同图片按钮切换不同的Activity,并在中间显示Activity对应的ContentView
二、 实现代码
2.1 layout.xml
Java代码
1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:layout_width="fill_parent" android:orientation="vertical"
4. android:layout_height="fill_parent">
5. <LinearLayout android:gravity="center_horizontal"
6. android:background="@drawable/myinfor2" android:layout_width="fill_parent"
7. android:layout_height="wrap_content">
8. <TextView android:id="@+id/cust_title" android:textColor="@android:color/white"
9. android:textSize="28sp" android:text="模块1" android:layout_width="wrap_content"
10. android:layout_height="wrap_content"></TextView>
11. </LinearLayout>
12. <!-- 中间动态加载View -->
13. <ScrollView android:measureAllChildren="true" android:id="@+id/containerBody"
14. android:layout_weight="1" android:layout_height="fill_parent"
15. android:layout_width="fill_parent">
16. </ScrollView>
17. <LinearLayout android:background="@android:color/black"
18. android:layout_gravity="bottom" android:orientation="horizontal"
19. android:layout_width="fill_parent" android:layout_height="wrap_content">
20. <!-- 功能模块按钮1 -->
21. <ImageView android:id="@+id/btnModule1" android:src="/blog_article/@android_drawable/ic_dialog_dialer/index.html"
22. android:layout_marginLeft="7dp" android:layout_marginTop="3dp"
23. android:layout_marginBottom="3dp" android:layout_width="wrap_content"
24. android:layout_height="wrap_content" />
25. <!-- 功能模块按钮2 -->
26. <ImageView android:id="@+id/btnModule2" android:src="/blog_article/@android_drawable/ic_dialog_info/index.html"
27. android:layout_marginLeft="7dp" android:layout_marginTop="3dp"
28. android:layout_marginBottom="3dp" android:layout_width="wrap_content"
29. android:layout_height="wrap_content" />
30. <!-- 功能模块按钮3 -->
31. <ImageView android:id="@+id/btnModule3" android:src="/blog_article/@android_drawable/ic_dialog_alert/index.html"
32. android:layout_marginLeft="7dp" android:layout_marginTop="3dp"
33. android:layout_marginBottom="3dp" android:layout_width="wrap_content"
34. android:layout_height="wrap_content" />
35. </LinearLayout>
36. </LinearLayout>
2.2 TestView.java
Java代码
1. /**
2. * 使用ActivityGroup来切换Activity和Layout
3. * @author 农民伯伯
4. * @version 2010-9-7
5. *
6. */
7. public class TestView extends ActivityGroup {
8.
9. private ScrollView container = null;
10.
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. // 隐藏标题栏
15. requestWindowFeature(Window.FEATURE_NO_TITLE);
16. // 设置视图
17. setContentView(R.layout.layout);
18.
19. container = (ScrollView) findViewById(R.id.containerBody);
20.
21. // 模块1
22. ImageView btnModule1 = (ImageView) findViewById(R.id.btnModule1);
23. btnModule1.setOnClickListener(new OnClickListener() {
24. @Override
25. public void onClick(View v) {
26. container.removeAllViews();
27. container.addView(getLocalActivityManager().startActivity(
28. "Module1",
29. new Intent(TestView.this, ModuleView1.class)
30. .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
31. .getDecorView());
32. }
33. });
34.
35. // 模块2
36. ImageView btnModule2 = (ImageView) findViewById(R.id.btnModule2);
37. btnModule2.setOnClickListener(new OnClickListener() {
38. @Override
39. public void onClick(View v) {
40. container.removeAllViews();
41. container.addView(getLocalActivityManager().startActivity(
42. "Module2",
43. new Intent(TestView.this, ModuleView2.class)
44. .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
45. .getDecorView());
46. }
47. });
48.
49. // 模块3
50. ImageView btnModule3 = (ImageView) findViewById(R.id.btnModule3);
51. btnModule3.setOnClickListener(new OnClickListener() {
52. @Override
53. public void onClick(View v) {
54. container.removeAllViews();
55. container.addView(getLocalActivityManager().startActivity(
56. "Module3",
57. new Intent(TestView.this, ModuleView3.class)
58. .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
59. .getDecorView());
60. }
61. });
62. }
63. }
[3] ContentProvider-一查询
来源: 互联网 发布时间: 2014-02-18
ContentProvider-1查询
今天看了android的官方文档中ContentProvider的那部分,因为数据库使用我一直很晕乎,我想要完成自己写一个provider,再写一个工程来使用它读数据,建数据,所以今天先学习了如何查询的这部分知识,首先是一些从官方文档中总结出来的几点:
1.查询必备的三个条件:
1.The URI that identifies the provider-->URI
2.The names of the data fields you want to receive-->data fields
3.The data types for those fields-->data types
所以写Provider的时候也必须要提供一个类,来把这些数据暴露给使用者们
2.查询有两种方法:
1. ContentResolver.query()
2. Activity.managedQuery():unloading itself when the activity pauses, and requerying itself when the activity restarts,可以使用Activity.startManagingCursor()来控制开始manage和使用stopManagingCursor(Cursor c)结束manage
当然查询数据库的方法肯定不止这两个,比如使用SQLiteDatabase的query方法,可以有更多复杂的查法。
3.如果你已知ID的情况下,可以这么查数据库
使用ContentUris.withAppendedId() 或 Uri.withAppendedPath()
例如:
view plaincopy to clipboardprint?
1. import android.provider.Contacts.People;
2. import android.content.ContentUris;
3. import android.net.Uri;
4. import android.database.Cursor;
5.
6. // Use the ContentUris method to produce the base URI for the contact with _ID == 23.
7. Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, 23);
8.
9. // Alternatively, use the Uri method to produce the base URI.
10. // It takes a string rather than an integer.
11. Uri myPerson = Uri.withAppendedPath(People.CONTENT_URI, "23");
12.
13. // Then query for this specific record:
14. Cursor cur = managedQuery(myPerson, null, null, null, null);
4.其他参数说明
• The names of the data columns that should be returned. A null value returns all columns. Otherwise, only columns that are listed by name are returned. All the content providers that come with the platform define constants for their columns. For example, the android.provider.Contacts.Phones class defines constants for the names of the columns in the phone table illustrated earlier — _ID, NUMBER, NUMBER_KEY, NAME, and so on.
• A filter detailing which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). A null value returns all rows (unless the URI limits the query to a single record).
• Selection arguments.
• A sorting order for the rows that are returned, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). A null value returns the records in the default order for the table, which may be unordered
5.取得查询结果
1. The Cursor lets you request the column name from the index of the column, or the index number from the column name.
(可以从从column name拿到column index,反之也可以从column index拿到column name)
2. Cursor object has a separate method for reading each type of data — such as getString(), getInt(), and getFloat().
(However, for most types, if you call the method for reading strings, the Cursor object will give you the String representation of the data.)
括号里面的这个功能很方便哟,我有试成功
具备了以上的基础之后,我写了一个例子来实现排序和模糊查找(需要使用正则表达式),不过我一直很想做的多表查询始终无果,有高手知道的麻烦告诉我一下吧。
代码如下:
view plaincopy to clipboardprint?
1. package com.ianc.querycontact;
2.
3. import android.app.Activity;
4. import android.content.ContentResolver;
5. import android.content.ContentUris;
6. import android.database.Cursor;
7. import android.net.Uri;
8. import android.os.Bundle;
9. import android.provider.Contacts;
10. import android.util.Log;
11.
12. public class QueryContact extends Activity {
13. /** Called when the activity is first created. */
14. @Override
15. public void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.main);
18. Uri uri = Contacts.People.CONTENT_URI;
19. String[] projection = {Contacts.People._ID, Contacts.People.PRIMARY_PHONE_ID, Contacts.PeopleColumns.NAME, Contacts.PeopleColumns.TIMES_CONTACTED};
20. String selection = Contacts.PeopleColumns.NAME + " like ?";
21. String[] selectionArgs = {"%li,%"};
22. String sortOrder = Contacts.PeopleColumns.NAME+" ASC";
23. Cursor cursor = managedQuery(uri, projection, selection, selectionArgs, sortOrder);
24. int nColumnIndex;
25. String id;
26. int phoneID;
27. String name;
28. String times;
29. ContentResolver cr = getContentResolver();
30. if(cursor.moveToFirst()){
31.
32. Log.i("lily", "total "+cursor.getCount()+" records.");
33.
34. do {
35. Log.i("lily", "***************************************");
36.
37. nColumnIndex = cursor.getColumnIndex(Contacts.People._ID);
38. id = cursor.getString(nColumnIndex);
39. Log.i("lily", "id = " + id);
40.
41. nColumnIndex = cursor.getColumnIndex(Contacts.People.PRIMARY_PHONE_ID);
42. phoneID = cursor.getInt(nColumnIndex);
43. Log.i("lily", "phoneID = " + phoneID);
44. Uri phoneuri = ContentUris.withAppendedId(Contacts.Phones.CONTENT_URI, phoneID);
45. String[] phoneprojection = {Contacts.Phones._ID, Contacts.PhonesColumns.NUMBER};
46. Cursor phonecursor = cr.query(phoneuri, phoneprojection, null, null, null);
47. if (phonecursor.moveToFirst()){
48. String phoneNumber = phonecursor.getString(phonecursor.getColumnIndex(Contacts.PhonesColumns.NUMBER));
49. Log.i("lily", "phoneNumber = " + phoneNumber);
50. }else{
51. Log.i("lily", "no phone number");
52. }
53. phonecursor.close();
54.
55.
56. nColumnIndex = cursor.getColumnIndex(Contacts.PeopleColumns.NAME);
57. name = cursor.getString(nColumnIndex);
58. Log.i("lily", "name = "+ name);
59.
60. nColumnIndex = cursor.getColumnIndex(Contacts.PeopleColumns.TIMES_CONTACTED);
61. times = cursor.getString(nColumnIndex);
62. Log.i("lily", "contact times = "+times);
63.
64. Log.i("lily", "***************************************");
65. }while(cursor.moveToNext());
66. }else{
67. Log.i("lily", "no result");
68. }
69. cursor.close();
70. }
71.
72. @Override
73. protected void onResume() {
74.
75. super.onResume();
76. }
77.
78. }
今天看了android的官方文档中ContentProvider的那部分,因为数据库使用我一直很晕乎,我想要完成自己写一个provider,再写一个工程来使用它读数据,建数据,所以今天先学习了如何查询的这部分知识,首先是一些从官方文档中总结出来的几点:
1.查询必备的三个条件:
1.The URI that identifies the provider-->URI
2.The names of the data fields you want to receive-->data fields
3.The data types for those fields-->data types
所以写Provider的时候也必须要提供一个类,来把这些数据暴露给使用者们
2.查询有两种方法:
1. ContentResolver.query()
2. Activity.managedQuery():unloading itself when the activity pauses, and requerying itself when the activity restarts,可以使用Activity.startManagingCursor()来控制开始manage和使用stopManagingCursor(Cursor c)结束manage
当然查询数据库的方法肯定不止这两个,比如使用SQLiteDatabase的query方法,可以有更多复杂的查法。
3.如果你已知ID的情况下,可以这么查数据库
使用ContentUris.withAppendedId() 或 Uri.withAppendedPath()
例如:
view plaincopy to clipboardprint?
1. import android.provider.Contacts.People;
2. import android.content.ContentUris;
3. import android.net.Uri;
4. import android.database.Cursor;
5.
6. // Use the ContentUris method to produce the base URI for the contact with _ID == 23.
7. Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, 23);
8.
9. // Alternatively, use the Uri method to produce the base URI.
10. // It takes a string rather than an integer.
11. Uri myPerson = Uri.withAppendedPath(People.CONTENT_URI, "23");
12.
13. // Then query for this specific record:
14. Cursor cur = managedQuery(myPerson, null, null, null, null);
4.其他参数说明
• The names of the data columns that should be returned. A null value returns all columns. Otherwise, only columns that are listed by name are returned. All the content providers that come with the platform define constants for their columns. For example, the android.provider.Contacts.Phones class defines constants for the names of the columns in the phone table illustrated earlier — _ID, NUMBER, NUMBER_KEY, NAME, and so on.
• A filter detailing which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). A null value returns all rows (unless the URI limits the query to a single record).
• Selection arguments.
• A sorting order for the rows that are returned, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). A null value returns the records in the default order for the table, which may be unordered
5.取得查询结果
1. The Cursor lets you request the column name from the index of the column, or the index number from the column name.
(可以从从column name拿到column index,反之也可以从column index拿到column name)
2. Cursor object has a separate method for reading each type of data — such as getString(), getInt(), and getFloat().
(However, for most types, if you call the method for reading strings, the Cursor object will give you the String representation of the data.)
括号里面的这个功能很方便哟,我有试成功
具备了以上的基础之后,我写了一个例子来实现排序和模糊查找(需要使用正则表达式),不过我一直很想做的多表查询始终无果,有高手知道的麻烦告诉我一下吧。
代码如下:
view plaincopy to clipboardprint?
1. package com.ianc.querycontact;
2.
3. import android.app.Activity;
4. import android.content.ContentResolver;
5. import android.content.ContentUris;
6. import android.database.Cursor;
7. import android.net.Uri;
8. import android.os.Bundle;
9. import android.provider.Contacts;
10. import android.util.Log;
11.
12. public class QueryContact extends Activity {
13. /** Called when the activity is first created. */
14. @Override
15. public void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.main);
18. Uri uri = Contacts.People.CONTENT_URI;
19. String[] projection = {Contacts.People._ID, Contacts.People.PRIMARY_PHONE_ID, Contacts.PeopleColumns.NAME, Contacts.PeopleColumns.TIMES_CONTACTED};
20. String selection = Contacts.PeopleColumns.NAME + " like ?";
21. String[] selectionArgs = {"%li,%"};
22. String sortOrder = Contacts.PeopleColumns.NAME+" ASC";
23. Cursor cursor = managedQuery(uri, projection, selection, selectionArgs, sortOrder);
24. int nColumnIndex;
25. String id;
26. int phoneID;
27. String name;
28. String times;
29. ContentResolver cr = getContentResolver();
30. if(cursor.moveToFirst()){
31.
32. Log.i("lily", "total "+cursor.getCount()+" records.");
33.
34. do {
35. Log.i("lily", "***************************************");
36.
37. nColumnIndex = cursor.getColumnIndex(Contacts.People._ID);
38. id = cursor.getString(nColumnIndex);
39. Log.i("lily", "id = " + id);
40.
41. nColumnIndex = cursor.getColumnIndex(Contacts.People.PRIMARY_PHONE_ID);
42. phoneID = cursor.getInt(nColumnIndex);
43. Log.i("lily", "phoneID = " + phoneID);
44. Uri phoneuri = ContentUris.withAppendedId(Contacts.Phones.CONTENT_URI, phoneID);
45. String[] phoneprojection = {Contacts.Phones._ID, Contacts.PhonesColumns.NUMBER};
46. Cursor phonecursor = cr.query(phoneuri, phoneprojection, null, null, null);
47. if (phonecursor.moveToFirst()){
48. String phoneNumber = phonecursor.getString(phonecursor.getColumnIndex(Contacts.PhonesColumns.NUMBER));
49. Log.i("lily", "phoneNumber = " + phoneNumber);
50. }else{
51. Log.i("lily", "no phone number");
52. }
53. phonecursor.close();
54.
55.
56. nColumnIndex = cursor.getColumnIndex(Contacts.PeopleColumns.NAME);
57. name = cursor.getString(nColumnIndex);
58. Log.i("lily", "name = "+ name);
59.
60. nColumnIndex = cursor.getColumnIndex(Contacts.PeopleColumns.TIMES_CONTACTED);
61. times = cursor.getString(nColumnIndex);
62. Log.i("lily", "contact times = "+times);
63.
64. Log.i("lily", "***************************************");
65. }while(cursor.moveToNext());
66. }else{
67. Log.i("lily", "no result");
68. }
69. cursor.close();
70. }
71.
72. @Override
73. protected void onResume() {
74.
75. super.onResume();
76. }
77.
78. }
最新技术文章: