在SQLite数据库中保存ArrayLists

时间:2011-04-18 13:04:15

标签: android database sqlite

所以我想保存一组有序的double值,我希望能够轻松地插入,检索或删除任何值。就这样,我使用的是一个ArrayList,我在其中定义了一个名为Doubles的类来存储double值。

如何将此arraylist存储在SQLite数据库的记录中?我的意思是......列类型应该是什么?可以吗?

6 个答案:

答案 0 :(得分:52)

您不能将ArrayList直接插入Sqlite。相反,您可以使用JSONObject(org.json.JSONObject)来插入ArrayList。请查看下面的代码片段,您可以尝试以下内容....

要插入,

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

将字符串插入db。

阅读,          从db中读取字符串作为String,

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

答案 1 :(得分:13)

要插入:

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

// ....将值添加到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 

要撤退:

从SQLiteDatabse获取您保存的字符串并将其更改为ArrayList类型,如下所示:

outputarray是一个String,它是从这个例子的SQLiteDatabase中获取的。

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

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

答案 2 :(得分:1)

在我的例子中,它是POJO类的ArrayList注意

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;
}

正如手册所说,JSONObject仅支持以下类型:对象:JSONObject,JSONArray,String,Boolean,Integer,Long,Double,NULL或null。可能不是NaN或无穷大。所以,我应该将我的Note类分解为支持的对象。

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

    }

将创建的数组打包到JSONObject中。

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

创建字符串。

String notesList = json.toString();

在ContentValues中添加创建的字符串,在我的情况下是它的Android应用程序

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

当我应该从SQLite数据库中读取值时。

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

答案 3 :(得分:0)

我建议您浏览所有3 Notepad tutorials,以便将存储的值存储到数据库表中。您不会将实际数组直接存储到数据库中。但实际上你根本不需要使用数组而不是向数组中添加新项而是调用db insert方法

答案 4 :(得分:0)

我需要在我的应用程序中做类似的事情,我有一个自定义类(Foo,Bar等),我有一个foo,bar等的ArrayList,我坚持使用SQL。我对SQL的了解并不强,但我会在这里解释我的方法以防万一。我的理解是,要存储任何类型的对象,您需要为该对象类型定义一个特定的表,其中该表具有表示该对象中的基元类型的单独列。此外,要持久化并检索这些对象的ArrayList,您将为每个ArrayList条目使用一个表行,并在循环中迭代以存储和检索。

我的应用程序中有几个自定义类的ArrayLists,我想继续保存到DB。所以,为了使事情变得整洁(好吧,至少对我来说 - 我仍然是一个相对较新的Java / Android程序员,所以带着一点点盐)我决定实现一种“SQL Serializable Interface”,我的DB-persistable对象必须实现。可以持久保存到DB的每个对象(Foo,Bar等)都必须实现:

  1. 公共静态最终TABLE_NAME字符串,用于此对象类型的SQL DB表的名称。
  2. 公共静态最终TABLE_CREATE_STRING,一个完整的SQL指令,用于为此对象创建表。
  3. 从ContentValues对象填充其成员变量的构造函数方法。
  4. 从其成员变量填充ContentValues的'get'方法。
  5. 所以,说我有对象Foo和Bar的ArrayLists。首次创建数据库时,在我的数据库帮助程序类中,我调用Foo.TABLE_CREATE_STRING,Bar.TABLE_CREATE_STRING等来为这些对象创建表。

    要填充我的ArrayList,我使用类似:

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

答案 5 :(得分:-1)

创建一个dbHelper类,它有一个内部类,几乎与记事本教程所说的无关。该类必须具有这样的插入方法: -

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

然后,此方法将值添加到表行中。 之后,您可以从主活动中调用此方法,因为您正在使用游标,我相信您将在for循环中调用该方法

for(i = 0; list.length(); i ++)或者可能是它的list.size:P

{

//在此处调用方法

}

并通过调用for循环

中的方法继续在数据库中添加值