ANDROID_MARS学习笔记_S01原始版_010_ContentProvider

一、简介

ANDROID_MARS学习笔记_S01原始版_010_ContentProvider_第1张图片

一、代码
1.xml
(1)main.xml

1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3     android:orientation="vertical" android:layout_width="fill_parent"
4     android:layout_height="fill_parent">
5     <Button android:id="@+id/insertButton" android:layout_width="fill_parent"
6         android:layout_height="wrap_content" android:text="insert" />
7     <Button android:id="@+id/queryButton" android:layout_width="fill_parent"
8         android:layout_height="wrap_content" android:text="query" />
9 </LinearLayout>

 

(2)AndroidManifest.xml.xml

 

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.example.s01_original_e16_textcp"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6 
 7     <uses-sdk
 8         android:minSdkVersion="8"
 9         android:targetSdkVersion="21" />
10 
11     <application
12         android:allowBackup="true"
13         android:icon="@drawable/ic_launcher"
14         android:label="@string/app_name"
15         android:theme="@style/AppTheme" >
16         <activity
17             android:name=".CPActivity"
18             android:label="@string/app_name" >
19             <intent-filter>
20                 <action android:name="android.intent.action.MAIN" />
21 
22                 <category android:name="android.intent.category.LAUNCHER" />
23             </intent-filter>
24         </activity>
25         <provider android:name="com.example.s01_original_e16_textcp.FirstContentProvider"
26             android:authorities="tony.cp.FirstContentProvider" />
27     </application>
28 
29 </manifest>

 

 

 

2.java
(1)CPActivity.java

 1 package com.example.s01_original_e16_textcp;
 2 
 3 import android.app.Activity;
 4 import android.content.ContentValues;
 5 import android.database.Cursor;
 6 import android.net.Uri;
 7 import android.os.Bundle;
 8 import android.view.View;
 9 import android.widget.Button;
10 
11 import com.example.s01_original_e16_textcp.FirstProviderMetaData.UserTableMetaData;
12 
13 public class CPActivity extends Activity {
14     /** Called when the activity is first created. */
15     private Button insertButton = null;
16     private Button queryButton = null;
17 
18     @Override
19     public void onCreate(Bundle savedInstanceState) {
20         super.onCreate(savedInstanceState);
21         setContentView(R.layout.main);
22         insertButton = (Button) findViewById(R.id.insertButton);
23         insertButton.setOnClickListener(new View.OnClickListener() {
24 
25             @Override
26             public void onClick(View v) {
27                 ContentValues values = new ContentValues();
28                 values.put(FirstProviderMetaData.UserTableMetaData.USER_NAME,
29                         "zhangsan");
30                 Uri uri = getContentResolver().insert(
31                         FirstProviderMetaData.UserTableMetaData.CONTENT_URI,
32                         values);
33                 System.out.println("uri  ---> " + uri.toString());
34             }
35         });
36         queryButton = (Button) findViewById(R.id.queryButton);
37         queryButton.setOnClickListener(new View.OnClickListener() {
38 
39             @Override
40             public void onClick(View v) {
41                 Cursor c = getContentResolver().query(
42                         FirstProviderMetaData.UserTableMetaData.CONTENT_URI,
43                         null, null, null, null);
44                 while (c.moveToNext()) {
45                     System.out.println(c.getString(c
46                             .getColumnIndex(UserTableMetaData.USER_NAME)));
47                 }
48 
49             }
50         });
51     }
52 }

 

