如何指定要插入的内容提供程序中的哪个表

时间:2014-09-04 08:25:15

标签: android android-contentprovider

我在下面有内容提供商。这是我的数据库的接口,它有几个表,消息,电话,交易等。

我可以使用查询方法和游标加载器检索数据。我在列表视图中显示数据时这样做。

据我所知,如果我想插入数据,我必须使用contentResolver。如下所示。

getContentResolver().insert(URI, values);

我如何插入消息表中?例如?

我可以看到内容提供程序中有一个uriMatching机制,但是在使用内容提供程序执行插入时如何指定特定的表。我如何在contentResolver中指定它?

我是否必须像在查询方法中那样执行切换?

提前致谢

public class RR3ContentProvider extends ContentProvider {

   private static final String TAG = RR3ContentProvider.class.getSimpleName();
   NfcScannerApplication nfcAppObj; 

   static final String PROVIDER_NAME = "com.carefreegroup.rr3.ContentProvider";
   static final String URLPHONENUMBERS = "content://" + PROVIDER_NAME + "/phonenumbers";
   static final Uri CONTENT_URI_PHONE_NUMBERS = Uri.parse(URLPHONENUMBERS);


   static final String _ID_PHONENUMBERS = "_id";
   static final String PHONE_NAME = "phonename";
   static final String PHONE_NUMBER = "phonenumber";

   static final String TABLEPHONE = "phone";

   private static HashMap<String, String> PHONE_PROJECTION_MAP;

   static final int PHONES = 1;
   static final int PHONE_ID = 2;


   static final String URLMESSAGES = "content://" + PROVIDER_NAME + "/messages";
   static final Uri CONTENT_URI_MESSAGES = Uri.parse(URLMESSAGES);


   static final String _ID_MESSAGES = "_id";
   static final String MESSAGE_CREATED_AT = "messagecreatedat";
   static final String MESSAGE_TEXT = "messagetext";
   static final String MESSAGE_SENDER = "messagesender";

   static final String TABLEMESSAGE = "message";

   private static HashMap<String, String> MESSAGE_PROJECTION_MAP;

   static final int MESSAGES = 3;
   static final int MESSAGE_ID = 4;











   public static final String C_ID = BaseColumns._ID; // special for id
    // internally in system


   static final String URLTRANSACTIONS = "content://" + PROVIDER_NAME + "/transactions";
   static final Uri CONTENT_URI_TRANSACTIONS = Uri.parse(URLTRANSACTIONS);


   static final String _ID_TRANSACTIONS = "_id";

   static final String TRANSACTIONS_TYPE = "type";
   static final String TRANSACTIONS_COMPANY_ID = "companyid";
   static final String TRANSACTIONS_PERSON_ID = "person";
   static final String TRANSACTIONS_NAME = "name";
   static final String TRANSACTIONS_TAG_ID = "tagid";
   static final String TRANSACTIONS_STATUS = "status";
   static final String TRANSACTIONS_TAG_SCAN_TIME = "tagscantime";
   static final String TRANSACTIONS_TAG_SENTSERVER_TIME = "tagsentservertime";
   static final String TRANSACTIONS_TRANSACTIONS_LATITUDE = "transactionslatitude";
   static final String TRANSACTIONS_TRANSACTIONS_LONGITUDE = "transactionslongitude";
   static final String TRANSACTIONS_DRIVER = "driver";


   static final String TABLETRANSACTIONS = "transactions";

   private static HashMap<String, String> TRANSACTIONS_PROJECTION_MAP;

   static final int TRANSACTIONS = 5;
   static final int TRANSACTION_ID = 6;






   static final String URLLOG = "content://" + PROVIDER_NAME + "/log";
   static final Uri CONTENT_URI_LOG = Uri.parse(URLLOG);


   static final String _ID_Log = "_id";


   static final String LOG_CALLID = "logcallid";
   static final String LOG_MESSAGE = "logmessage";
   static final String LOG_CREATED_TIME = "logcreatedtime";
   static final String LOG_CLIENTID = "logclientid";
   static final String LOG_CARERID = "logcarerid";
   static final String LOG_SERVER_TIME = "logservertime";




   static final String TABLELOG = "log";

   private static HashMap<String, String> LOG_PROJECTION_MAP;

   static final int LOG = 7;
   static final int LOG_ID = 8;


   static final UriMatcher uriMatcher;
   static{
      uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
      uriMatcher.addURI(PROVIDER_NAME, "phonenumbers", PHONES);
      uriMatcher.addURI(PROVIDER_NAME, "phonenumbers/#", PHONE_ID);
      uriMatcher.addURI(PROVIDER_NAME, "messages", MESSAGES);
      uriMatcher.addURI(PROVIDER_NAME, "messages/#", MESSAGE_ID);
      uriMatcher.addURI(PROVIDER_NAME, "transactions", TRANSACTIONS);
      uriMatcher.addURI(PROVIDER_NAME, "transactions/#", TRANSACTION_ID);
      uriMatcher.addURI(PROVIDER_NAME, "log", LOG);
      uriMatcher.addURI(PROVIDER_NAME, "log/#", LOG_ID);
   }

