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?

6
  • At least you can move 'ContentValues cv = new ContentValues();' outside the loops and reuse it. Commented Oct 9, 2014 at 9:32
  • 1
    Use a transaction. stackoverflow.com/questions/8147440/… Commented Oct 9, 2014 at 9:33
  • How will a transaction help me in this huge loop ? Commented Oct 9, 2014 at 9:37
  • developer.android.com/training/articles/perf-tips.html Commented Oct 9, 2014 at 10:12
  • @RahulGupta, may I ask you to mark the answer as correct if it was useful for you and answers your question :) Commented Oct 30, 2014 at 7:37

1 Answer 1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.