Saving ArrayLists in SQLite databases

So I want to save an ordered set of double values, and I want to be able to insert, retrieve or delete any value from this easily. As of such, I'm using a an ArrayList, where I define a class called Doubles to store the double values.

How do I store this arraylist in a record in an SQLite database? I mean...what should the columns type be? Can it be done?

Answers


You cannot insert ArrayList directly into Sqlite. Instead, you could use JSONObject (org.json.JSONObject) to insert the ArrayList. Please check below snippet, you can try something like below....

To insert,

JSONObject json = new JSONObject();
json.put("uniqueArrays", new JSONArray(items));
String arrayList = json.toString();

Insert the string into db.

To Read, Read the string from db as String,

 JSONObject json = new JSONObject(stringreadfromsqlite);
  ArrayList items = json.optJSONArray("uniqueArrays");

To Insert :

ArrayList<String> inputArray=new ArrayList<String>();

//....Add Values to inputArray

Gson gson = new Gson();

String inputString= gson.toJson(inputArray);

System.out.println("inputString= " + inputString);


use "inputString" to save the value of ArrayList<String> in SQLite Database 

To retreive:

Get the String from the SQLiteDatabse what you saved and changed into ArrayList type like below:

outputarray is a String which is get from SQLiteDatabase for this example.

Type type = new TypeToken<ArrayList<String>>() {}.getType();

ArrayList<String>  finalOutputString = gson.fromJson(outputarray, type);

In my case it was ArrayList of POJO classes Note

private String mNoteTitle;
private int mFingerIndex;
private Point mNoteCoordinates;

public Note(String noteTitle, int fingerIndex, Point noteCoordinates) {
    this.mNoteTitle = noteTitle;
    this.mFingerIndex = fingerIndex;
    this.mNoteCoordinates = noteCoordinates;
}

As manual says JSONObject supports only following types: Object: a JSONObject, JSONArray, String, Boolean, Integer, Long, Double, NULL, or null. May not be NaNs or infinities. So, I should break my Note class into supported objects.

 JSONObject json = new JSONObject();
    JSONArray jsonArray = new JSONArray();

    for(Note note: chordShape.getNotes()){
        JSONObject singleNoteJsonObject = new JSONObject();

        try {
            singleNoteJsonObject.put(SHAPE_NOTE_TITLE, note.getNoteTitle());
            singleNoteJsonObject.put(SHAPE_NOTE_FINGER_INDEX, note.getFingerIndex());
            singleNoteJsonObject.put(SHAPE_NOTE_X, note.getNoteCoordinates().x);
            singleNoteJsonObject.put(SHAPE_NOTE_Y, note.getNoteCoordinates().y);
        } catch (JSONException e){
            e.printStackTrace();
        }

        jsonArray.put(singleNoteJsonObject);

    }

Pack created array into JSONObject.

try {
        json.put(SHAPE_NOTES, jsonArray);
        Log.i(TAG, json.toString());
    } catch (JSONException e){
        e.printStackTrace();
    }

Create String.

String notesList = json.toString();

Put created String in ContentValues, cause in my case it's Android app

if(notesList.length() > 0){
        contentValues.put(DatabaseHelper.SHAPE_NOTES_LIST, notesList);
    }

And when i should read values from SQLite database.

ArrayList<Note> notes = new ArrayList<>();
    while(cursor.moveToNext()){
        JSONObject jsonNotes = null;
        try {
           jsonNotes = new JSONObject(cursor.getString(cursor.getColumnIndex(DatabaseHelper.SHAPE_NOTES_LIST)));
        } catch (JSONException e){
            e.printStackTrace();
        }

        if(jsonNotes != null){
            Log.i(TAG, jsonNotes.toString());
            JSONArray jsonArray = jsonNotes.optJSONArray(SHAPE_NOTES);
            for(int i = 0; i < jsonArray.length(); i++){
                Note note = null;
                JSONObject arrayObject = null;

                try {
                    arrayObject = jsonArray.getJSONObject(i);
                } catch (JSONException e){
                    e.printStackTrace();
                }

                if(arrayObject != null){
                    try {
                        note = new Note(
                            arrayObject.getString(SHAPE_NOTE_TITLE),
                                arrayObject.getInt(SHAPE_NOTE_FINGER_INDEX),
                                new Point(
                                        arrayObject.getInt(SHAPE_NOTE_X),
                                        arrayObject.getInt(SHAPE_NOTE_Y)
                                )
                        );
                    } catch (JSONException e){
                        e.printStackTrace();
                    }
                }


                if(note != null){
                    notes.add(note);
                }
            }
        }
    }
    cursor.close();

I suggest going through all 3 Notepad tutorials you want to store the values your storing to a database table. you don't store the actual array directly into the database just the data. but you shouldn't actually need to use an array at all instead of adding a new item to the array instead call your db insert method


I've needed to do something similar in my application, where I have a custom class (Foo, Bar, etc.) and I have an ArrayList of foo, bar, etc. that I persist to SQL. My knowledge of SQL isn't strong, but I'll explain my approach here in case it helps. My understanding is that to store any kind of object, you need to define a particular table for that object type, where the table has separate columns representing the primitive types within that object. Furthermore, to persist and retrieve an ArrayList of those objects, you'll use one table row per ArrayList entry, and iterate over in a loop to store and retrieve.

There are ArrayLists of several custom classes in my application that I wanted to persist to DB. So, to make things tidy (well, to me at least -- I'm still a relatively new Java / Android programmer, so take this with a pinch of salt) I decided to implement a kind of "SQL Serializable Interface" that my DB-persistable objects must implement. Each object (Foo, Bar, etc.) that can be persisted to DB must implement:

  1. A public static final TABLE_NAME string, the name of the SQL DB table used for this object type.
  2. A public static final TABLE_CREATE_STRING, a complete SQL instruction to create the table for this object.
  3. A constructor method to populate its member variables from a ContentValues object.
  4. A 'get' method to populate a ContentValues from its member variables.

So, say I have ArrayLists of objects Foo and Bar. When the DB is first created, within my DB helper class I call Foo.TABLE_CREATE_STRING, Bar.TABLE_CREATE_STRING, etc. to create the tables for those objects.

To populate my ArrayList, I use something like:

cursor = dbh.retrieve(Foo.TABLE_NAME);
if(!cursor.moveToFirst()){
  return false
}
do{
  DatabaseUtils.cursorRowToContentValues(cursor, vales);
  FooArrayList.add( new Foo(values) );
} while( cursor.moveToNext() );

Create a dbHelper class which has an inner class and pretty much whatever the notepad tutorial says. The class must be having an insertion method somthing like this :-

public long insertRows(ContentValues values, String tableName) {
    long val = myDatabase.insert(tableName, null, values);
    return val;
}

This method will then add values into the table row. After that you can call this method from your main activity and since you are using cursor i believe you will call the method in a for loop

for(i=0;list.length();i++) or may be its list.size :P

{

// Call the method here

}

and keep adding value in the database by calling the method in for loop


Need Your Help

Add 'Watermark' to images with php

php image watermark

I have a website where users may upload images...

Visual Studio keyboard generates wrong characters

visual-studio visual-studio-2008 keyboard key-bindings

Every now and then my keyboard in Visual Studio starts to behave wrongly. For example Shift + 3 inserts a pound symbol instead of a hash #. Shift + \ inserts a tilde ~ instead of a pipe |. When ...