   /**
    * Database specific constant declarations
    */
   private SQLiteDatabase db;


   @Override
   public boolean onCreate() {
      Context context = getContext();
      nfcAppObj = (NfcScannerApplication) getContext();

      Log.e(TAG, "inside RR3ContentProvider onCreate");
      return (nfcAppObj == null)? false:true;
   }

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

       db = nfcAppObj.getDb();

      long rowID = db.insert(   TABLEPHONE, "", values);
      /** 
       * If record is added successfully
       */
      if (rowID > 0)
      {
         Uri _uri = ContentUris.withAppendedId(CONTENT_URI_PHONE_NUMBERS, rowID);
         getContext().getContentResolver().notifyChange(_uri, null);
         return _uri;
      }
      throw new SQLException("Failed to add a record into " + uri);
   }

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

       Log.e(TAG, "inside RR3ContentProvider query method");

       db = nfcAppObj.getDb();

      SQLiteQueryBuilder qb = new SQLiteQueryBuilder();


      switch (uriMatcher.match(uri)) {
      case PHONES:
          Log.e(TAG, "CASE PHONES");
          qb.setTables(TABLEPHONE);
          qb.setProjectionMap(PHONE_PROJECTION_MAP);

          if (sortOrder == null || sortOrder == ""){

             sortOrder = PHONE_NAME;
          }

         break;

      case PHONE_ID:
          Log.e(TAG, "CASE PHONE_ID");
          qb.setTables(TABLEPHONE);
          qb.appendWhere( _ID_PHONENUMBERS + "=" + uri.getPathSegments().get(1));

          if (sortOrder == null || sortOrder == ""){

             sortOrder = PHONE_NAME;
          }

         break;


      case MESSAGES:
          Log.e(TAG, "CASE MESSAGES");
          qb.setTables(TABLEMESSAGE);
          qb.setProjectionMap(MESSAGE_PROJECTION_MAP);

          if (sortOrder == null || sortOrder == ""){

             sortOrder = MESSAGE_CREATED_AT + " DESC";
          }

         break;

      case MESSAGE_ID:
          Log.e(TAG, "CASE MESAAGE_ID");
          qb.setTables(TABLEMESSAGE);
          qb.appendWhere( _ID_MESSAGES + "=" + uri.getPathSegments().get(1));

          if (sortOrder == null || sortOrder == ""){

             sortOrder = MESSAGE_CREATED_AT + " DESC";
          }

         break;


      case TRANSACTIONS:
          Log.e(TAG, "CASE TRANSACTIONS");
          qb.setTables(TABLETRANSACTIONS);
          qb.setProjectionMap(TRANSACTIONS_PROJECTION_MAP);

          if (sortOrder == null || sortOrder == ""){

             sortOrder = TRANSACTIONS_TAG_SCAN_TIME + " DESC";
          }

         break;

      case TRANSACTION_ID:
          Log.e(TAG, "CASE TRANSACTION_ID");
          qb.setTables(TABLETRANSACTIONS);
          qb.appendWhere( _ID_TRANSACTIONS + "=" + uri.getPathSegments().get(1));

          if (sortOrder == null || sortOrder == ""){

             sortOrder = TRANSACTIONS_TAG_SCAN_TIME + " DESC";
          }

         break;

      default:

         throw new IllegalArgumentException("Unknown URI " + uri);
      }



