-3

i'm a beginner in android ... Can we save arraylist to SQLite database? some suggested to use JSON object to insert the arraylist. If this method can be done, please give an example. Here is my code:

ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("agendaTitle",agendaTitle );
map.put("presenterName", presenterName);                     
mylist.add(map);                      
System.out.println("Map values are: "+ mylist);  
JSONObject json = new JSONObject(map);
json.put(map);
String agendaStrings = json.toString();
System.out.printf( "JSON: %s", json.toString(2) );

here i am pass the agendatitle and presentername values to hashmap, later add it to the arraylist. now i want to save my arraylist to SQLite.

Jaydroid
  • 334
  • 3
  • 13
  • Could you give us some more information? Why do you want it in a database? For persistent storage? – RvdK Mar 20 '14 at 07:17
  • Why not handle it correctly in database approach? Create a table with `ID` and `value`, use `ID` for "variable name" and `value` for "list's values"? – Andrew T. Mar 20 '14 at 07:18
  • You can store your JSON Object to store data into arraylist or you can directly store the data without arraylist also. Its upto you that how do you want to process your data to store into database. Please brief your question more. – GrIsHu Mar 20 '14 at 07:19
  • Nope. You can't save ArrayList in SQLite. see [here](http://www.sqlite.org/datatype3.html) for allowed data types of SQLite – Gopal Gopi Mar 20 '14 at 07:20

2 Answers2

0

You need to iterate through ArrayList and fetch each items. Each item need to be stored in a ContentValue and you can directly pass this contentvalue to db.

  ContentValues cv=new ContentValues();
  public void insertToDb(HashMap<String,String> items)
  {
  for(int i=0;i<items.size();i++)
     {
      cv.put(COLUMN_NAME_FOR_TITLE,items.get("agendaTitle");
      cv.put(COLUMN_NAME_FOR_PRESENTER_NAME,items.get("presenterName");
      db.insert(TABLE_NAME,null,cv);//where db is an instance of SQLiteDatabase
      cv.clear()
     }
   }
Antony
  • 603
  • 6
  • 14
0

You can try out as below:

public void addRecords(HashMap<String, String> queryValues) {
  SQLiteDatabase database = this.getWritableDatabase();
  ContentValues values = new ContentValues();
  values.put("agendaTitle", queryValues.get("agendaTitle"));
  database.insert(TABLE_NAME, null, values);
  database.close();
}
GrIsHu
  • 29,068
  • 10
  • 64
  • 102