AndroidでのUriによるデータベースの変更について

15290 ワード

ネット上のオリジナルの傍受データベースの変化に関する文章は少なく、ほとんど役に立たないので、自分でBluetooth伝送のソースコードを見て、Demoを書いて、ここで参考にして、ソースコードを見てみました.
srcにはMyDataProvider、MainActivity、MyBeanの3つのファイルがあります.次を見てください.
    MyDataProvider.java:
   
public class MyDataProvider extends ContentProvider
{

    // public static final String SCHEME = "test";
    public static final String SCHEME = "content"; //          ,          

    public static final String HOST = "com.zyj";
    public static final String PORT = "497393102";
    public static final String PATH = "simple";

    public static final int ALARMS = 1;
    public static final String SHARE_LIST_TYPE = "com.zyj.test.dir/";
    public static final int ALARMS_ID = 2;
    public static final String SHARE_TYPE = "com.zyj.test.item/";

    private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    private SQLiteOpenHelper mDB = null;

    // ===content://com.zyj:497393102/simple
    public static final Uri CONTENT_URI = Uri.parse(SCHEME + "://" + HOST + ":" + PORT + "/" + PATH);

    //   Uri     ,               ,1          ,2           
    static
    {
        sURIMatcher.addURI(HOST + ":" + PORT, PATH, ALARMS);
        sURIMatcher.addURI(HOST + ":" + PORT, PATH + "/#", ALARMS_ID);
    }

    @Override
    public boolean onCreate()
    {
        mDB = new MyDB(getContext()); //         
        return mDB != null;
    }

