0

i am following this link using database

but it uses "ContentValues" to insert data into database

 ContentValues values = new ContentValues();
 values.put(KEY_NAME, contact.getName()); // Contact Name
 values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone`..

but i have 654 number of items to insert..
therefore i need to write these lines 654 times..is there any alternative way to do this...

azizbekian
  • 60,783
  • 13
  • 169
  • 249
Keshri_raj
  • 81
  • 1
  • 8

4 Answers4

2

I'd recommend you to use DatabaseUtils.InsertHelper.

Read this for more info and example.

As the author assures:

After replacing SQLiteDatabase.insert with DatabaseUtils.InsertHelper, the database insertion speed went from the equivalent of about 95 rows per second to about 525 rows per second.

azizbekian
  • 60,783
  • 13
  • 169
  • 249
1

the best thing to optimize the speed of making a lot of operations to the DB is using transactions for batch operations.

also, even if it takes a short time to execute, consider putting the operation in the background, while the user sees a progressBar or something.

example:

db.beginTransaction();
try{
 for(Contact contact : contacts)
   {
   ContentValues values = new ContentValues();
   values.put(KEY_NAME, contact.getName()); 
   values.put(KEY_PH_NO, contact.getPhoneNumber()); 
   db.insert(tablename,values,null,null);
   }
 db.setTransactionSuccessful();// marks a commit
}
finally{
 db.endTransaction();
}
android developer
  • 114,585
  • 152
  • 739
  • 1,270
1

The question is not about how to insert values into database.

It seems you have some data you wish to insert into a database. If the items are in a list of some sort then the answers given here would work. If you have the items in a file then you would need to read the file and parse the items and add them into the database. You should not write the same code 654 times.

user2138983
  • 1,313
  • 9
  • 15
-3

try like this
create 2 Arraylist for name and number. Add all the names and numbers using for loop like this

 arralistname.add(contact.getName());
 arralistnumber.add(contactgetPhoneNumber());


then use for loop to insert

 for(int i=0;i<arralistname.size();i++)
 {
 ContentValues values = new ContentValues();
 values.put(KEY_NAME,arralistname.get(i)); // Contact Name
 values.put(KEY_PH_NO,arralistnumber.get(i)); // C

 db.insert(tablename,values,null,null);

 } 
Senthil
  • 1,244
  • 10
  • 25