Android開發之路十三———–ContentProvider串連

來源:互聯網
上載者:User
ContentProvider

1、PersonProvider

package cn.class3g.db;

 

import cn.class3g.service.DatabaseHelper;

import android.content.ContentProvider;

import android.content.ContentUris;

import android.content.ContentValues;

import android.content.UriMatcher;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.net.Uri;

 

public class PersonProvider extends ContentProvider {

       private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);

 

       private static final int PERSONS = 1;

       private static final int PERSON = 2;

 

       private DatabaseHelper dbHelper;

 

       static {

              matcher.addURI("cn.class3g.providers.personprovider", "person", PERSONS);

              matcher.addURI("cn.class3g.providers.personprovider", "person/#",

                            PERSON);

       }

 

       public boolean onCreate() {

              dbHelper = new DatabaseHelper(this.getContext());

              return true;

       }

 

       //  content://cn.itcast.provides.personprovider/person

       public Uri insert(Uri uri, ContentValues values) {

              SQLiteDatabase db = dbHelper.getWritableDatabase();

              long rowId;

 

              switch (matcher.match(uri)) {

              case PERSONS: //向表中添加新紀錄並返回其行號

                     rowId = db.insert("person", "personid", values);

                     return ContentUris.withAppendedId(uri, rowId);

              default:

                     throw new IllegalArgumentException("Unknow Uri:" + uri);

              }

       }

 

       public Cursor query(Uri uri, String[] projection, String selection,

                     String[] selectionArgs, String sortOrder) {

              SQLiteDatabase db = dbHelper.getReadableDatabase();

              switch (matcher.match(uri)) {

              case PERSONS:

                     return db.query("person", projection, selection, selectionArgs, null, null, sortOrder);

              case PERSON:

                     long personid = ContentUris.parseId(uri);

                     String where = "personid="+ personid;

                     if(selection!=null && !"".equals(selection)){

                            where = where + " and "+ selection;

                     }

                     return db.query("person", projection, where, selectionArgs, null, null, sortOrder);

                    

              default:

                     throw new IllegalArgumentException("Unknown Uri:"+ uri);

              }

       }

 

       //  content://cn.itcast.provides.personprovider/person 更新表中的所有記錄

       //  content://cn.itcast.provides.personprovider/person/10 更新表中指定id的記錄

       public int update(Uri uri, ContentValues values, String selection,

                     String[] selectionArgs) {

              SQLiteDatabase db = dbHelper.getWritableDatabase();

              int num;

              switch(matcher.match(uri)){

              case PERSONS: //更新指定記錄

                     num = db.update("person", values, selection, selectionArgs);

                     break;

              case PERSON:

                     long personid = ContentUris.parseId(uri);

                     String where = "personid=" + personid;

                     if(selection != null){

                            where += " and " + selection;

                     }

                     num = db.update("person", values, where, selectionArgs);

                     break;

              default:

                     throw new IllegalArgumentException("Unknow Uri"+uri);

              }

              return num;

       }

 

       public int delete(Uri uri, String selection, String[] selectionArgs) {

              SQLiteDatabase db = dbHelper.getWritableDatabase();

              int num = 0;

              switch (matcher.match(uri)) {

              case PERSONS:

                     num = db.delete("person", selection, selectionArgs);

                     break;

              case PERSON:

                     long personid = ContentUris.parseId(uri);

                     String where = "personid="+ personid;

                     if(selection!=null && !"".equals(selection)){

                            where = where + " and "+ selection;

                     }

                     num = db.delete("person", where, selectionArgs);

                     break;    

              default:

                     throw new IllegalArgumentException("Unknown Uri:"+ uri);

              }

              return num;

       }

 

       public String getType(Uri uri) {

              switch (matcher.match(uri)) {

              case PERSONS:

                     return "vnd.android.cursor.dir/person";

              case PERSON:

                     return "vnd.android.cursor.item/person";

              default:

                     throw new IllegalArgumentException("Unknown Uri:"+ uri);

              }

       }

}

2、配置

        <provider

            android:authorities="cn.class3g.providers.personprovider"

            android:name="PersonProvider" >

        </provider>

3、建立測試工程編寫測試代碼

package cn.class3g.visitor;

 

import android.content.ContentResolver;

import android.content.ContentValues;

import android.database.Cursor;

import android.net.Uri;

import android.test.AndroidTestCase;

import android.util.Log;

 

public class AccessContentProviderTest extends AndroidTestCase {

   

    public void testSave() throws Throwable{

       ContentResolver resolver = this.getContext().getContentResolver();

       Uri insertUri = Uri.parse("content://cn.class3g.providers.personprovider/person");

       ContentValues values = new ContentValues();

       values.put("name", "laozhang");

       values.put("age", "50");

       Uri uri = resolver.insert(insertUri, values);

       Log.i("TAG", uri.toString());

    }

   

    public void testQuery() throws Throwable{

       ContentResolver resolver = this.getContext().getContentResolver();

       Uri uri = Uri.parse("content://cn.class3g.providers.personprovider/person");

      

       Cursor cursor = resolver.query(uri, null,
null, null, "personid asc");

      

       while(cursor.moveToNext()){

           int personid = cursor.getInt(cursor.getColumnIndex("personid"));

           String name = cursor.getString(cursor.getColumnIndex("name"));

          

           Log.i("TAG", "personid="+ personid + ",name="+ name);

       }

       cursor.close();

    }

   

    public void testUpdate() throws Throwable{

       ContentResolver contentResolver = this.getContext().getContentResolver();

       Uri updateUri = Uri.parse("content://cn.class3g.providers.personprovider/person/5");

       ContentValues values = new ContentValues();

       values.put("name", "蔣介石");

       contentResolver.update(updateUri, values, null,
null);

    }

    public void testDelete() throws Throwable{

       ContentResolver contentResolver = this.getContext().getContentResolver();

       Uri uri = Uri.parse("content://cn.class3g.providers.personprovider/person/5");

       contentResolver.delete(uri, null,
null
);

    }  

}

 

 

4、測試(注意需要先將provider擁有者工程部署到裝置上)

5、ContentProvider的監聽器

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.