Chinaunix首页 | 论坛 | 博客
  • 博客访问: 208413
  • 博文数量: 102
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1015
  • 用 户 组: 普通用户
  • 注册时间: 2013-06-05 16:45
文章存档

2014年(73)

2013年(29)

我的朋友

分类: Android平台

2014-04-10 07:28:38

01_19_ContentProvider初步(插入数据成功、但查询失败,得进一步调试)


最重要的是在AndroidMainfest.xml中注册provider

点击(此处)折叠或打开

  1. <provider android:name="mars.cp.FirstContentProvider"
  2.                  android:authorities="mars.cp.FirstContentProvider"/>
具体如下:

点击(此处)折叠或打开

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android=""
  3.       package="mars.cp"
  4.       android:versionCode="1"
  5.       android:versionName="1.0">
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">
  7.         <activity android:name=".CPActivity"
  8.                   android:label="@string/app_name">
  9.             <intent-filter>
  10.                 <action android:name="android.intent.action.MAIN" />
  11.                 <category android:name="android.intent.category.LAUNCHER" />
  12.             </intent-filter>
  13.         </activity>
  14.         <provider android:name="mars.cp.FirstContentProvider"
  15.                  android:authorities="mars.cp.FirstContentProvider"/>
  16.     </application>
  17.     <uses-sdk android:minSdkVersion="4" />
  18. </manifest>

点击(此处)折叠或打开

  1. //CPActivity.java
  2. package mars.cp;

  3. import mars.cp.FirstProviderMetaData.UserTableMetaData;
  4. import android.app.Activity;
  5. import android.content.ContentValues;
  6. import android.database.Cursor;
  7. import android.net.Uri;
  8. import android.os.Bundle;
  9. import android.view.View;
  10. import android.view.View.OnClickListener;
  11. import android.widget.Button;

  12. public class CPActivity extends Activity {
  13.     /** Called when the activity is first created. */
  14.     private Button insertButton = null;
  15.     private Button queryButton = null;

  16.     @Override
  17.     public void onCreate(Bundle savedInstanceState) {
  18.         super.onCreate(savedInstanceState);
  19.         setContentView(R.layout.main);
  20.         queryButton = (Button) findViewById(R.id.query);
  21.         queryButton.setOnClickListener(new QueryListener());
  22.         insertButton = (Button) findViewById(R.id.insert);
  23.         insertButton.setOnClickListener(new InsertListener());
  24.     //    System.out.println(getContentResolver().getType(FirstProviderMetaData.UserTableMetaData.CONTENT_URI));
  25.     }

  26.     class InsertListener implements OnClickListener {

  27.         @Override
  28.         public void onClick(View v) {
  29.             // TODO Auto-generated method stub
  30.             ContentValues values = new ContentValues(); //USER_NAME = "name"
  31.             values.put(FirstProviderMetaData.UserTableMetaData.USER_NAME,
  32.                     "zhangsan");
  33.             Uri uri = getContentResolver()
  34.                     .insert(            //CONTENT_URI = Uri.parse("content://" + AUTHORIY + "/users");
  35.                             FirstProviderMetaData.UserTableMetaData.CONTENT_URI,
  36.                             values);
  37.             System.out.println("uri--->" + uri.toString());
  38.         }

  39.     }

  40.     class QueryListener implements OnClickListener {

  41.         @Override
  42.         public void onClick(View v) {
  43.             // TODO Auto-generated method stub
  44.             Cursor c = getContentResolver().query( //这里有问题
  45.                     FirstProviderMetaData.UserTableMetaData.CONTENT_URI, null,
  46.                     null, null, null);
  47.             //query(Uri uri, String[] projection, String selection, String[] selectionArgs,String sortOrder)
  48.             while(c.moveToNext()){
  49.                 System.out.println(c.getString(c.getColumnIndex(UserTableMetaData.USER_NAME)));
  50.             }
  51.         }

  52.     }
  53. }

