Passing an array of data to a SQLite database in android

I am using an array to send data to a SQLite database.
The array contains all the selected values.

 private void addContacts(String[] selectedItems) {

    manager.Insert_phone_contact(selectedItems);
    Intent i = new Intent(this, MainActivity.class);    
    startActivity(i);
}

My SQLite database code to insert the aforementioned array of "selectedItems" into the contentvalues ​​looks like this:

public void Insert_phone_contact(String [] contact){
    try{

        SQLiteDatabase DB = this.getWritableDatabase();
        for(int i=0;i<contact.length;i++){
            ContentValues cv = new ContentValues();
            cv.put(CONTACT_NAME, contact[i]);
            DB.insert(TABLE_CONTACTS, null, cv);
            DB.close();
        }
        }
    catch(Exception ex){
        Log.e("Error in phone contact insertion", ex.toString());
    }

Only the first element of the array is stored in ContentValuescv, and not in all elements of the array.
What is wrong with this code? How can I insert all elements of an array into the table "TABLE_CONTACTS"?
Any help would be appreciated.

+4
source share
4 answers

. Db.Close() , , Db .

public void Insert_phone_contact(String [] contact){
try{

    SQLiteDatabase DB = this.getWritableDatabase();
    ContentValues cv = new ContentValues(); //Declare once
    for(int i=0;i<contact.length;i++){            
        cv.put(CONTACT_NAME, contact[i]);
        DB.insert(TABLE_CONTACTS, null, cv); //Insert each time for loop count            
    }
    DB.close(); // Now close the DB Object
    }
catch(Exception ex){
    Log.e("Error in phone contact insertion", ex.toString());
}
+6

insert close , db :

   ContentValues cv = new ContentValues();
    for(int i=0;i<contact.length;i++){
       // put all values in  ContentValues
        cv.put(CONTACT_NAME, contact[i]);
    }
    DB.insert(TABLE_CONTACTS, null, cv); // insert in db
    DB.close();  // call close
+3

You can also view transactions in sqlite

    DB.beginTransaction();
    for(int i=0;i<contact.length;i++){    
        ContentValues cv = new ContentValues();  
        cv.put(CONTACT_NAME, contact[i]);
        DB.insert(TABLE_CONTACTS, "0.0", cv);
    }
    DB.setTransactionSuccessful();

    DB.endTransaction();

This will make the insert operation faster than a single insert.

+1
source

you can use the code. I have only some changes to your code.

public void Insert_phone_contact(String [] contact){
try{

    SQLiteDatabase DB = this.getWritableDatabase();
    for(int i=0;i<contact.length;i++){
        ContentValues cv = new ContentValues();
        cv.put(CONTACT_NAME, contact[i]);
        DB.insert(TABLE_CONTACTS, null, cv);

    }

        cv.close();
        DB.close();
    }
catch(Exception ex){
    Log.e("Error in phone contact insertion", ex.toString());
}
0
source

Source: https://habr.com/ru/post/1524950/


All Articles