Android SQLite database: slow insertion

前端 未结 5 1870
南方客
南方客 2020-11-22 07:26

I need to parse a fairly large XML file (varying between about a hundred kilobytes and several hundred kilobytes), which I\'m doing using Xml#parse(String, ContentHand

5条回答
  •  隐瞒了意图╮
    2020-11-22 07:32

    If using a ContentProvider:

    @Override
    public int bulkInsert(Uri uri, ContentValues[] bulkinsertvalues) {
    
        int QueryType = sUriMatcher.match(uri);
        int returnValue=0;
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    
         switch (QueryType) {
    
             case SOME_URI_IM_LOOKING_FOR: //replace this with your real URI
    
                db.beginTransaction();
    
                for (int i = 0; i < bulkinsertvalues.length; i++) {
                    //get an individual result from the array of ContentValues
                    ContentValues values = bulkinsertvalues[i];
                    //insert this record into the local SQLite database using a private function you create, "insertIndividualRecord" (replace with a better function name)
                    insertIndividualRecord(uri, values);    
                }
    
                db.setTransactionSuccessful();
                db.endTransaction();                 
    
                break;  
    
             default:
                 throw new IllegalArgumentException("Unknown URI " + uri);
    
         }    
    
        return returnValue;
    
    }
    

    Then the private function to perform the insert (still inside your content provider):

           private Uri insertIndividualRecord(Uri uri, ContentValues values){
    
                //see content provider documentation if this is confusing
                if (sUriMatcher.match(uri) != THE_CONSTANT_IM_LOOKING_FOR) {
                    throw new IllegalArgumentException("Unknown URI " + uri);
                }
    
                //example validation if you have a field called "name" in your database
                if (values.containsKey(YOUR_CONSTANT_FOR_NAME) == false) {
                    values.put(YOUR_CONSTANT_FOR_NAME, "");
                }
    
                //******add all your other validations
    
                //**********
    
               //time to insert records into your local SQLite database
               SQLiteDatabase db = mOpenHelper.getWritableDatabase();
               long rowId = db.insert(YOUR_TABLE_NAME, null, values);           
    
               if (rowId > 0) {
                   Uri myUri = ContentUris.withAppendedId(MY_INSERT_URI, rowId);
                   getContext().getContentResolver().notifyChange(myUri, null);
    
                   return myUri;
               }
    
    
               throw new SQLException("Failed to insert row into " + uri);
    
    
        }
    

提交回复
热议问题