0

I have a problem in my aplication trying to deserialize a ArrayList of String from a Blob in a SQLite DataBase. I reached to serialize the array and save it in the Database but I could not recover it as it should be. I think the problem is when deserializing because I manage to recover the strings but all within the same array element run. This is the deserializing method

private static ArrayList<String> sqliteBytesToArrayListString(ResultSet results){
        ArrayList<String> acciones = new ArrayList<String>();        
        try {   
                byte[] asBytes = results.getBytes("actions");
                ByteArrayInputStream bin = new ByteArrayInputStream(asBytes);
                BufferedReader din = new BufferedReader(new InputStreamReader(bin));
                for (int i = 0; i < asBytes.length/16; i++) 
                    acciones.add(din.readLine());
        } catch (SQLException e) {
            System.out.println("There was a problem converting bytes[] to ArrayList in the method | " + e.getMessage() + " | " + e.toString());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("There was a problem converting bytes[] to ArrayList in the method | " + e.getMessage() + " | " + e.toString());
            e.printStackTrace();
        }
        return acciones;
    }

Here I leave my complete code

package BDD;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;

public class DataBase {

    private final static String BDD_URL = "jdbc:sqlite:grabadora.db";
    private final static String SCRIT_INSERT = "INSERT INTO test (recordName, actions) VALUES (?, ?);";
    private final static String SCRIT_SELECT_ALL = "SELECT * FROM test;";
    private final static String SCRIPT_TABLE =
        "CREATE TABLE IF NOT EXISTS test (recordId INTEGER PRIMARY KEY AUTOINCREMENT, recordName TEXT, actions BLOB);"; 
    
    public static void main(String[] args) throws SQLException {
        ArrayList<String> datos = new ArrayList<>();
        datos.add("Second");
        datos.add("Third");
        datos.add(0, "First");
        String name = "record2";
        
        Connection con = DataBase.getConnection();
        DataBase.createTable(con);
        DataBase.addNewRecord(name, datos, con);
        con.close();
        System.out.print(DataBase.getRecords());
        
    }    
    
    public static void addNewRecord(String nombre, ArrayList<String> acciones, Connection con){
        
        try {
            PreparedStatement stat = con.prepareStatement(SCRIT_INSERT, Statement.RETURN_GENERATED_KEYS);
            stat.setString(1, nombre);
            stat.setBytes(2, arrayListToBytes(acciones));
            stat.executeUpdate();
            ResultSet res = stat.getGeneratedKeys();
            
            while(res.next()){
                System.out.println(res.getInt(1) + "\t" );
            }
            stat.close();
            res.close();
            
        } catch (SQLException e) {
            System.out.println("There was a problem doing the update in the method | " + e.getMessage() + " | " + e.getSQLState()+ " | " + e.toString());
            e.printStackTrace();
        }
    }
       
    public static String getRecords(){
        Connection con = DataBase.getConnection();
        String Records="";
        try{
            Statement sta = con.createStatement();
            ResultSet results = sta.executeQuery(SCRIT_SELECT_ALL);

            while(results.next()){
                int id = Integer.parseInt(results.getString("recordId"));
                String nombre = results.getString("recordName");
                ArrayList<String> actionsArray = sqliteBytesToArrayListString(results);
                String print = "\n RecordId= " + id + " | RecordName= " + nombre + " | Actions= " + Arrays.toString(actionsArray.toArray()) ;
                Records += print;
            }
            con.close();
            sta.close();
        }catch(SQLException e){
            System.out.println("There was a problem al obtener las grabaciones in the method | " + e.getMessage() + " | " + e.toString());
            e.printStackTrace();
        }
        return Records;
    }
    
    private static ArrayList<String> sqliteBytesToArrayListString(ResultSet results){
        ArrayList<String> acciones = new ArrayList<String>();        
        try {   
                byte[] asBytes = results.getBytes("actions");
                ByteArrayInputStream bin = new ByteArrayInputStream(asBytes);
                BufferedReader din = new BufferedReader(new InputStreamReader(bin));
                for (int i = 0; i < asBytes.length/16; i++) 
                    acciones.add(din.readLine());
        } catch (SQLException e) {
            System.out.println("There was a problem converting bytes[] to ArrayList in the method | " + e.getMessage() + " | " + e.toString());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("There was a problem converting bytes[] to ArrayList in the method | " + e.getMessage() + " | " + e.toString());
            e.printStackTrace();
        }
        return acciones;
    }
    
    private static byte[] arrayListToBytes(ArrayList<String> array){
        byte[] dataInBytes= new byte[1];
        try {
            ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
            DataOutputStream dataOutput = new DataOutputStream(byteOutput);
            
            for (String  element: array) 
                dataOutput.writeBytes(element);
            
            dataOutput.close();            
            dataInBytes = byteOutput.toByteArray();            
            
        } catch (IOException e) {
            System.out.println("There was a problem converting the ArrayList in the method | " + e.getMessage() + " | " + e.toString());
            e.printStackTrace();
        }
        
        return dataInBytes;        
    }
    
    private static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName("org.sqlite.JDBC");            
            conn = DriverManager.getConnection(BDD_URL);
            System.out.println("Connection created successfully");
        } catch (ClassNotFoundException e) {
            System.out.println("There was a problem creating the connection in the method | " + e.getMessage() + " | " + e.toString());
            e.printStackTrace();
        } catch (SQLException e){
            System.out.println("There was a problem creating the connection in the method | " + e.getMessage() + " | " + e.toString());
            e.printStackTrace();
        }
        return conn;
    }
    
    private static void createTable(Connection conexion){
        try {
            Statement stat = conexion.createStatement();
            stat.executeUpdate(SCRIPT_TABLE);
            stat.close();
            System.out.println("The table was created or already exists");
        } catch (SQLException e) {
            System.out.println("There was a problem creating the table in the method | " + e.getMessage() + " | " + e.toString());
            e.printStackTrace();
        }
    }
    
}

I base myself on this answer about to store a ArrayList in sql

And I use this tool to se the use this tool to view my database data I got this results

brandon v
  • 36
  • 5

0 Answers0