【Android基础入门〖6〗】四大组件之ContentProvider

简介

简而言之,ContentProvider 向别的应用程序提供数据(联系人这个应用程序提供了 它的 ContentProvider),ContentResolver 从 别的应用程序(已提供ContentProvider)获取、修改、添加数据(我们可以通过ContentResolver 来操纵联系人中的数据)。
 

说明

既然是四大组件之一,那么创建步骤基本相同
1: 自定义 ContentProvider
2: 注册
3: 使用
 

1    自定义ContentProvider

 MyProvider.java

  1. <SPAN style="FONT-WEIGHT: normal">package com.myprovider;  
  2. import android.content.ContentProvider;  
  3. import android.content.ContentUris;  
  4. import android.content.ContentValues;  
  5. import android.content.UriMatcher;  
  6. import android.database.Cursor;  
  7. import android.database.sqlite.SQLiteDatabase;  
  8. import android.net.Uri;  
  9. public class MyProvider extends ContentProvider{  
  10.     DatabaseHelper dbhelper;  
  11.     SQLiteDatabase db;  
  12.       
  13.     UriMatcher UMatcher=new UriMatcher(UriMatcher.NO_MATCH);  
  14.       
  15.     @Override  
  16.     public boolean onCreate() {  
  17.         // TODO 自动生成的方法存根   
  18.         dbhelper=new DatabaseHelper(getContext(), "michael"null1);  
  19.           
  20.         UMatcher.addURI("com.michael""michael"1);  
  21.         UMatcher.addURI("com.michael""michael/#"2);  
  22.         db=dbhelper.getWritableDatabase();  
  23.         return true;  
  24.     }  
  25.     @Override  
  26.     public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {  
  27.         // TODO 自动生成的方法存根   
  28.         Cursor cursor;  
  29.           
  30.         switch(UMatcher.match(uri))  
  31.         {  
  32.         case 1:  
  33.             cursor= db.query("michael", projection, selection, selectionArgs, nullnull, sortOrder);  
  34.             break;  
  35.         case 2:  
  36.             long id=ContentUris.parseId(uri);  
  37.             String myselection="_id="+id;  
  38.               
  39.             if(selection!=null)  
  40.                 myselection +=selection;      
  41.               
  42.             cursor =db.query("michael", projection, myselection, selectionArgs, nullnull, sortOrder);  
  43.             break;  
  44.         default:  
  45.             //非法的参数异常   
  46.             throw new IllegalArgumentException("unknow uri" + uri.toString());  
  47.         }  
  48.         return cursor;  
  49.     }  
  50.     @Override  
  51.     public String getType(Uri uri) {  
  52.         // TODO 自动生成的方法存根   
  53.         return null;  
  54.     }  
  55.     @Override  
  56.     public Uri insert(Uri uri, ContentValues values) {  
  57.         // TODO 自动生成的方法存根   
  58.         long id =db.insert("michael""username", values);  
  59.         return ContentUris.withAppendedId(uri, id);  
  60.     }  
  61.     @Override  
  62.     public int delete(Uri uri, String selection, String[] selectionArgs) {  
  63.         // TODO 自动生成的方法存根   
  64.         int num;  
  65.         switch(UMatcher.match(uri))  
  66.         {  
  67.         case 1:  
  68.             num=db.delete("michael", selection, selectionArgs);  
  69.             break;  
  70.         case 2:  
  71.             long id=ContentUris.parseId(uri);  
  72.             String myselection="_id="+id;  
  73.               
  74.             if(selection!=null)  
  75.                 myselection +=selection;  
  76.               
  77.             num= db.delete("michael", myselection, selectionArgs);  
  78.             break;  
  79.         default:  
  80.             //非法的参数异常   
  81.             throw new IllegalArgumentException("unknow uri" + uri.toString());  
  82.         }  
  83.         return num;  
  84.     }  
  85.     @Override  
  86.     public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {  
  87.         // TODO 自动生成的方法存根   
  88.         int num;  
  89.           
  90.         switch(UMatcher.match(uri))  
  91.         {  
  92.         case 1:  
  93.             num=db.update("michael", values, selection, selectionArgs);  
  94.             break;  
  95.         case 2:  
  96.             long id=ContentUris.parseId(uri);  
  97.             String myselection="_id="+id;  
  98.               
  99.             if(selection!=null)  
  100.                 myselection +=selection;  
  101.             num=db.update("michael", values, myselection, selectionArgs);  
  102.             break;  
  103.         default:  
  104.             //非法的参数异常   
  105.             throw new IllegalArgumentException("unknow uri" + uri.toString());  
  106.         }  
  107.         return num;  
  108.     }  
  109. }</SPAN>  
