簡體   English   中英

在Android中的SQLite數據庫中保存ArrayList

[英]Saving ArrayList in SQLite database in Android

我一直在Android上使用SQLite,我想在表中的列中添加一個arraylist,然后將數據作為arraylist獲取。 arraylist是Longs的列表。 我注意到SQL有一個存儲BLOBS的選項,但是看起來我需要先將arraylist轉換為byte [],然后才能將它作為blob存儲在我的SQLite數據庫中。

如果有人有一個如何將arraylists保存到SQLite數據庫的解決方案,將非常感激。 或者是否有任何其他選項來保存我的數據數組,我應該考慮?

要插入:

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

//添加值為inputArray

Gson gson = new Gson();

String inputString= gson.toJson(inputArray);

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

使用“inputString”在SQLite數據庫中保存ArrayList的值

要撤消:

從SQLiteDatabse中獲取保存的字符串並將其更改為ArrayList類型,如下所示:outputarray是一個String,它是從SQLiteDatabase獲取的示例。

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

ArrayList<String> finalOutputString = gson.fromJson(outputarray, type);
  • 在SQLite中使用text作為格式來存儲字符串Value .....

請原諒我剽竊我之前對BLOB vs. VARCHAR的回答, 以便在MySQL表中存儲數組 那里的其他答案也非常相關。

我認為Con的方法可能比使用java序列化更好,因為java的內置序列化將需要額外的字節,而非Java應用程序將更難處理數據。

public static void storeInDB(ArrayList<Long> longs) throws IOException, SQLException {

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(bout);
    for (long l : longs) {
        dout.writeLong(l);
    }
    dout.close();
    byte[] asBytes = bout.toByteArray();

    PreparedStatement stmt = null;  // however you get this...
    stmt.setBytes(1, asBytes);
    stmt.executeUpdate();
    stmt.close();
}

public static ArrayList<Long> readFromDB() throws IOException, SQLException {

    ArrayList<Long> longs = new ArrayList<Long>();
    ResultSet rs = null;  // however you get this...
    while (rs.next()) {
        byte[] asBytes = rs.getBytes("myLongs");
        ByteArrayInputStream bin = new ByteArrayInputStream(asBytes);
        DataInputStream din = new DataInputStream(bin);
        for (int i = 0; i < asBytes.length/8; i++) {
            longs.add(din.readLong());
        }
        return longs;
    }

}

注意:如果您的列表有時包含超過31個長度(248個字節),那么您將需要使用BLOB。 你不能在MySQL中使用BINARY()或VARBINARY()。 我意識到你在問SQLite,但本着完全抄襲我以前的答案的精神,我會假裝你在問MySQL:

mysql> CREATE TABLE t (a VARBINARY(2400)) ;
ERROR 1074 (42000): Column length too big for column 'a' (max = 255);
use BLOB or TEXT instead

我有兩個ArrayList<String> ,兩個都有1000多個條目。 我看着斑點和字節,但對我來說,解決加快這一進程,並使其可通過改變插入方法和擺脫database.insert -信用為這是在這里

private static final String INSERT = "insert into "
            + YOUR_TABLE_NAME+ " (" + COLUMN_1 + ", "
            + COLUMN_2 + ") values (?, ?)";

public void insertArrayData(ArrayList<String> array1,
            ArrayList<String> array2) {

        try {
            database.open();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        int aSize = array1.size();

        database.beginTransaction();

        try {
            SQLiteStatement insert = database.compileStatement(INSERT);

            for (int i = 0; i < aSize; i++) {

                insert.bindString(1, array1.get(i));
                insert.bindString(2, array2.get(i));
                insert.executeInsert();

            }

            database.setTransactionSuccessful();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            database.endTransaction();
        }

        try {
            database.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

它很容易適應Longs和Integers等,並且快速閃電。 所以謝天謝地,我不再需要關注blob和字節了! 希望能幫助到你。

有一種更簡單的方法可以用另一種方式完成這樣的事情。 你可以創建一個包含所有數組值的字符串。 為此創建一個StringBuilder並使用分隔符連續附加值和offcource(就像你在數組值中不會使用的simbole一樣。例如,在代碼中使用虛擬'|'。):

double[] mylist = new double[]{23, 554, 55};
    StringBuilder str = null;
    str = new StringBuilder();

    for(int i=0;i<mylist.length;i++){
        str.append(mylist[i]+"|");
    }

    String result = str.toString();

    db.open();
    db.insert(result);
    db.close();

當你想要獲取它們並使用這些值時。 從數據庫中獲取列,將其純化為String,並使用splite()opration pure,數組中的每個數組值都比u更容易使用:)

讓我們在代碼中執行:

String str = db.getdata();
    String[] list = str.split("|");

通過簡單的轉換,您可以將它們用作雙倍;

double mydouble = Double.parsDouble(list[1].toString());

也許它不是標准但它是有幫助的,希望幫助;)

聽起來你想序列化List。 這是 Java Serialization API 的教程/介紹

您必須手動執行此操作,遍歷列表中的每個項目並將其更改為字節,然后再將其存儲在數據庫中

for (long l : array<long>){
//change to byte here
//Store in database here
}
    ArrayList<String> list = new ArrayList<String>();
                    list.add("Item 1");
                    list.add("Item 2");
                    list.add("Item 3");

                    String joined = TextUtils.join(",", list);
                    Log.i(TAG, "joined strings: " + joined);

                    String[] array = TextUtils.split(joined, ",");
                    Log.i(TAG, "joined strings: " + array[0] + array[1] + array[2]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM