Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array of data into a SQLite Database in android

I am using an array to send data to my 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 databse code to insert the above mentioned "selectedItems" array in contentvalues is as follows:

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 array item is stored in ContentValues cv, not all the array elements.
What's wrong in this code?
How can I insert all the array items in the "TABLE_CONTACTS" table?
Any help will be appreciated.

like image 528
user3169552 Avatar asked Dec 19 '22 18:12

user3169552


1 Answers

You have to fix few lines of code, First is to delete Db.Close() and add it after loop The code you were trying was closing the Db object after first insertion and unavailable for the rest of loop iterations.

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());
}
like image 187
DareDevil Avatar answered Feb 16 '23 03:02

DareDevil