1. 程式人生 > >Android ContentProvider實現兩個程式間資料共享demo

Android ContentProvider實現兩個程式間資料共享demo

1、客戶端程式碼:

先實現服務端

SQL建立:

public class DBHelper extends SQLiteOpenHelper {

    // 資料庫名
    private static final String DATABASE_NAME = "finch.db";

    // 表名
    public static final String USER_TABLE_NAME = "user";
    public static final String JOB_TABLE_NAME = "job";

    private static final int DATABASE_VERSION = 1;
    //資料庫版本號

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        // 建立兩個表格:使用者表 和職業表
        db.execSQL("CREATE TABLE IF NOT EXISTS " + USER_TABLE_NAME + "(_id INTEGER PRIMARY KEY AUTOINCREMENT," + " name TEXT)");

        db.execSQL("CREATE TABLE IF NOT EXISTS " + JOB_TABLE_NAME + "(_id INTEGER PRIMARY KEY AUTOINCREMENT," + " job TEXT)");
    }

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

    }
}
ContentProvider類程式碼:

 

public class MyProvider extends ContentProvider {

    private Context mContext;
    DBHelper mDbHelper = null;
    SQLiteDatabase db = null;
    public static final String AUTOHORITY = "scut.carson_ho.myprovider";
    // 設定ContentProvider的唯一標識

    public static final int User_Code = 1;
    public static final int Job_Code = 2;

    // UriMatcher類使用:在ContentProvider 中註冊URI
    private static final UriMatcher mMatcher;
    static{
        mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        // 初始化
        mMatcher.addURI(AUTOHORITY,"user", User_Code);
        mMatcher.addURI(AUTOHORITY, "job", Job_Code);
        // 若URI資源路徑 = content://cn.scu.myprovider/user ,則返回註冊碼User_Code
        // 若URI資源路徑 = content://cn.scu.myprovider/job ,則返回註冊碼Job_Code
    }

    // 以下是ContentProvider的6個方法

    /**
     * 初始化ContentProvider
     */
    @Override
    public boolean onCreate() {

        mContext = getContext();
        // 在ContentProvider建立時對資料庫進行初始化
        // 執行在主執行緒,故不能做耗時操作,此處僅作展示
        mDbHelper = new DBHelper(getContext());
        db = mDbHelper.getWritableDatabase();

        // 初始化兩個表的資料(先清空兩個表,再各加入一個記錄)
        db.execSQL("delete from user");
        db.execSQL("insert into user values(1,'Carson');");
        db.execSQL("insert into user values(2,'Kobe');");

        db.execSQL("delete from job");
        db.execSQL("insert into job values(1,'Android');");
        db.execSQL("insert into job values(2,'iOS');");

        return true;
    }

    /**
     * 新增資料
     */

    @Override
    public Uri insert(Uri uri, ContentValues values) {

        // 根據URI匹配 URI_CODE,從而匹配ContentProvider中相應的表名
        // 該方法在最下面
        String table = getTableName(uri);

        // 向該表新增資料
        db.insert(table, null, values);

        // 當該URI的ContentProvider資料發生變化時,通知外界(即訪問該ContentProvider資料的訪問者)
        mContext.getContentResolver().notifyChange(uri, null);

//        // 通過ContentUris類從URL中獲取ID
//        long personid = ContentUris.parseId(uri);
//        System.out.println(personid);

        return uri;
        }

    /**
     * 查詢資料
     */
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        // 根據URI匹配 URI_CODE,從而匹配ContentProvider中相應的表名
        // 該方法在最下面
        String table = getTableName(uri);

//        // 通過ContentUris類從URL中獲取ID
//        long personid = ContentUris.parseId(uri);
//        System.out.println(personid);

        // 查詢資料
        return db.query(table,projection,selection,selectionArgs,null,null,sortOrder,null);
    }

    /**
     * 更新資料
     */
    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        // 由於不展示,此處不作展開
        return 0;
    }

    /**
     * 刪除資料
     */
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // 由於不展示,此處不作展開
        return 0;
    }

    @Override
    public String getType(Uri uri) {

        // 由於不展示,此處不作展開
        return null;
    }

    /**
     * 根據URI匹配 URI_CODE,從而匹配ContentProvider中相應的表名
     */
    private String getTableName(Uri uri){
        String tableName = null;
        switch (mMatcher.match(uri)) {
            case User_Code:
                tableName = DBHelper.USER_TABLE_NAME;
                break;
            case Job_Code:
                tableName = DBHelper.JOB_TABLE_NAME;
                break;
        }
        return tableName;
        }
    }

服務端原始碼:https://download.csdn.net/download/meixi_android/10698025

 

客戶端通過uri連結到服務端:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /**
         * 對user表進行操作
         */

        // 設定URI
        Uri uri_user = Uri.parse("content://scut.carson_ho.myprovider/user");
//        Uri uri_user = Uri.parse("content://cn.scu.myprovider/user");

        // 插入表中資料
        ContentValues values = new ContentValues();
        values.put("_id", 4);
        values.put("name", "Jordan");


        // 獲取ContentResolver
        ContentResolver resolver =  getContentResolver();
        // 通過ContentResolver 根據URI 向ContentProvider中插入資料
        resolver.insert(uri_user,values);

        // 通過ContentResolver 向ContentProvider中查詢資料
        Cursor cursor = resolver.query(uri_user, new String[]{"_id","name"}, null, null, null);
        while (cursor.moveToNext()){
            System.out.println("query11111 book:" + cursor.getInt(0) +" "+ cursor.getString(1));
            // 將表中資料全部輸出
        }
        cursor.close();
        // 關閉遊標

        /**
         * 對job表進行操作
         */
        // 和上述類似,只是URI需要更改,從而匹配不同的URI CODE,從而找到不同的資料資源
        Uri uri_job = Uri.parse("content://scut.carson_ho.myprovider/job");
//        Uri uri_job = Uri.parse("content://cn.scu.myprovider/job");

        // 插入表中資料
        ContentValues values2 = new ContentValues();
        values2.put("_id", 4);
        values2.put("job", "NBA Player");

        // 獲取ContentResolver
        ContentResolver resolver2 =  getContentResolver();
        // 通過ContentResolver 根據URI 向ContentProvider中插入資料
        resolver2.insert(uri_job,values2);

        // 通過ContentResolver 向ContentProvider中查詢資料
        Cursor cursor2 = resolver2.query(uri_job, new String[]{"_id","job"}, null, null, null);
        while (cursor2.moveToNext()){
            System.out.println("query11111 job:" + cursor2.getInt(0) +" "+ cursor2.getString(1));
            // 將表中資料全部輸出
        }
        cursor2.close();
        // 關閉遊標
    }
}

客戶端原始碼:https://download.csdn.net/download/meixi_android/10698034