//      switch (uriMatcher.match(uri)) {
//      case PHONES:
//        
//        if (sortOrder == null || sortOrder == ""){
//               
//               sortOrder = PHONE_NAME;
//            }
//        
//         break;
//         
//      case PHONE_ID:
//        
//        if (sortOrder == null || sortOrder == ""){
//               
//               sortOrder = PHONE_NAME;
//            }
//        
//         break;
//         
//         
//      case MESSAGES:
//        
//        if (sortOrder == null || sortOrder == ""){
//               
//               sortOrder = MESSAGE_CREATED_AT + " DESC";
//            }
//        
//         break;
//         
//      case MESSAGE_ID:
//        
//        if (sortOrder == null || sortOrder == ""){
//               
//               sortOrder = MESSAGE_CREATED_AT + " DESC";
//            }
//        
//         break;
//         
//      default:
//        
//         throw new IllegalArgumentException("Unknown URI " + uri);
//      }
//      
      Log.e(TAG, "About to do the query method in content provider");

      Cursor c = qb.query(db,   projection, selection, selectionArgs, 
                          null, null, sortOrder);
      /** 
       * register to watch a content URI for changes
       */
      c.setNotificationUri(getContext().getContentResolver(), uri);

      return c;

   }//end of query





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

       db = nfcAppObj.getDb();

      int count = 0;

      switch (uriMatcher.match(uri)){
      case PHONES:
         count = db.delete(TABLEPHONE, selection, selectionArgs);
         break;
      case PHONE_ID:
         String id = uri.getPathSegments().get(1);
         count = db.delete( TABLEPHONE, _ID_PHONENUMBERS +  " = " + id + 
                (!TextUtils.isEmpty(selection) ? " AND (" + 
                selection + ')' : ""), selectionArgs);
         break;

      case MESSAGES:
          count = db.delete(TABLEMESSAGE, selection, selectionArgs);
          break;
       case MESSAGE_ID:
          String id2 = uri.getPathSegments().get(1);
          count = db.delete( TABLEMESSAGE, _ID_MESSAGES +  " = " + id2 + 
                 (!TextUtils.isEmpty(selection) ? " AND (" + 
                 selection + ')' : ""), selectionArgs);
          break;
      default: 
         throw new IllegalArgumentException("Unknown URI " + uri);
      }

      getContext().getContentResolver().notifyChange(uri, null);
      return count;
   }






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

       db = nfcAppObj.getDb();

      int count = 0;

      switch (uriMatcher.match(uri)){
      case PHONES:
         count = db.update(TABLEPHONE, values, 
                 selection, selectionArgs);
         break;
      case PHONE_ID:
         count = db.update(TABLEPHONE, values, _ID_PHONENUMBERS + 
                 " = " + uri.getPathSegments().get(1) + 
                 (!TextUtils.isEmpty(selection) ? " AND (" +
                 selection + ')' : ""), selectionArgs);
         break;

      case MESSAGES:
          count = db.update(TABLEMESSAGE, values, 
                  selection, selectionArgs);
          break;
       case MESSAGE_ID:
          count = db.update(TABLEMESSAGE, values, _ID_MESSAGES + 
                  " = " + uri.getPathSegments().get(1) + 
                  (!TextUtils.isEmpty(selection) ? " AND (" +
                  selection + ')' : ""), selectionArgs);
          break;
      default: 
         throw new IllegalArgumentException("Unknown URI " + uri );
      }
      getContext().getContentResolver().notifyChange(uri, null);
      return count;
   }//end of delete






   @Override
   public String getType(Uri uri) {
      switch (uriMatcher.match(uri)){
      /**
       * Get all  records 
       */
      case PHONES:
         return "vnd.android.cursor.dir/vnd.example.phonenumbers";
      /** 
       * Get a particular record
       */
      case PHONE_ID:
         return "vnd.android.cursor.item/vnd.example.phonenumbers";

         /**
          * Get all  records 
          */
         case MESSAGES:
            return "vnd.android.cursor.dir/vnd.example.messages";
         /** 
          * Get a particular record
          */
         case MESSAGE_ID:
            return "vnd.android.cursor.item/vnd.example.messages";
      default:
         throw new IllegalArgumentException("Unsupported URI: " + uri);
      }
   }
}

[EDIT1] 我已经让它工作并使用以下代码插入Log表。

如果我想指定要插入的不同表,我是否必须在insert方法中执行switch语句?

ContentValues cv = new ContentValues();
                    cv.putNull(LoginValidate.C_ID_LOG);
                    cv.putNull(LoginValidate.C_LOG_CALLID);
                    cv.put(LoginValidate.C_LOG_MESSAGE, logString);
                    cv.put(LoginValidate.C_LOG_CREATED_TIME, formattedNowTime);
                    cv.put(LoginValidate.C_LOG_CLIENTID, clientID);
                    cv.put(LoginValidate.C_LOG_CARERID, carerID);
                    cv.putNull(LoginValidate.C_LOG_SERVER_TIME);

                    getContentResolver().insert(RR3ContentProvider.CONTENT_URI_LOG, cv);

1 个答案:

答案 0 :(得分:0)

ContentValues cv = new ContentValues();                     cv.putNull(LoginValidate.C_ID_LOG);                     cv.putNull(LoginValidate.C_LOG_CALLID);                     cv.put(LoginValidate.C_LOG_MESSAGE,logString);                     cv.put(LoginValidate.C_LOG_CREATED_TIME,formattedNowTime);                     cv.put(LoginValidate.C_LOG_CLIENTID,clientID);                     cv.put(LoginValidate.C_LOG_CARERID,carerID);                     cv.putNull(LoginValidate.C_LOG_SERVER_TIME);

                getContentResolver().insert(RR3ContentProvider.CONTENT_URI_LOG, cv);