(2)FirstContentProvider.java

 

  1 package com.example.s01_original_e16_textcp;
  2 
  3 import java.util.HashMap;
  4 
  5 import android.content.ContentProvider;
  6 import android.content.ContentUris;
  7 import android.content.ContentValues;
  8 import android.content.UriMatcher;
  9 import android.database.Cursor;
 10 import android.database.SQLException;
 11 import android.database.sqlite.SQLiteDatabase;
 12 import android.database.sqlite.SQLiteQueryBuilder;
 13 import android.net.Uri;
 14 import android.text.TextUtils;
 15 
 16 import com.example.s01_original_e16_textcp.FirstProviderMetaData.UserTableMetaData;
 17 
 18 public class FirstContentProvider extends ContentProvider {
 19 
 20     // UriMatcher用来检查URI是否合法
 21     public static final UriMatcher uriMatcher;
 22     public static final int INCOMING_USER_COLLECTION = 1;
 23     public static final int INCOMING_USER_SINGLE = 2;
 24 
 25     private DatabaseHelper dh;
 26 
 27     static {
 28         uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
 29         uriMatcher.addURI(FirstProviderMetaData.AUTHORITY, "users",
 30                 INCOMING_USER_COLLECTION);
 31         uriMatcher.addURI(FirstProviderMetaData.AUTHORITY, "users/#",
 32                 INCOMING_USER_SINGLE);
 33     }
 34 
 35     //相当于给sql的列起别名
 36     public static HashMap<String, String> userProjectionMap;
 37     static {
 38         userProjectionMap = new HashMap<String, String>();
 39         userProjectionMap.put(UserTableMetaData._ID, UserTableMetaData._ID);
 40         userProjectionMap.put(UserTableMetaData.USER_NAME,
 41                 UserTableMetaData.USER_NAME);
 42     }
 43 
 44     @Override
 45     public int delete(Uri arg0, String arg1, String[] arg2) {
 46         // TODO Auto-generated method stub
 47         System.out.println("delete...");
 48         return 0;
 49     }
 50 
 51     // 根据传入的URI,返回该URI所表示的数据类型
 52     @Override
 53     public String getType(Uri uri) {
 54         System.out.println("getType...");
 55         switch (uriMatcher.match(uri)) {
 56         case INCOMING_USER_COLLECTION:
 57             return UserTableMetaData.CONTENT_TYPE;
 58         case INCOMING_USER_SINGLE:
 59             return UserTableMetaData.CONTENT_TYPE_ITEM;
 60         default:
 61             throw new IllegalArgumentException("Unknow URI " + uri);
 62         }
 63     }
 64 
 65     /**
 66      * 该函数的返回值是一个Uri,这个Uri表示的是刚刚那使用这个函数所插入的数据
 67      * content://ycitss.cp.firstContentProivder/users/1
 68      */
 69     @Override
 70     public Uri insert(Uri uri, ContentValues values) {
 71         System.out.println("insert...");
 72         SQLiteDatabase db = dh.getWritableDatabase();
 73         long rowId = db.insert(UserTableMetaData.TABLE_NAME, null, values);
 74         if (rowId > 0) {
 75             Uri insertedUserUri = ContentUris.withAppendedId(
 76                     UserTableMetaData.CONTENT_URI, rowId);
 77             // 通知监听器,数据已经修改
 78             getContext().getContentResolver().notifyChange(insertedUserUri,
 79                     null);
 80             return insertedUserUri;
 81         }
 82         throw new SQLException("Failed to insert row into " + uri);
 83     }
 84 
 85     // 是一个回调方法,所以说在ContentProvider创建的时候执行
 86     @Override
 87     public boolean onCreate() {
 88         dh = new DatabaseHelper(getContext(),
 89                 FirstProviderMetaData.DATABASE_NAME);
 90         System.out.println("onCreate...");
 91         return true;
 92     }
 93 
 94     @Override
 95     public Cursor query(Uri uri, String[] projection, String selection,
 96             String[] selectionArgs, String sortOrder) {
 97         SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
 98         switch (uriMatcher.match(uri)) {
 99         case INCOMING_USER_COLLECTION:
100             qb.setTables(UserTableMetaData.TABLE_NAME);
101             qb.setProjectionMap(userProjectionMap);
102             break;
103         case INCOMING_USER_SINGLE:
104             qb.setTables(UserTableMetaData.TABLE_NAME);
105             qb.setProjectionMap(userProjectionMap);
106             qb.appendWhere(UserTableMetaData._ID + "="
107                     + uri.getPathSegments().get(1));
108             break;
109         }
110         String orderBy;
111         if (TextUtils.isEmpty(sortOrder)) {
112             orderBy = UserTableMetaData.DEFAULT_SORT_ORDER;
113         } else {
114             orderBy = sortOrder;
115         }
116         SQLiteDatabase db = dh.getWritableDatabase();
117         Cursor c = qb.query(db, projection, selection, selectionArgs, null,
118                 null, orderBy);
119         c.setNotificationUri(getContext().getContentResolver(), uri);
120         System.out.println("query...");
121         return c;
122     }
123 
124     @Override
125     public int update(Uri uri, ContentValues values, String selection,
126             String[] selectionArgs) {
127         System.out.println("update...");
128         return 0;
129     }
130 
131 }

 

 

 

