Androidの4つのコンポーネント-ContentProviderの追加削除と最適化

13071 ワード

ContentProviderの追加削除と最適化
事前説明:
ContentProviderステップ:データベースを作成し、ルールマッチングを書き込み、manifestsを構成し、別のアプリケーションで使用
実はContentProviderは:1つのマッチング器の中で自分の書いたマッチングルールを書き込んで、そして対外的に書いたマッチングルールを提供して使用して、残りは削除して調べる処理です
詳細:
インクリメンタル・チェックのクエリにはcursor.getBooleanというメソッドはありませんので、データベースでブール値を取得するには、次の手順に従います.
msg.setFlag(cursor.getInt(cursor.getColumnIndex("flag")) != 0);

ContentProviderの追加削除
ステップ1:クラス継承SQLiteOpenHelperを作成し、SQL文でSQLiteを作成する
    public class CommonOpenHelper extends SQLiteOpenHelper {

    private static CommonOpenHelper helper;

    public static CommonOpenHelper getInstance(Context context) {
        if (helper == null) {
            helper = new CommonOpenHelper(context, "common.db", null, 1);
        }
        return helper;
    }

    private CommonOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table message(" +
                "id integer primary key autoincrement, " +
                "content varchar, " +
                "date varchar " +
                ")");
    }

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

    }
}

ステップ2:クラス継承ContentProviderを作成し、削除・変更の方法を提供する
    public class MyMessageProvider extends ContentProvider {

    //    
    public final static String DB_MESSAGE = "message";

    //       
    CommonOpenHelper helper;
    SQLiteDatabase db;

    //     
    UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);

    //       
    final static int CODE_MESSAGE_INSERT = 0;
    final static int CODE_MESSAGE_QUERY = 1;
    final static int CODE_MESSAGE_DELETE = 2;
    final static int CODE_MESSAGE_UPDATE = 3;

    //   
    final static String authority = "com.handsome.nfcc";
    final static Uri BASE_URI = Uri.parse("content://com.handsome.nfcc");
    
    //           
    {
        matcher.addURI(authority, "message/insert", CODE_MESSAGE_INSERT);
        matcher.addURI(authority, "message/query", CODE_MESSAGE_QUERY);
        matcher.addURI(authority, "message/delete", CODE_MESSAGE_DELETE);
        matcher.addURI(authority, "message/update", CODE_MESSAGE_UPDATE);
    }

    //     URI
    public interface URI {
        Uri CODE_MESSAGE_INSERT = Uri.parse("content://" + authority + "/message/insert");
        Uri CODE_MESSAGE_QUERY = Uri.parse("content://" + authority + "/message/query");
        Uri CODE_MESSAGE_DELETE = Uri.parse("content://" + authority + "/message/delete");
        Uri CODE_MESSAGE_UPDATE = Uri.parse("content://" + authority + "/message/update");
    }

    @Override
    public boolean onCreate() {
        helper = CommonOpenHelper.getInstance(getContext());
        db = helper.getWritableDatabase();
        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        switch (matcher.match(uri)) {
            case CODE_MESSAGE_QUERY:
                Cursor cursor = db.query(DB_MESSAGE, projection, selection, selectionArgs, null, null, sortOrder);
                //       ,      
                cursor.setNotificationUri(getContext().getContentResolver(), BASE_URI);
                return cursor;
            default:
                throw new IllegalArgumentException("    uri" + uri);
        }
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        switch (matcher.match(uri)) {
            case CODE_MESSAGE_INSERT:
                long rowId = db.insert(DB_MESSAGE, null, values);
                if (rowId == -1) {
                    //    
                    return null;
                } else {
                    //      
                    getContext().getContentResolver().notifyChange(BASE_URI, null);
                    //    
                    return ContentUris.withAppendedId(uri, rowId);
                }
            default:
                throw new IllegalArgumentException("    uri" + uri);
        }
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        switch (matcher.match(uri)) {
            case CODE_MESSAGE_DELETE:
                int number = db.delete(DB_MESSAGE, selection, selectionArgs);
                //      
                getContext().getContentResolver().notifyChange(BASE_URI, null);
                return number;
            default:
                throw new IllegalArgumentException("    uri" + uri);
        }
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        switch (matcher.match(uri)) {
            case CODE_MESSAGE_UPDATE:
                int number = db.update(DB_MESSAGE, values, selection, selectionArgs);
                //      
                getContext().getContentResolver().notifyChange(BASE_URI, null);
                return number;
            default:
                throw new IllegalArgumentException("    uri" + uri);
        }
    }
}

手順3:manifestsファイルで書いたContentProviderを構成する
    

ステップ4:別のアプリケーションにデータベースの追加削除検索クラスを書き、ContentProviderを使用する
    public class MessageDao {

    /**
     *     
     */
    public static boolean insert(ContentResolver resolver, Message msg) {
        ContentValues values = new ContentValues();
        values.put("content", msg.getContent());
        values.put("date", DateUtils.showDate());
        resolver.insert(MyMessageProvider.URI.CODE_MESSAGE_INSERT, values);
        return true;
    }


    /**
     *     
     */
    public static void delete(ContentResolver resolver, int id) {
        resolver.delete(MyMessageProvider.URI.CODE_MESSAGE_DELETE, "id = " + id, null);
    }

    /**
     *       
     */
    public static void deleteAll(ContentResolver resolver) {
        resolver.delete(MyMessageProvider.URI.CODE_MESSAGE_DELETE, null, null);
    }

    /**
     *     
     *
     * @param resolver
     * @return
     */
    public static List query(ContentResolver resolver) {
        List list = new ArrayList<>();
        Cursor cursor = resolver.query(MyMessageProvider.URI.CODE_MESSAGE_QUERY, null, null, null, null);
        while (cursor.moveToNext()) {
            Message msg = new Message();
            msg.setDate(cursor.getString(cursor.getColumnIndex("date")));
            msg.setContent(cursor.getString(cursor.getColumnIndex("content")));
            msg.setId(cursor.getInt(cursor.getColumnIndex("id")));
            list.add(0, msg);
        }
        return list;
    }


}