点击(此处)折叠或打开

  1. //FirstContentProvider.java
  2. package mars.cp;

  3. import java.util.HashMap;

  4. import mars.cp.FirstProviderMetaData.UserTableMetaData;
  5. import mars.sqlite3.db.DatabaseHelper;
  6. import android.content.ContentProvider;
  7. import android.content.ContentUris;
  8. import android.content.ContentValues;
  9. import android.content.UriMatcher;
  10. import android.database.Cursor;
  11. import android.database.SQLException;
  12. import android.database.sqlite.SQLiteDatabase;
  13. import android.database.sqlite.SQLiteQueryBuilder;
  14. import android.net.Uri;
  15. import android.text.TextUtils;

  16. public class FirstContentProvider extends ContentProvider {

  17.     public static final UriMatcher uriMatcher;
  18.     public static final int INCOMING_USER_COLLECTION = 1;
  19.     public static final int INCOMING_USER_SINGLE = 2;
  20.     private DatabaseHelper dh;
  21.     static {
  22.         uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
  23.         uriMatcher.addURI(FirstProviderMetaData.AUTHORIY, "/users",
  24.                 INCOMING_USER_COLLECTION);
  25.         uriMatcher.addURI(FirstProviderMetaData.AUTHORIY, "/users/#",
  26.                 INCOMING_USER_SINGLE);
  27.     }
  28.     
  29.     public static HashMap<String,String> userProjectionMap;
  30.     static
  31.     {
  32.         userProjectionMap = new HashMap<String,String>();
  33.         userProjectionMap.put(UserTableMetaData._ID,UserTableMetaData._ID);
  34.         userProjectionMap.put(UserTableMetaData.USER_NAME, UserTableMetaData.USER_NAME);
  35.     }
  36.     @Override
  37.     public int delete(Uri arg0, String arg1, String[] arg2) {
  38.         // TODO Auto-generated method stub
  39.         System.out.println("delete");
  40.         return 0;
  41.     }

  42.     //根据传入的URI,返回该URI所表示的数据类型
  43.     @Override
  44.     public String getType(Uri uri) {
  45.         // TODO Auto-generated method stub
  46.         System.out.println("getType");
  47.         switch(uriMatcher.match(uri)){
  48.         case INCOMING_USER_COLLECTION:
  49.             return UserTableMetaData.CONTENT_TYPE;
  50.         case INCOMING_USER_SINGLE:
  51.             return UserTableMetaData.CONTENT_TYPE_ITEM;
  52.         default:
  53.             throw new IllegalArgumentException("Unknown URI" + uri);
  54.         }
  55.     }

  56.     /**
  57.      * 该函数的返回值是一个Uri,这个Uri表示的是刚刚使用这个函数所插入的数据
  58.      * content://mars.cp.FirstContentProvider/users/1
  59.      */
  60.     @Override
  61.     public Uri insert(Uri uri, ContentValues values) {
  62.         System.out.println("insert");
  63.         SQLiteDatabase db = dh.getWritableDatabase();
  64.         long rowId = db.insert(UserTableMetaData.TABLE_NAME, null, values);//TABLE_NAME = "users";
  65.         if(rowId > 0){
  66.             Uri insertedUserUri = ContentUris.withAppendedId(UserTableMetaData.CONTENT_URI, rowId);
  67.             //通知监听器,数据已经改变
  68.             getContext().getContentResolver().notifyChange(insertedUserUri, null);
  69.             return insertedUserUri;
  70.         }
  71.         throw new SQLException("Failed to insert row into" + uri);
  72.     }

  73.     //是一个回调方法,所以说在ContentProvider创建的时候执行
  74.     @Override
  75.     public boolean onCreate() {
  76.         //打开数据库
  77.         dh = new DatabaseHelper(getContext(),FirstProviderMetaData.DATABASE_NAME);//DATABASE_NAME = "FirstProvider.db";
  78.         System.out.println("onCreate");
  79.         return true;
  80.     }

  81.     @Override
  82.     public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
  83.             String sortOrder) {
  84.         SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
  85.         switch(uriMatcher.match(uri)){
  86.         case INCOMING_USER_COLLECTION:
  87.             qb.setTables(UserTableMetaData.TABLE_NAME);
  88.             qb.setProjectionMap(userProjectionMap);
  89.             break;
  90.         case INCOMING_USER_SINGLE:
  91.             qb.setTables(UserTableMetaData.TABLE_NAME); //TABLE_NAME = "users"
  92.             qb.setProjectionMap(userProjectionMap);
  93.             qb.appendWhere(UserTableMetaData._ID + "=" + uri.getPathSegments().get(1));
  94.             break;
  95.         }
  96.         String orderBy;
  97.         if(TextUtils.isEmpty(sortOrder)){
  98.             orderBy = UserTableMetaData.DEFAULT_SORT_ORDER; //String DEFAULT_SORT_ORDER = "_id desc";
  99.         }
  100.         else{
  101.             orderBy = sortOrder;
  102.         }
  103.         SQLiteDatabase db = dh.getWritableDatabase();
  104.         //Cursor c = qb.query(db, projectionIn, selection, selectionArgs, groupBy, having, sortOrder)
  105.         Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);//这里有问题
  106.     
  107.         c.setNotificationUri(getContext().getContentResolver(), uri);
  108.         System.out.println("query");
  109.         return c;
  110.     }
  111.     //12-25 04:08:43.103: E/AndroidRuntime(487):     at mars.cp.FirstContentProvider.query(FirstContentProvider.java:111)
  112.     //12-25 04:08:43.103: E/AndroidRuntime(487): java.lang.IllegalStateException: Invalid tables
  113.     //12-25 04:08:43.103: E/AndroidRuntime(487):     at mars.cp.CPActivity$QueryListener.onClick(CPActivity.java:51)

  114.     @Override
  115.     public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
  116.         // TODO Auto-generated method stub
  117.         System.out.println("update");
  118.         return 0;
  119.     }

  120. }


