Search code examples
javaarrayssqliteandroid-sqlite

Trying to store information from database into array?


So I am currently trying to figure out how I can store my data from a SQlite database into an array, so that I can use this array somewhere else to manage it's data. I am trying to read all data from a table called ProjectInfo, in this table I use the projectName column to retrieve all of it's data using a while loop.

   public static String [] readAllData () {
        //Connecting to database
        Connection con = DbConnection.connect();
        //Preparing statement
        PreparedStatement ps = null;
        //result set declaration
        ResultSet rs = null;

        //tableData String array
        String tableData [] = new String[300];

            try {
                //Database initialization
                String sql = "SELECT * FROM ProjectInfo";
                ps = con.prepareStatement(sql);
                rs = ps.executeQuery();

                //counter initialization
                int counter = 0;

                while (rs.next()) {
                    //for each iteration store the data into variable a from column projectName
                    String a = rs.getString("projectName");
                    //print out each element to see what is happening
                    System.out.println("a = " + a);
                    //increment counter
                    counter++;
                    
                    //for each increment, store a element from projectName
                    tableData[counter] = a;
                    
                    //testing extra stuff
                    //String b = rs.getString("teamName");
                    //String c = rs.getString("teamLocation");
                    //String d = rs.getString("supportTeamLocation");
                }
                //other catch exceptions
            } catch (SQLException e) {
                System.out.println(e.toString());
            } finally {
                try {
                    rs.close();
                    ps.close();
                    con.close();
                } catch (SQLException e){
                    System.out.println(e.toString());
                }
            }

        System.out.println(tableData);
            //return all the data that has been stored into this array 
            return tableData;

        }

When I run my code, I get the following problem

[Ljava.lang.String;@4c402120

Not sure where to go from here?


Solution

  • If you want to print the items of the array, you must use Arrays.toString() which returns a string consisting of all the items of the array separated by commas:

    System.out.println(Arrays.toString(tableData));
    

    You will have to use this import:

    import java.util.Arrays;
    

    Also, move the line:

    counter++;
    

    after this line:

    tableData[counter] = a;
    

    because the array's index is 0 based.