ContentProviderの最適化
多くの場合、1つのプロジェクトに多くのデータベースがあります.この場合、ContentProviderコードを繰り返し書くのではなく、すべてのデータベースを1つのContentProviderに配置し、テーブル名をクエリーする方法を提供し、対応するテーブルを操作します.
手順1:ContentProviderのコード最適化(一連のコードは複数のデータベースに適用)
public class MyDataProvider extends ContentProvider {

    //    
    public final static String DB_DATA = "data";
    public final static String DB_FETCH = "fetch";
    public final static String DB_MESSAGE = "message";

    //       
    CommonOpenHelper helper;
    SQLiteDatabase db;

    UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);

    //       
    final static int CODE_DATA = 0;
    final static int CODE_FETCH = 1;
    final static int CODE_MESSAGE = 2;

    //   
    final static String authority = "com.handsome.nfc";
    final static Uri BASE_URI = Uri.parse("content://com.handsome.nfc");


    //           
    {
        matcher.addURI(authority, "data", CODE_DATA);
        matcher.addURI(authority, "fetch", CODE_FETCH);
        matcher.addURI(authority, "message", CODE_MESSAGE);
    }

    //     URI
    public interface URI {
        Uri DATA_CONTENT_URI = Uri.parse(BASE_URI + "/data");
        Uri FETCH_CONTENT_URI = Uri.parse(BASE_URI + "/fetch");
        Uri MESSAGE_CONTENT_URI = Uri.parse(BASE_URI + "/message");
    }

    /**
     *        
     *
     * @param uri
     * @return
     */
    private String getTableName(Uri uri) {
        String tableName = null;
        switch (matcher.match(uri)) {
            case CODE_DATA:
                tableName = DB_DATA;
                break;
            case CODE_FETCH:
                tableName = DB_FETCH;
                break;
            case CODE_MESSAGE:
                tableName = DB_MESSAGE;
                break;
            default:
                break;
        }
        return tableName;
    }

    @Override
    public boolean onCreate() {
        helper = CommonOpenHelper.getInstance(getContext());
        db = helper.getWritableDatabase();
        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        String tableName = getTableName(uri);
        if (tableName == null) {
            throw new IllegalArgumentException("  Uri:" + uri);
        }
        Cursor cursor = db.query(tableName, projection, selection, selectionArgs, null, null, sortOrder);
        //       ,      
        cursor.setNotificationUri(getContext().getContentResolver(), BASE_URI);
        return cursor;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        String tableName = getTableName(uri);
        if (tableName == null) {
            throw new IllegalArgumentException("  Uri:" + uri);
        }
        long rowId = db.insert(tableName, null, values);
        if (rowId == -1) {
            return null;
        } else {
            //      
            getContext().getContentResolver().notifyChange(BASE_URI, null);
            return ContentUris.withAppendedId(uri, rowId);
        }
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        String tableName = getTableName(uri);
        if (tableName == null) {
            throw new IllegalArgumentException("  Uri:" + uri);
        }
        int number = db.delete(tableName, selection, selectionArgs);
        //      
        getContext().getContentResolver().notifyChange(BASE_URI, null);
        return number;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        String tableName = getTableName(uri);
        if (tableName == null) {
            throw new IllegalArgumentException("  Uri:" + uri);
        }
        int number = db.update(tableName, values, selection, selectionArgs);
        //      
        getContext().getContentResolver().notifyChange(BASE_URI, null);
        return number;
    }
}

ステップ2:各異なるデータベースでの使用
Dataデータベースの名前照会の例
private static boolean queryDataByName(ContentResolver resolver, String tag_id) {
        Cursor cursor = resolver.query(MyDataProvider.URI.DATA_CONTENT_URI, null, "tag_id = '" + tag_id + "'", null, null);
        if (cursor.moveToFirst()) {
            return true;
        }
        return false;
    }

Fetchデータベース挿入例
public static boolean insert(ContentResolver resolver, Fetch fetch) {
        ContentValues values = new ContentValues();
        values.put("fetch_num", fetch.getFetch_num());
        values.put("username", fetch.getUsername());
        values.put("installationId", fetch.getInstallationId());
        values.put("created", fetch.getCreated());
        values.put("date", System.currentTimeMillis());
        resolver.insert(MyDataProvider.URI.FETCH_CONTENT_URI, values);
        return true;
    }

Messageデータベースクエリーの例
 public static List query(ContentResolver resolver) {
        List list = new ArrayList<>();
        Cursor cursor = resolver.query(MyDataProvider.URI.MESSAGE_CONTENT_URI, null, null, null, null);
        while (cursor.moveToNext()) {
            Message msg = new Message();
            msg.setDate(cursor.getString(cursor.getColumnIndex("date")));
            msg.setContent(cursor.getString(cursor.getColumnIndex("content")));
            msg.setId(cursor.getInt(cursor.getColumnIndex("id")));
            list.add(0, msg);
        }
        return list;
    }