package com.myprovider;
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 MyProvider extends ContentProvider{
    DatabaseHelper dbhelper;
    SQLiteDatabase db;
    
    UriMatcher UMatcher=new UriMatcher(UriMatcher.NO_MATCH);
    
    @Override
    public boolean onCreate() {
        // TODO 自动生成的方法存根
        dbhelper=new DatabaseHelper(getContext(), "michael", null, 1);
        
        UMatcher.addURI("com.michael", "michael", 1);
        UMatcher.addURI("com.michael", "michael/#", 2);
        db=dbhelper.getWritableDatabase();
        return true;
    }
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        // TODO 自动生成的方法存根
        Cursor cursor;
        
        switch(UMatcher.match(uri))
        {
        case 1:
            cursor= db.query("michael", projection, selection, selectionArgs, null, null, sortOrder);
            break;
        case 2:
            long id=ContentUris.parseId(uri);
            String myselection="_id="+id;
            
            if(selection!=null)
                myselection +=selection;    
            
            cursor =db.query("michael", projection, myselection, selectionArgs, null, null, sortOrder);
            break;
        default:
            //非法的参数异常
            throw new IllegalArgumentException("unknow uri" + uri.toString());
        }
        return cursor;
    }
    @Override
    public String getType(Uri uri) {
        // TODO 自动生成的方法存根
        return null;
    }
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // TODO 自动生成的方法存根
        long id =db.insert("michael", "username", values);
        return ContentUris.withAppendedId(uri, id);
    }
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // TODO 自动生成的方法存根
        int num;
        switch(UMatcher.match(uri))
        {
        case 1:
            num=db.delete("michael", selection, selectionArgs);
            break;
        case 2:
            long id=ContentUris.parseId(uri);
            String myselection="_id="+id;
            
            if(selection!=null)
                myselection +=selection;
            
            num= db.delete("michael", myselection, selectionArgs);
            break;
        default:
            //非法的参数异常
            throw new IllegalArgumentException("unknow uri" + uri.toString());
        }
        return num;
    }
    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        // TODO 自动生成的方法存根
        int num;
        
        switch(UMatcher.match(uri))
        {
        case 1:
            num=db.update("michael", values, selection, selectionArgs);
            break;
        case 2:
            long id=ContentUris.parseId(uri);
            String myselection="_id="+id;
            
            if(selection!=null)
                myselection +=selection;
            num=db.update("michael", values, myselection, selectionArgs);
            break;
        default:
            //非法的参数异常
            throw new IllegalArgumentException("unknow uri" + uri.toString());
        }
        return num;
    }
}

2    封装的 SQLiteOpenHelper 用以操作数据库

DatabaseHelper.java

  1. <SPAN style="FONT-WEIGHT: normal">package com.myprovider;  
  2. import android.content.ContentValues;  
  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. public class DatabaseHelper extends SQLiteOpenHelper {  
  8.     public DatabaseHelper(Context context, String name, CursorFactory factory, int version) {  
  9.         super(context, name, factory, version);  
  10.     }  
  11.     @Override  
  12.     public void onCreate(SQLiteDatabase db) {  
  13.         //创建数据库   
  14.         db.execSQL("create table michael(_id integer primary key autoincrement ,username text);");  
  15.           
  16.         //初始数据   
  17.         ContentValues values=new ContentValues();  
  18.         values.put("username""张三");  
  19.         db.insert("michael""username", values);  
  20.         values.put("username""李四");  
  21.         db.insert("michael""username", values);  
  22.         values.put("username""王五");  
  23.         db.insert("michael""username", values);  
  24.         values.put("username""赵六");  
  25.         db.insert("michael""username", values);  
  26.     }  
  27.     @Override  
  28.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  29.         //升级数据库   
  30.         db.execSQL("drop table if exists michael;");  
  31.         this.onCreate(db);  
  32.     }  
  33. }</SPAN>  
