第一行代码 第7章 内容提供器 --实现跨程序数据共享

DatabaseTest.apk源码如下:

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private MyDatabaseHelper myDatabaseHelper;

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

        myDatabaseHelper = new MyDatabaseHelper(this, "BookStore.db", null, 1);

        Button createDatabase = (Button)findViewById(R.id.create_database);
        createDatabase.setOnClickListener(this);

        Button addData = (Button)findViewById(R.id.add_data);
        addData.setOnClickListener(this);

        Button updateData = (Button)findViewById(R.id.update_data);
        updateData.setOnClickListener(this);

        Button deleteData = (Button)findViewById(R.id.delete_data);
        deleteData.setOnClickListener(this);

        Button queryData = (Button)findViewById(R.id.query_data);
        queryData.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        SQLiteDatabase db = myDatabaseHelper.getReadableDatabase();
        ContentValues values = new ContentValues();
        switch (view.getId()){
            case R.id.create_database:
                //myDatabaseHelper.getReadableDatabase();
                break;
            case R.id.add_data:
                values.put("author", "admin");
                values.put("book_name", "Android");
                values.put("pages", 800);
                values.put("price", 68.4);
                db.insert("Book", null, values);
                values.clear();

                values.put("author", "sky");
                values.put("book_name", "Iphone");
                values.put("pages", 1000);
                values.put("price", 78.2);
                db.insert("Book", null, values);
                break;
            case R.id.update_data:
                values.put("price", 12.02);
                db.update("Book", values, "book_name=?", new String[]{"Android"});
                break;
            case R.id.delete_data:
                db.delete("Book", "book_name=?", new String[]{"Android"});
                break;
            case R.id.query_data:
                int count = 0;
                Cursor cursor = db.query("Book", null, null, null, null, null,null);
                if(cursor.moveToFirst()){
                    do{
                        String author = cursor.getString(cursor.getColumnIndex("author"));
                        Toast.makeText(this,author+":"+count,Toast.LENGTH_SHORT).show();
                        count++;
                    }while (cursor.moveToNext());
                }
                cursor.close();
                break;
            default:
                break;
        }

    }
}

MyDatabaseHelper.java

public class MyDatabaseHelper extends SQLiteOpenHelper {

    private Context context;
    public static final String CREATE_BOOK = "create table Book (" +
            "id integer primary key autoincrement," +
            "author text," +
            "price real," +
            "pages integer," +
            "book_name text)";

    public static final String CREATE_CATEGORY = "create table Category (" +
            "id integer primary key autoincrement, " +
            "category_name text, " +
            "category_code integer)" ;

    public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(CREATE_BOOK);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL(CREATE_CATEGORY);
    }
}

MyContentProvider.java

public class MyContentProvider extends ContentProvider {

    public static final int BOOK_DIR = 0;
    public static final int BOOK_ITEM = 1;
    public static final int CATEGORY_DIR = 2;
    public static final int CATEGORY_ITEM = 3;