(3)FirstProviderMetaData.java

 1 package com.example.s01_original_e16_textcp;
 2 
 3 import android.net.Uri;
 4 import android.provider.BaseColumns;
 5 
 6 public class FirstProviderMetaData {
 7     // 必需与AndroidManifest.xml中定义的android:authorities一致
 8     public static final String AUTHORITY = "tony.cp.FirstContentProvider";
 9     // 数据库名称
10     public static final String DATABASE_NAME = "FirstProvider.db";
11     // 数据库版本
12     public static final int DATABASE_VERSION = 1;
13     // 表名
14     public static final String USERS_TABLE_NAME = "users";
15 
16     public static final class UserTableMetaData implements BaseColumns {
17         // 表名
18         public static final String TABLE_NAME = "users";
19         // 访问该ContentProvider的URI
20         public static final Uri CONTENT_URI = Uri.parse("content://"
21                 + AUTHORITY + "/users");
22         // 该contentProvider所返回的数据类型的定义
23         public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.firstprovider.user";//访问整张表
24         public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/vnd.firstprovider.user";//取一条数据
25         // 列名
26         public static final String USER_NAME = "name";
27         // 默认的排序方法
28         public static final String DEFAULT_SORT_ORDER = "_id desc";
29     }
30 }

 

(4)DatabaseHelper.java

 1 package com.example.s01_original_e16_textcp;
 2 
 3 import android.content.Context;
 4 import android.database.sqlite.SQLiteDatabase;
 5 import android.database.sqlite.SQLiteDatabase.CursorFactory;
 6 import android.database.sqlite.SQLiteOpenHelper;
 7 
 8 public class DatabaseHelper extends SQLiteOpenHelper {
 9     private static final int VERSION = 1;
10 
11     public DatabaseHelper(Context context, String name, CursorFactory factory,
12             int version) {
13         super(context, name, factory, version);
14         // TODO Auto-generated constructor stub
15     }
16 
17     public DatabaseHelper(Context context, String name, int version) {
18         this(context, name, null, version);
19     }
20 
21     public DatabaseHelper(Context context, String name) {
22         this(context, name, VERSION);
23     }
24 
25     // 该函数是在第一次创建数据库的时候执行,实际上是在第一次得到SQLiteDAtabase对象的时候,才会调用这个方法
26     @Override
27     public void onCreate(SQLiteDatabase db) {
28         System.out.println("cteate a Database");
29         // execSQL函数用于执行SQL语句
30         db.execSQL("create table " + FirstProviderMetaData.USERS_TABLE_NAME
31                 + "(" + FirstProviderMetaData.UserTableMetaData._ID
32                 + " INTEGER_PARIMARY_AUTOINCREMENT,"
33                 + FirstProviderMetaData.UserTableMetaData.USER_NAME
34                 + " varchar(20))");
35     }
36 
37     @Override
38     public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
39         System.out.println("update a Database");
40     }
41 
42 }

 

你可能感兴趣的:(ANDROID_MARS学习笔记_S01原始版_010_ContentProvider)