Saving ArrayLists in SQLite databases

前端 未结 6 2259
傲寒
傲寒 2020-11-30 03:42

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, whe

6条回答
  •  臣服心动
    2020-11-30 04:10

    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() );
    

提交回复
热议问题