Best practices for exposing multiple tables using content providers in Android

前端 未结 5 493
迷失自我
迷失自我 2020-12-04 05:19

I\'m building an app where I have a table for events and a table for venues. I want to be able to grant other applications access to this data. I have a few questions relate

5条回答
  •  甜味超标
    2020-12-04 05:47

    Note: This is a clarification/modification to the answer provide by Opy.

    This approach subdivides each of the insert, delete, update, and getType methods with switch statements in order to handle each of your individual tables. You'll use a CASE to identify each table (or uri) to be referenced. Each CASE then maps to one of your tables or URI's. E.g., TABLE1 or URI1 is selected in CASE #1, etc. for all the tables your app employs.

    Here's an example of the approach. This is for the insert method. It's implemented a bit differently from Opy's but performs the same function. You can select the style you prefer. I also wanted to be sure insert returns a value even if the table insertion fails. In that case it returns a -1.

      @Override
      public Uri insert(Uri uri, ContentValues values) {
        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase sqlDB; 
    
        long id = 0;
        switch (uriType){ 
            case TABLE1: 
                sqlDB = Table1Database.getWritableDatabase();
                id = sqlDB.insert(Table1.TABLE_NAME, null, values); 
                getContext().getContentResolver().notifyChange(uri, null);
                return Uri.parse(BASE_PATH1 + "/" + id);
            case TABLE2: 
                sqlDB = Table2Database.getWritableDatabase();
                id = sqlDB.insert(Table2.TABLE_NAME, null, values); 
                getContext().getContentResolver().notifyChange(uri, null);
                return Uri.parse(BASE_PATH2 + "/" + id);
            default: 
                throw new SQLException("Failed to insert row into " + uri); 
                return -1;
        }       
      }  // [END insert]
    

提交回复
热议问题