1. 程式人生 > >Android 四大元件 ————ContenProvider(內容提供者)

Android 四大元件 ————ContenProvider(內容提供者)

1,介紹:

    內容提供者(Content Provider) 主要用於在不同的應用程式之間實現資料共享的功能,它提供了一套完整的機制,允許一個程式訪問另一個程式的資料,同時還能保證被訪資料的安全性。

2,簡單原理圖

3,程序間訪問對方資料庫:

【1】在A程序中建立資料庫

public class MyOpenHelper extends SQLiteOpenHelper {



    /**

     * @param context

     * name :資料庫名字

     * factory: 遊標工廠

     * version: 資料庫的版本

     */

    public MyOpenHelper(Context context) {

        super(context, "account.db", null, 1);

    }



    //Called when the database is created for the first time. 當資料庫第一次建立的時候呼叫 那麼這個方法適合做表結構的初始化

    @Override

    public void onCreate(SQLiteDatabase db) {



        db.execSQL("create table info (_id integer primary key autoincrement,name varchar(20),phone varchar(20),money varchar(20))");

        db.execSQL("insert into info ('name','phone','money') values ('張三','138888','2000')");

        db.execSQL("insert into info ('name','phone','money') values ('李四','139999','5000')");

    }

    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}

【2】Mian 方法中獲取資料庫例項,然後查詢當前資料庫訪問自己

public class MainActivity extends Activity {



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        

        //[1]獲取MyOpenHelper例項

        MyOpenHelper myOpenHelper = new MyOpenHelper(getApplicationContext());

        //[2]建立資料庫  代表當前資料庫的物件

        SQLiteDatabase db = myOpenHelper.getReadableDatabase();

        //[3]把張三和李四的資訊讀取出來

        Cursor cursor = db.query("info", null, null, null, null, null, null);

        if (cursor!=null && cursor.getCount()>0) {

            //[4]★ 想取出資料必須移動遊標

            while(cursor.moveToNext()){

                String name = cursor.getString(1);

                String money = cursor.getString(3);

                System.out.println("name:"+name+"----"+money);

            }

        }

    }

}

【3】  在A程序中內容提供者暴露出來資料。

import android.content.ContentProvider;

import android.content.ContentValues;

import android.content.UriMatcher;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.net.Uri;



public class AccountProvider extends ContentProvider {



    // [1]定義一個urimatcher路徑匹配器

    private static final UriMatcher sURIMatcher = new UriMatcher(

            UriMatcher.NO_MATCH);

    private static final int QUERYSUCESS = 0;

    private static final int INSERTSUCESS = 1;

    private static final int UPDATESUCESS = 2;

    private static final int DELETESUCESS = 3;

    private MyOpenHelper myOpenHelper;



    // [2]在靜態程式碼塊中新增路徑

    static {

        /**

         * authority:要和你在清單檔案裡面宣告authority一樣

         *

         * URL:統一資源定位符 https://www.baidu.com/tieba Uri:統一資源識別符號

         * com.xiaoshuai.db/query uri就是自己定義的一個路徑 代表一個含義

         *

         */

        sURIMatcher.addURI("com.xiaoshuai.db", "query", QUERYSUCESS);

        sURIMatcher.addURI("com.xiaoshuai.db", "insert", INSERTSUCESS);

        sURIMatcher.addURI("com.xiaoshuai.db", "update", UPDATESUCESS);

        sURIMatcher.addURI("com.xiaoshuai.db", "delete", DELETESUCESS);

    }

    @Override

    public boolean onCreate() {

        myOpenHelper = new MyOpenHelper(getContext());

        return false;

    }



    // 把這個方法對外暴露出去

    @Override

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

