1

I'm trying to populate an Android SQLIte database table using String Arrays. I've got arrays that look like this:

idStrArray = "1, 2, 3, 4"
titleStrArray = "Title 1", "Title 2", "Title 3", "Title 4"
descrStrArray = "Descr 1", "Descr 2", "Descr 3", "Descr 4"
locationStrArray = "Location 1", "Location 2", "Location 3", "Location 4"

And I can't figure out how to write a method in the DBAdapter Class that would populate a DB Table using the arrays like this:

ID  TITLE  DESCR  LOCATION
1  title1  descr1 location1
2  title2  descr2 location2
3  title3  descr3 location3
4  title4  descr4 location4  

I tried this in the Adapter Class:

    DBAdapter Class:

public long AddStrArraysToDB(String[] calTitleStrArray, String[] calDescrStrArray, String[]     calLocationStrArray){
    try{

        mDb = mDbHelper.getWritableDatabase();
        cv = new ContentValues();

        //--- title
        for(int i=0;i<calTitleStrArray.length;i++){
            cv.put(KEY_EVENT_TITLE, calTitleStrArray[i]);
            mDb.insert(DB_TABLE, null, cv);
        }
        //--- end title

        //--- descr
        for(int i=0;i<calDescrStrArray.length;i++){
            cv.put(KEY_EVENT_DESCR, calDescrStrArray[i]);
            mDb.insert(DB_TABLE, null, cv);
        }
        //--- end descr

        //--- location
        for(int i=0;i<calLocationStrArray.length;i++){
            cv.put(KEY_EVENT_LOCATION, calLocationStrArray[i]);
            mDb.insert(DB_TABLE, null, cv);
        }
        //--- end location

        mDb.close();



    }catch(Exception ex){
        Log.e("Error in phone contact insertion", ex.toString());
    }//--- END Try
    return mDb.insert(DB_TABLE, null, cv);

}

and then tried calling this method in the MainActivity like this:

    Main Activity:

Cal27Adapter addData = new Cal27Adapter(Cal27Main.this);
            addData.open();
            addData.AddStrArraysToDB    (calTitleStrArray,calDescrStrArray,calLocationStrArray);
            addData.close();

Doing this throws an exception. Any ideas how I can write a method in the Adapter class that would add the String Arrays as columns to my DB table?

1 Answer 1

3

You should use a single loop, and fill all fields for each record, i.e.

    for(int i=0; i < calTitleStrArray.length ; i++){
        cv = new ContentValues();
        cv.put(KEY_EVENT_TITLE, calTitleStrArray[i]);
        cv.put(KEY_EVENT_DESCR, calDescrStrArray[i]);
        cv.put(KEY_EVENT_LOCATION, calLocationStrArray[i]);
        mDb.insert(DB_TABLE, null, cv);
    }

This assumes that all the arrays have the same length (which is reasonable for this case).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.