0

I have a huge data which i need to insert in sqlite database.

public synchronized void insert(ResponseModel[] response) {

    for (int i = 0; i < response.length; i++) { // Here response length is 100
        for (int j = 0; j < response[i].getPings().size(); j++) { // Here per response, ping size is around 300
            ContentValues cv = new ContentValues();
            if (response[i].getPings().get(j).getId() != null)
                cv.put(Constants.ID, response[i].getPings().get(j).getId().toString().trim());
            // More insertion code goes here
        }
    }
}

Now in this situation, the application takes too much time. The app doesn't hangs because it happens in a background thread. Is there any way to efficiently handle this huge looping?

Ridcully
  • 23,362
  • 7
  • 71
  • 86
Rahul Gupta
  • 5,275
  • 8
  • 35
  • 66

1 Answers1

0

Unfortunately Android SQLite API does not support bulk insertion. Although you can optimize the execution time by using a single transaction. By default Android uses a separate transaction for each insert() call. So in your scenario you will have 30000 transactions. Beginning and committing transactions is a time consuming operation. So you can use a single transaction for all the insertions:

try{
  db.beginTransaction();

  for (int i = 0; i < response.length; i++) { // Here response length is 100
    for (int j = 0; j < response[i].getPings().size(); j++) { // Here per response, ping size is around 300
      ContentValues cv = new ContentValues();
      if (response[i].getPings().get(j).getId() != null) {
        cv.put(Constants.ID, response[i].getPings().get(j).getId().toString().trim());
      }
      // More insertion code goes here
    }
  }

  db.setTransactionSuccessful();
} catch (SQLException e) {
  // Handle the exception...
} finally {
  db.endTranscation();
}
Kiril Aleksandrov
  • 2,601
  • 20
  • 27