            String[] selectionArgs, String sortOrder) {

        // [1]獲取一個匹配碼

        int code = sURIMatcher.match(uri);

        if (code == QUERYSUCESS) {

            // 說明路徑匹配成功 把這個方法實現 實際上就是在這個方法對資料庫進行查詢的操作

            SQLiteDatabase db = myOpenHelper.getReadableDatabase();

            Cursor cursor = db.query("info", projection, selection,

                    selectionArgs, null, null, sortOrder);

            return cursor;

        } else {

            // 代表路徑匹配失敗

            return null;

            // throw new IllegalArgumentException("哥們路徑不正確 ,請檢查路徑");

        }

    }



    @Override

    public String getType(Uri uri) {

        return null;

    }



    @Override

    public Uri insert(Uri uri, ContentValues values) {

        int code = sURIMatcher.match(uri);

        if (code == INSERTSUCESS) {

            // 代表路徑匹配成功 把insert方法實現

            SQLiteDatabase db = myOpenHelper.getReadableDatabase();

            // 代表新插入行的id

            long insert = db.insert("info", null, values);

            Uri uri2 = Uri.parse("com.xiaoshuai.insert/" + insert);

            return uri2;

        } else {

            return null;

        }

    }

    @Override

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

        int code = sURIMatcher.match(uri);

        if (code == DELETESUCESS) {

            // 代表路徑匹配成功 把insert方法實現

            SQLiteDatabase db = myOpenHelper.getReadableDatabase();

            // 代表刪除的行數

            int delete = db.delete("info", selection, selectionArgs);

            return delete;

        } else {

            return 0;

        }

    }

    @Override

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

            String[] selectionArgs) {

        int code = sURIMatcher.match(uri);

        if (code == UPDATESUCESS) {

            // 代表路徑匹配成功 把insert方法實現

            SQLiteDatabase db = myOpenHelper.getReadableDatabase();

            // 代表更新的行數

            int update = db.update("info", values, selection, selectionArgs);

            return update;



        } else {

            return 0;

        }



    }



}

【4】在Android Manifest裡面註冊

<provider

android:authorities="com.xiaoshuai.db"

android:exported="true"

android:name=".AccountProvider" />

 

【5】在另一個程序中訪問A程序的資料庫  

  // 點選按鈕往資料庫裡面插入一條資料

    public void click1(View v) {



        // [1]由於第一個應用的資料庫系統已經通過內容提供者暴露出來 所以可以直接通過內容解析者操作資料庫

        Uri uri = Uri.parse("content://com.xiaoshuai.db/insert");

        // [2]建立contentValues

        ContentValues values = new ContentValues();

        // 引數1 是表的列名:

        values.put("name", "王五");

        values.put("money", "100");

        // [3]往資料庫裡面插入了一條資料

        Uri insert = getContentResolver().insert(uri, values);

        System.out.println("inset:::" + insert);



    }



    // 點選按鈕刪除資料庫的資料

    public void click2(View v) {

        // [1]由於第一個應用的資料庫系統已經通過內容提供者暴露出來 所以可以直接通過內容解析者操作資料庫

        Uri uri = Uri.parse("content://com.xiaoshuai.db/delete");

        int delete = getContentResolver().delete(uri, "name=?",

                new String[] { "王五" });

        Toast.makeText(getApplicationContext(), "刪除了" + delete + "行", 1).show();

    }



    // 點選修改一條記錄

    public void click3(View v) {

        Uri uri = Uri.parse("content://com.xiaoshuai.db/update");

        ContentValues values = new ContentValues();

        values.put("money", "10000");

        int update = getContentResolver().update(uri, values, "name=?",

                new String[] { "王五" });

        Toast.makeText(getApplicationContext(), "修改了了" + update + "行", 1)

                .show();

    }



    // 點選按鈕查詢資料庫

    public void click4(View v) {

        // 二由於第一個應用程式的資料庫已經通過內容提供者暴露出來 所以我使用內容解析者來獲取資料

        Uri uri = Uri.parse("content://com.xiaoshuai.db/query");

        Cursor cursor = getContentResolver().query(uri, null, null, null, null);

        if (cursor != null && cursor.getCount() > 0) {

            // ★★★ 想取出資料必須移動遊標

            while (cursor.moveToNext()) {

                String name = cursor.getString(1);

                String money = cursor.getString(3);

                System.out.println("第二個應用~~name:" + name + "----" + money);

            }

        }

}