    public static final String AUTHORITY = "com.sky.databasetest.provider";
    private static UriMatcher uriMatcher;
    private MyDatabaseHelper dbHelper;

    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(AUTHORITY, "Book", BOOK_DIR);
        uriMatcher.addURI(AUTHORITY, "Book/#", BOOK_ITEM);
        uriMatcher.addURI(AUTHORITY, "Category", CATEGORY_DIR);
        uriMatcher.addURI(AUTHORITY, "Category/#", CATEGORY_ITEM);

    }
    public MyContentProvider() {
    }

    @Override
    public boolean onCreate() {
        dbHelper = new MyDatabaseHelper(getContext(), "BookStore.db", null, 2);
        return true;
    }

    @Override
    public String getType(Uri uri) {
        String type = null;
        switch (uriMatcher.match(uri)){
            case BOOK_DIR:
                type = "vnd.android.cursor.dir/vnd.com.sky.databasetest.provider.Book";
                break;
            case BOOK_ITEM:
                type = "vnd.android.cursor.item/vnd.com.sky.databasetest.provider.Book";
                break;
            case CATEGORY_DIR:
                type = "vnd.android.cursor.dir/vnd.com.sky.databasetest.provider.Category";
                break;
            case CATEGORY_ITEM:
                type = "vnd.android.cursor.item/vnd.com.sky.databasetest.provider.Category";
                break;
            default:
                break;
        }
        return type;
    }

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

        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Uri uriRet=null;
        switch (uriMatcher.match(uri)){
            case BOOK_DIR:
            case BOOK_ITEM:
                long newBookId = db.insert("Book", null, values);
                uriRet = Uri.parse("content://" + AUTHORITY + "/Book/"+newBookId);
                break;
            case CATEGORY_DIR:
            case CATEGORY_ITEM:
                long newCategoryId = db.insert("Category", null, values);
                uriRet = Uri.parse("content://" + AUTHORITY + "/Category/"+newCategoryId);
                break;
            default:break;
        }
        return uriRet;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {

        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = null;
        switch (uriMatcher.match(uri)){
            case BOOK_DIR:
                cursor = db.query("Book", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case BOOK_ITEM:
                String bookId = uri.getPathSegments().get(1);
                cursor = db.query("Book", projection, "id=?", new String[]{bookId}, null, null, sortOrder);
                break;
            case CATEGORY_DIR:
                cursor = db.query("Category", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case CATEGORY_ITEM:
                String categoryId = uri.getPathSegments().get(1);
                cursor = db.query("Category", projection, "id=?", new String[]{categoryId}, null, null, sortOrder);
                break;
            default:break;
        }
        return cursor;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {

        SQLiteDatabase db = dbHelper.getReadableDatabase();
        int updateRows = 0;
        switch (uriMatcher.match(uri)){
            case BOOK_DIR:
                updateRows = db.update("Book", values, selection, selectionArgs);
                break;
            case BOOK_ITEM:
                String bookId = uri.getPathSegments().get(1);
                updateRows = db.update("Book", values, "id=?", new String[]{bookId});
                break;
            case CATEGORY_DIR:
                updateRows = db.update("Category", values, selection, selectionArgs);
                break;
            case CATEGORY_ITEM:
                String categoryId = uri.getPathSegments().get(1);
                updateRows = db.update("Category", values, "id=?", new String[]{categoryId});
                break;
            default:break;
        }
        return updateRows;
    }

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

        SQLiteDatabase db = dbHelper.getReadableDatabase();
        int deleteRows = 0;
        switch (uriMatcher.match(uri)){
            case BOOK_DIR:
                deleteRows = db.delete("Book", selection, selectionArgs);
                break;
            case BOOK_ITEM:
                String bookId = uri.getPathSegments().get(1);
                deleteRows = db.delete("Book", "id=?", new String[]{bookId});
                break;
            case CATEGORY_DIR:
                deleteRows = db.delete("Category", selection, selectionArgs);
                break;
            case CATEGORY_ITEM:
                String categoryId = uri.getPathSegments().get(1);
                deleteRows = db.delete("Category", "id=?", new String[]{categoryId});
                break;
            default:break;
        }
        return deleteRows;
    }

}

AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sky.databasetest">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            intent-filter>
        activity>

        <provider
            android:name=".MyContentProvider"
            android:authorities="com.sky.databasetest.provider"
            android:enabled="true"
            android:exported="true">

        provider>
    application>

manifest>

ProviderTest.apk源码如下:
MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {


    public static final String AUTHORITY = "com.sky.databasetest.provider";
    private String newId;

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

        Button btnAddData = (Button)findViewById(R.id.btnAddData);
        Button btnQueryData = (Button)findViewById(R.id.btnQueryData);
        Button btnUpdateData = (Button)findViewById(R.id.btnUpdateData);
        Button btnDeleteData = (Button)findViewById(R.id.btnDeleteData);

        btnAddData.setOnClickListener(this);
        btnQueryData.setOnClickListener(this);
        btnUpdateData.setOnClickListener(this);
        btnDeleteData.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btnAddData: {
                Uri uri = Uri.parse("content://"+ AUTHORITY + "/Book");
                ContentValues values = new ContentValues();
                values.put("book_name", "adfsaffsf");
                values.put("author", "aha");
                values.put("price", "45.3");
                values.put("pages", "120");
                Uri newUri = getContentResolver().insert(uri, values);
                newId = newUri.getPathSegments().get(1);
            }
                break;
            case R.id.btnQueryData: {
                Uri uri = Uri.parse("content://"+ AUTHORITY+"/Book");
                Cursor cursor = getContentResolver().query(uri, null, null, null, null);
                if(cursor!=null){
                    while (cursor.moveToNext()){
                        String name = cursor.getString(cursor.getColumnIndex("book_name"));
                        String author = cursor.getString(cursor.getColumnIndex("author"));
                        int page = cursor.getInt(cursor.getColumnIndex("pages"));
                        double price = cursor.getDouble(cursor.getColumnIndex("price"));
                        Log.d("MainActivity", "book name is :" + name);
                        Log.d("MainActivity", "book author is :" + author);
                        Log.d("MainActivity", "book page is :" + page);
                        Log.d("MainActivity", "book price is :" + price);
                    }
                    cursor.close();
                }
            }
                break;
            case R.id.btnUpdateData:{
                Uri uri = Uri.parse("content://"+ AUTHORITY + "/Book/" + newId);
                ContentValues values = new ContentValues();
                values.put("price", "22.6");
                getContentResolver().update(uri, values, null, null);
            }
                break;
            case R.id.btnDeleteData:{
                Uri uri = Uri.parse("content://"+ AUTHORITY + "/Book/" + newId);
                getContentResolver().delete(uri, null, null);
            }
                break;
            default:
                break;
        }
    }
}

AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sky.providertest">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            intent-filter>
        activity>
    application>

manifest>

你可能感兴趣的:(第一行代码,Android第二版,笔记)