Saving ArrayList in SQLite database in Android

后端 未结 7 1685
臣服心动
臣服心动 2020-12-04 18:11

I\'ve been working with SQLite on android and I would like to add an arraylist to a column in a table, and then fetch the data back as an arraylist. The arraylist is a list

7条回答
  •  独厮守ぢ
    2020-12-04 18:48

    I had two ArrayList, both will 1000+ entries. I looked at blobs and bytes, but for me the solution to speeding up the process and making it usable was by changing the insert method and getting rid of database.insert - Credit for this is here.

    private static final String INSERT = "insert into "
                + YOUR_TABLE_NAME+ " (" + COLUMN_1 + ", "
                + COLUMN_2 + ") values (?, ?)";
    
    public void insertArrayData(ArrayList array1,
                ArrayList 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();
            }
        }
    

    It's easily adaptable to Longs and Integers etc and lightening quick. So thankfully I didn't have to scratch my head any longer about blobs and bytes! Hope it helps.

提交回复
热议问题