首页 文章

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

提问于
浏览
18

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

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

7 回答

  • 7

    要插入:

    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中使用文本作为格式来存储字符串Value .....
  • 6

    请原谅我剽窃我之前对BLOB vs. VARCHAR for storing arrays in a MySQL table的回答 . 那里的其他答案也非常相关 .

    我认为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
    
  • 26

    我有两个 ArrayList<String> ,两个都会有1000个条目 . 我查看blob和字节,但对我来说,加快进程并使其可用的解决方案是通过更改插入方法并摆脱 database.insert - 这是here .

    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和字节了!希望能帮助到你 .

  • 1

    有一种更简单的方法可以用另一种方式完成这样的事情 . 你可以创建一个包含所有数组值的字符串 . 为此创建一个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());
    

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

  • 2

    听起来你想序列化List . Here is a tutorial/intro到Java Serialization API .

  • 4

    您必须手动执行此操作,遍历列表中的每个项目并将其更改为字节,然后再将其存储在数据库中

    for (long l : array<long>){
    //change to byte here
    //Store in database here
    }
    
  • 0
    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]);
    

相关问题