    @Override
    public String getType(Uri uri)
    {
        //         Uri   ,         
        int match = sURIMatcher.match(uri);
        switch (match)
        {
            case ALARMS:
            {
                return SHARE_LIST_TYPE;
            }
            case ALARMS_ID:
            {
                return SHARE_TYPE;
            }
            default:
            {
                throw new IllegalArgumentException("Unknown URI: " + uri);
            }
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values)
    {
        //     Uri           ,,                    
        SQLiteDatabase db = mDB.getWritableDatabase();
        if (sURIMatcher.match(uri) != ALARMS)
        {
            throw new IllegalArgumentException("Unknown/Invalid URI " + uri);
        }

        ContentValues filteredValues = new ContentValues();
        filteredValues.put(MyDB.BEAN_ID, values.getAsInteger(MyDB.BEAN_ID));
        filteredValues.put(MyDB.MESSAGE, values.getAsString(MyDB.MESSAGE));
        filteredValues.put(MyDB.TASK_PROGRESS, values.getAsFloat(MyDB.TASK_PROGRESS));
        long rowID = db.insert(MyDB.TABLET, null, filteredValues);
        if (rowID != -1)
        {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return CONTENT_URI;
    }

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

        //     Uri           ,,       

        SQLiteDatabase db = mDB.getWritableDatabase();
        int count = 0;
        int match = sURIMatcher.match(uri);
        switch (match)
        {
            case ALARMS:
            case ALARMS_ID:
                String where = null;
                //    selection      ,                   
                if (selection != null)
                {
                    if (match == ALARMS)
                    {
                        where = "( " + selection + " )";
                    }
                    else
                    {
                        where = "( " + selection + " ) AND ";
                    }
                }
                else
                {
                    where = "";
                }
                if (match == ALARMS_ID)
                {
                    //               ,   Uri     /item ,                     ,  sql    where
                    String segment = uri.getPathSegments().get(1);
                    long rowId = Long.parseLong(segment);
                    where += " ( " + MyDB.BEAN_ID + " = " + rowId + " ) ";
                }
                count = db.delete(MyDB.TABLET, where, selectionArgs);
                break;
            default:
                throw new UnsupportedOperationException("Cannot delete URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
    {
        //      
        SQLiteDatabase db = mDB.getWritableDatabase();

        int count;
        long rowId = 0;

        int match = sURIMatcher.match(uri);
        switch (match)
        {
            case ALARMS:
            case ALARMS_ID:
            {
                String myWhere;
                if (selection != null)
                {
                    if (match == ALARMS)
                    {
                        myWhere = "( " + selection + " )";
                    }
                    else
                    {
                        myWhere = "( " + selection + " ) AND ";
                    }
                }
                else
                {
                    myWhere = "";
                }
                if (match == ALARMS_ID)
                {
                    String segment = uri.getPathSegments().get(1);
                    rowId = Long.parseLong(segment);
                    myWhere += " ( " + MyDB.BEAN_ID + " = " + rowId + " ) ";
                }

                if (values.size() > 0)
                {
                    count = db.update(MyDB.TABLET, values, myWhere, selectionArgs);
                }
                else
                {
                    count = 0;
                }
                break;
            }
            default:
            {
                throw new UnsupportedOperationException("Cannot update URI: " + uri);
            }
        }
        getContext().getContentResolver().notifyChange(uri, null);

        return count;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
    {
        SQLiteDatabase db = mDB.getReadableDatabase();
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); //SQLiteQueryBuilder     SQL        

        int match = sURIMatcher.match(uri);
        switch (match)
        {
            case ALARMS:
            {
                qb.setTables(MyDB.TABLET);
                break;
            }
            case ALARMS_ID:
            {
                qb.setTables(MyDB.TABLET);
                qb.appendWhere(MyDB.BEAN_ID + "=");
                qb.appendWhere(uri.getPathSegments().get(1));
                break;
            }
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        Cursor ret = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);

        if (ret != null)
        {
            ret.setNotificationUri(getContext().getContentResolver(), uri);
            Log.d("zyj", "created cursor " + ret + " on behalf of ");
        }
        else
        {
            Log.d("zyj", "query failed in downloads database");
        }
        return ret;
    }

    private static class MyDB extends SQLiteOpenHelper
    {

        //         ,     、  、   ...
        private static final String DATABASE = "test_database";
        public static final String TABLET = "test_table";
        public static String ID = "_id";
        public static String BEAN_ID = "_bean_id";
        public static String MESSAGE = "_message";
        public static String TASK_PROGRESS = "_progress";

        private SQLiteDatabase mDB = null;

        private final String msql = "CREATE TABLE IF NOT EXISTS " + TABLET + "( " + ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT, " + BEAN_ID + " TEXT, " + MESSAGE + " TEXT, " + TASK_PROGRESS
                + " TEXT )";

        private MyDB(Context context)
        {
            super(context, DATABASE, null, 1);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            mDB = db;
            mDB.execSQL(msql);
        }

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

    MyBean.JAvaインスタンスオブジェクト
   
public class MyBean
{

    public int id = 0;
    
    public String message = null;

    public float progress = 0.0f;

    public MyBean(int id)
    {
        this.id = id;
    }
    
}

     MainActivity.JAvaメインインタフェース
    
public class MainActivity extends Activity
{

    TextView mMessage = null;

    private ContentObserver mDatabaseListener = null;
    private Handler mHand = null;

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

        mMessage = (TextView) findViewById(R.id.message);

        init();

        //         ,       Uri
        getContentResolver().registerContentObserver(MyDataProvider.CONTENT_URI, true, mDatabaseListener);
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        //      
        getContentResolver().unregisterContentObserver(mDatabaseListener);
    }

    private void init()
    {
        mHand = new Handler();
        //          
        mDatabaseListener = new ContentObserver(mHand)
        {
            @Override
            public boolean deliverSelfNotifications()
            {
                System.out.println("deliverSelfNotifications ---------------- ");
                return super.deliverSelfNotifications();
            }

            @Override
            public void onChange(boolean selfChange, Uri uri)
            {
                System.out.println("onChange ---------------- " + uri.toString());
                super.onChange(selfChange, uri);
            }

            @Override
            public void onChange(boolean selfChange)
            {
                System.out.println("onChange ---------------- ...");
                super.onChange(selfChange);
            }
        };
    }

    private int count = 0;

    public void onViewClick(View view)
    {
        switch (view.getId())
        {
            case R.id.add:
                //     
                ContentValues calues = new ContentValues();
                calues.put("_bean_id", count++);
                calues.put("_message", "AAAAAAAAAAAAAAAAAAAAA");
                calues.put("_progress", 0.0f);
                getContentResolver().insert(MyDataProvider.CONTENT_URI, calues);
                break;
            case R.id.del:
                //         _bean_id=1、2、3 ,         ,          
                getContentResolver().delete(Uri.parse(MyDataProvider.CONTENT_URI.toString() + "/1"), null, null);
                getContentResolver().delete(Uri.parse(MyDataProvider.CONTENT_URI.toString() + "/2"), null, null);
                getContentResolver().delete(Uri.parse(MyDataProvider.CONTENT_URI.toString() + "/3"), null, null);
                break;
            case R.id.modify:
                ContentValues values = new ContentValues();
                values.put("_message", "ZZZZZZZZZZZZZZZZZZZZZ");
                //        ,         Uri       /item       
                getContentResolver()
                        .update(Uri.parse(MyDataProvider.CONTENT_URI.toString() + "/5"), values, null, null);
                getContentResolver().update(MyDataProvider.CONTENT_URI, values, "_bean_id=?", new String[] { "6" });
                break;
            case R.id.query:
                showMessage(getContentResolver().query(MyDataProvider.CONTENT_URI, null, null, null, null));
                break;
        }
    }

    private void showMessage(Cursor c)
    {
        if (c == null)
        {
            return;
        }
        final StringBuffer sb = new StringBuffer();
        if (c.getCount() > 0)
        {
            while (c.moveToNext())
            {
                MyBean bean = new MyBean(c.getInt(c.getColumnIndex("_bean_id")));
                bean.message = c.getString(c.getColumnIndex("_message"));
                bean.progress = c.getFloat(c.getColumnIndex("_progress"));
                sb.append(bean.id + "\t\t\t:" + bean.message + "\t\t\t,progress = " + bean.progress + "
"); } } c.close(); mHand.post(new Runnable() { public void run() { mMessage.setText(sb.toString()); } }); } }

    activity_main.xmlの上には4つのボタンがあり、下にはTextView表示コントロールがあります.
最後はAndroidManifestですxmlです.いつもと同じですが、中には自分で定義したContentProviderを書いています.私のように:
android:name="com.example.databasetest.MyDataProvider"android:authorities="com.zyj:49739102"/>上のauthorities属性は必ず書かなければなりません.これは上のMyDataProviderです.JAvaの中のCONTENT_URIのHOST+":"+PORTは、下に描かれているものを見ることができ、明らかになりました.
    content://com.example.project:200/folder/subfolder/etc    \---------/ \---------------------------/\---/\--------------------------/    scheme                 host               port        path                    \--------------------------------/                              authority   
そしてなくなり、自分で実行して、Uriとデータベースの傍受を感じることができます.
间违いがあったら出てきてほしい、ありがとう!!!