package com.myprovider;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
    public DatabaseHelper(Context context, String name, CursorFactory factory, int version) {
        super(context, name, factory, version);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        //创建数据库
        db.execSQL("create table michael(_id integer primary key autoincrement ,username text);");
        
        //初始数据
        ContentValues values=new ContentValues();
        values.put("username", "张三");
        db.insert("michael", "username", values);
        values.put("username", "李四");
        db.insert("michael", "username", values);
        values.put("username", "王五");
        db.insert("michael", "username", values);
        values.put("username", "赵六");
        db.insert("michael", "username", values);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //升级数据库
        db.execSQL("drop table if exists michael;");
        this.onCreate(db);
    }
}

3    注册

AndroidManifest.xml

  1. <provider  
  2.     android:name="com.myprovider.MyProvider"  
  3.     android:authorities="com.michael"  
  4.     android:exported="true"/>  
<provider
    android:name="com.myprovider.MyProvider"
    android:authorities="com.michael"
    android:exported="true"/>

4    访问数据    (在别的应用程序中亦同)

意思是,你新建一个项目,具备如下代码,仍然能操作访问 上述项目中的数据 。 这就是 ContentProvider 的神奇之处 :)

4.1 MainActivity.java

  1. package com.myprovider;  
  2. import android.app.Activity;  
  3. import android.content.ContentResolver;  
  4. import android.content.ContentValues;  
  5. import android.database.Cursor;  
  6. import android.net.Uri;  
  7. import android.os.Bundle;  
  8. import android.widget.ListView;  
  9. import android.widget.SimpleCursorAdapter;  
  10. public class MainActivity extends Activity {  
  11.     @Override  
  12.     protected void onCreate(Bundle savedInstanceState) {  
  13.         super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.activity_main);  
  15.           
  16.         ContentResolver resolver=this.getContentResolver();  
  17.         Uri uri=Uri.parse("content://com.michael/michael");  
  18.         ContentValues values=new ContentValues();  
  19.         values.put("username""霸王龙");  
  20.         resolver.insert(uri, values);  
  21.         values.put("username""巨无霸");  
  22.         resolver.insert(uri, values);  
  23.         values.put("username""擎天柱");  
  24.         resolver.insert(uri, values);  
  25.         values.put("username""大黄蜂");  
  26.         resolver.insert(uri, values);  
  27.           
  28.         Cursor cursor=resolver.query(uri, new String[]{"_id","username"}, nullnullnull);  
  29.         SimpleCursorAdapter adapter=new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, new String[]{"_id","username"}, new int[]{android.R.id.text1,android.R.id.text2}, 0);  
  30.       
  31.         ListView listview=(ListView)findViewById(R.id.listview);  
  32.         listview.setAdapter(adapter);  
  33.     }  
  34. }  
package com.myprovider;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        ContentResolver resolver=this.getContentResolver();
        Uri uri=Uri.parse("content://com.michael/michael");
        ContentValues values=new ContentValues();
        values.put("username", "霸王龙");
        resolver.insert(uri, values);
        values.put("username", "巨无霸");
        resolver.insert(uri, values);
        values.put("username", "擎天柱");
        resolver.insert(uri, values);
        values.put("username", "大黄蜂");
        resolver.insert(uri, values);
        
        Cursor cursor=resolver.query(uri, new String[]{"_id","username"}, null, null, null);
        SimpleCursorAdapter adapter=new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, new String[]{"_id","username"}, new int[]{android.R.id.text1,android.R.id.text2}, 0);
    
        ListView listview=(ListView)findViewById(R.id.listview);
        listview.setAdapter(adapter);
    }
}

4.2 activity_main.xml 布局文件

  1. <ListView xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:id="@+id/listview"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"/>  
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

5    效果截图


 
 
 
  转载请注明出处,毕竟代码是一个一个敲出来的 :)

原:http://blog.csdn.net/mkrcpp/article/details/11992025
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值