在Android中的SQLite数据库中保存ArrayList

Man*_*ngo 18 java sql sqlite android arraylist

我一直在Android上使用SQLite,我想在表中的列中添加一个arraylist,然后将数据作为arraylist获取.arraylist是Longs的列表.我注意到SQL有一个存储BLOBS的选项,但是看起来我需要先将arraylist转换为byte [],然后才能将它作为blob存储在我的SQLite数据库中.

如果有人有一个如何将arraylists保存到SQLite数据库的解决方案,将非常感激.或者是否有任何其他选项来保存我的数据数组,我应该考虑?

小智 28

要插入:

ArrayList<String> inputArray=new ArrayList<String>();
Run Code Online (Sandbox Code Playgroud)

//添加值为inputArray

Gson gson = new Gson();

String inputString= gson.toJson(inputArray);

System.out.println("inputString= " + inputString);
Run Code Online (Sandbox Code Playgroud)

使用"inputString"在SQLite数据库中保存ArrayList的值

要撤消:

从SQLiteDatabse中获取保存的字符串并将其更改为ArrayList类型,如下所示:outputarray是一个String,它是从SQLiteDatabase获取的示例.

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

ArrayList<String> finalOutputString = gson.fromJson(outputarray, type);
Run Code Online (Sandbox Code Playgroud)
  • 在SQLite中使用text作为格式来存储字符串Value .....

  • @ Md.ImranChoudhury'Gson(https://github.com/google/gson)是一个用于使用反射将Java对象转换为JSON和从JSON转换的库. (2认同)

Jul*_*eau 7

请原谅我剽窃我之前对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;
    }

}
Run Code Online (Sandbox Code Playgroud)

注意:如果您的列表有时包含超过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
Run Code Online (Sandbox Code Playgroud)


bra*_*all 6

我有两个ArrayList<String>,都会有1000多个条目.我查看了blob和字节,但对我来说,加速进程并使其可用的解决方案是通过更改插入方法并摆脱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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

它很容易适应Longs和Integers等,并且快速闪电.所以谢天谢地,我不再需要关注blob和字节了!希望能帮助到你.


Moh*_*adi 5

有一种更简单的方法可以完全以另一种方式做这样的事情。您可以创建一个包含所有数组值的字符串。为此,制作一个 StringBuilder 并连续附加值并使用分隔符在场外附加值(就像你不会在数组值中使用的 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();
Run Code Online (Sandbox Code Playgroud)

当您想要获取它们并使用这些值时。将列从数据库中提取为字符串,并使用 splite() 操作将数组的每个值都放在数组列中,这样您就可以轻松使用它了 :)

让我们用代码来做:

String str = db.getdata();
    String[] list = str.split("|");
Run Code Online (Sandbox Code Playgroud)

通过简单的转换,您可以将它们用作双精度;

double mydouble = Double.parsDouble(list[1].toString());
Run Code Online (Sandbox Code Playgroud)

也许它不是标准的,但它很有帮助,希望有所帮助;)


mat*_*t b 1

听起来你想序列化列表。这是Java 序列化 API 的教程/介绍。