点击(此处)折叠或打开

  1. //FirstProviderMetaData.java
  2. package mars.cp;

  3. import android.net.Uri;
  4. import android.provider.BaseColumns;

  5. public class FirstProviderMetaData {
  6.     public static final String AUTHORIY = "mars.cp.FirstContentProvider";
  7.     //数据库名称
  8.     public static final String DATABASE_NAME = "FirstProvider.db";
  9.     //数据库的版本
  10.     public static final int DATABASE_VERSION = 1;
  11.     //表名
  12.     public static final String USERS_TABLE_NAME = "users";
  13.     
  14.     public static final class UserTableMetaData implements BaseColumns{
  15.         //表名
  16.         public static final String TABLE_NAME = "users";
  17.         //访问该ContentProvider的URI
  18.         public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORIY + "/users");
  19.         //该ContentProvider所返回的数据类型的定义
  20.         public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.firstprovider.user";
  21.         public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/vnd.firstprovider.user";
  22.         //列名
  23.         public static final String USER_NAME = "name";
  24.         //默认的排序方法
  25.         public static final String DEFAULT_SORT_ORDER = "_id desc";
  26.     }
  27. }


点击(此处)折叠或打开

  1. //DatabaseHelper.java
  2. package mars.sqlite3.db;

  3. import mars.cp.FirstProviderMetaData;
  4. import android.content.Context;
  5. import android.database.sqlite.SQLiteDatabase;
  6. import android.database.sqlite.SQLiteOpenHelper;
  7. import android.database.sqlite.SQLiteDatabase.CursorFactory;

  8. //DatabaseHelper作为一个访问SQLite的助手类,提供两个方面的功能,
  9. //第一,getReadableDatabase(),getWritableDatabase()可以获得SQLiteDatabse对象,通过该对象可以对数据库进行操作
  10. //第二,提供了onCreate()和onUpgrade()两个回调函数,允许我们在创建和升级数据库时,进行自己的操作

  11. public class DatabaseHelper extends SQLiteOpenHelper {

  12.     private static final int VERSION = 1;

  13.     // 在SQLiteOepnHelper的子类当中,必须有该构造函数
  14.     public DatabaseHelper(Context context, String name, CursorFactory factory,
  15.             int version) {
  16.         // 必须通过super调用父类当中的构造函数
  17.         super(context, name, factory, version);
  18.         // TODO Auto-generated constructor stub
  19.     }

  20.     public DatabaseHelper(Context context, String name) {
  21.         this(context, name, VERSION);
  22.     }

  23.     public DatabaseHelper(Context context, String name, int version) {
  24.         this(context, name, null, version);
  25.     }

  26.     // 该函数是在第一次创建数据库的时候执行,实际上是在第一次得到SQLiteDatabse对象的时候,才会调用这个方法
  27.     @Override
  28.     public void onCreate(SQLiteDatabase db) {
  29.         // TODO Auto-generated method stub
  30.         System.out.println("create a Database");
  31.         // execSQL函数用于执行SQL语句
  32.         db.execSQL("create table " + FirstProviderMetaData.USERS_TABLE_NAME
  33.                 + "(" + FirstProviderMetaData.UserTableMetaData._ID
  34.                 + " INTEGER PRIMARY KEY AUTOINCREMENT,"
  35.                 + FirstProviderMetaData.UserTableMetaData.USER_NAME
  36.                 + " varchar(20));");
  37.     }

  38.     @Override
  39.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  40.         // TODO Auto-generated method stub
  41.         System.out.println("update a Database");
  42.     }

  43. }



阅读(434) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~