0

I code this method to fetch result from SQLite table in java.

    public String[][] select(String query, String table) throws ClassNotFoundException, SQLException
{
    Connection con;
    Statement st;
    Class.forName("org.sqlite.JDBC");
    con = DriverManager.getConnection("jdbc:sqlite:"+table);
    con.setAutoCommit(false);
    st = con.createStatement();
    ResultSet rs = st.executeQuery(query);
    String[][] result = new String[100][4];
    int j = 0;
    while ( rs.next() ) {
        String  name = rs.getString("fullname");
        String  username = rs.getString("username");
        String  password = rs.getString("password");
        String  email = rs.getString("email");
        result[j][0] = name; // line number 63
        result[j][1] = username;
        result[j][2] = password;
        result[j][3] = email;
        j++;
    }
    rs.close();
    st.close();
    con.close();
    return result;
}

From my main method i instantiated this method:

    try{
        String[][] data = db.select("SELECT * FROM user", "fliplist.db"); // line number 37
        System.out.println(data);
    } catch (ClassNotFoundException | SQLException e){
        System.out.println(e.getMessage());
    }

This gives me this error:

run:
Exception in thread "main" java.lang.NullPointerException
at FlipList.Database.select(Database.java:63)
at FlipList.FlipList.main(FlipList.java:37)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)

How it should be in order to fetch the result?

Update

I have initialized the second dimension of the array, and now it showing this error(most likely garbez value):

run:
[[Ljava.lang.String;@2077d4de
BUILD SUCCESSFUL (total time: 2 seconds)

How i can return an array?

rakibtg
  • 5,521
  • 11
  • 50
  • 73
  • 2
    Do us a favor and plop a comment on the line that's causing the error, so we can see where it is without having to guesstimate how much code you haven't shown. – Nic Dec 23 '14 at 13:05
  • Thanks, i plugged the line numbers in comment block – rakibtg Dec 23 '14 at 13:09
  • 2
    You didn't initialize the second dimension of the array, that's why it's null. Should be `new String[100][4]`. Also, you increment your row counter `j` outside of the `while` loop. – lea Dec 23 '14 at 13:09
  • I'm not sure if it will fix it, but I think you have to add `con.commit` after the execution the statement – Xipo Dec 23 '14 at 13:09
  • 1
    @lea Might want to put that into an answer. – Nic Dec 23 '14 at 13:10
  • 2-D array must be initialized. – Darshan Lila Dec 23 '14 at 13:10
  • In addition to what other people are saying, you want to move the `j++` inside the `while` loop or it's gonna overwrite row 0 every time. You also might want to use an ArrayList of `String[]` (`ArrayList`) if you won't always have exactly 100, since that'll both allow you to have more and save memory when you have fewer. – Nic Dec 23 '14 at 13:12
  • That's not an error. That's what `data.toString()` yields, which is what it prints. You need to iterate through to print everything. – Nic Dec 23 '14 at 13:17
  • @newbiedoodle `j++;` was a typo, i don't understand your second comment :) @everone: I have updated the Question please have a review :) – rakibtg Dec 23 '14 at 13:19
  • @rakibtg See my new answer. – Nic Dec 23 '14 at 13:30

3 Answers3

2

(Thanks to @lea for this; if they've posted one please let me know)

You need to initialize the inner arrays, too. In your while loop, put something like this at the top, and it should work.

data[j] = new String[4];

For your new error, you want to iterate through the array instead of just printing it. For example:

for (int i = 0; i < data.length; i++) {
    for (int j = 0; j < data[0].length; j++) {
        System.out.print(data[i][j] + "\t\t");
    }
    System.out.println();
}

There are also a couple of other tips that I'd like to give you:

  1. Move the j++ into the while loop, just before the closing bracket. That way it increments with every loop instead of just once, after every loop. Fixed!

  2. You might want to use an ArrayList<String[]> instead of String[][] if you won't always have exactly a hundred items. That way, you can go over 100 if you need, and if you use less, it will save memory. To do that, you'll want to do something like this for your while loop:

    while ( rs.next() ) {
        String[] nextRow = new String[4];
        String  name = rs.getString("fullname");
        String  username = rs.getString("username");
        String  password = rs.getString("password");
        String  email = rs.getString("email");
        nextRow[0] = name; // line number 63
        nextRow[1] = username;
        nextRow[2] = password;
        nextRow[3] = email;
        result.add(nextRow);
    }
    

You'll also want to change the declaration of data to ArrayList<String[]> result = new ArrayList<String[]>() instead of String[][] result = ....

Nic
  • 6,211
  • 10
  • 46
  • 69
  • there is no put method for ArrayList object – rakibtg Dec 24 '14 at 03:28
  • @rakibtg My bad -- I made a typo. That should be add. I've been using some things with add and others with out and I forgot there was a distinction. – Nic Dec 24 '14 at 03:53
  • @rakibtg Make sure you follow all of the instructions I gave. You'll notice that your 'data' is a String[][]. Mine isn't. – Nic Dec 24 '14 at 04:01
  • Ok, i am still having the null pointer exception error :/ here i paste the code: http://paste.ubuntu.com/9608515/ – rakibtg Dec 24 '14 at 04:09
  • You defined your data as null. Then you call a method on it. You need to initialize data before you can use it. – Nic Dec 24 '14 at 04:12
  • To clarify, see the bottom of the answer. – Nic Dec 24 '14 at 04:13
  • Yes you are correct, i should instantiate a object for result instead of null. But why it should give me garbez data like this- `[[Ljava.lang.String;@2077d4de, [Ljava.lang.String;@7591083d, [Ljava.lang.String;@77a567e1] BUILD SUCCESSFUL (total time: 1 second) ` – rakibtg Dec 24 '14 at 05:11
1

i redefined the ArrayList as the list of Strings rather than Arrays.

public void tester()
    {
        ArrayList result = new ArrayList();


    try
    {
    Connection connect = DriverManager.getConnection(host, username, password);

    String sql="select * from FRIENDS";

    Statement stmt=connect.createStatement();

    ResultSet rs=stmt.executeQuery(sql);



    String[] nextRow = new String[4];
    while ( rs.next() ) {


            String  firstname = rs.getString("FIRSTNAME");
            String  lastusername = rs.getString("LASTNAME");
            String  nickname = rs.getString("NICKNAME");
            String  friendsince = rs.getString("FRIENDSINCE");
            String  email = rs.getString("EMAIL");

            System.out.print("Firstname :- "+firstname+" lastname :- "+lastusername+" nickname :-  "+nickname+" friendsince :- "+friendsince+" Email :- "+email);

            nextRow[0] = firstname; 
            nextRow[1] = lastusername;
            nextRow[2] = nickname;
            nextRow[3] = email;

            System.out.println("The values in array are :- "+nextRow);




            int i=0;
            for(i=0;i<nextRow.length;i++)
            {
                String add1=nextRow[i];

                result.add(add1);
            }



           }

    }

Hope , this helps.

sudhir
  • 46
  • 5
  • You should definitely use generics here -- instead of `ArrayList`, it should be `ArrayList` – Nic Dec 25 '14 at 01:15
  • I used first that only (copying what you guys were discussing) , but that is giving garbage values. In one of the answers to the same question i found following suggestion :-"Ljava.lang.String;@ is returned where you used string arrays as strings." Thus i tried using ArrayList and it seems to work – sudhir Dec 25 '14 at 05:02
  • That has nothing to do with what I'm saying. I'm saying you should define your ArrayList as an `ArrayList` instead, since it's far better coding practice. – Nic Dec 25 '14 at 05:04
  • Can you please elaborate the merits of using ArrayList over ArrayList ? – sudhir Dec 25 '14 at 05:09
  • [This.](http://docs.oracle.com/javase/tutorial/java/generics/why.html). In short, it helps turn runtime errors into faster-to-fix compile errors, and it makes your code cleaner. – Nic Dec 25 '14 at 05:13
  • Thanks @newbiedoodle , but then the above code is giving garbage values. – sudhir Dec 25 '14 at 05:28
  • So iterate through and print each. That's how it's supposed to be done, unless I've forgotten about something. Maybe there's a utility function in the `Arrays` class that does that; I should really check. It might be useful. – Nic Dec 25 '14 at 05:30
  • Got it :-)....and yes using ArrayList result = new ArrayList(); is not giving any garbage values. My bad. i ran the code again and it worked fine. The garbage value is given when i am trying to print nextRow[] which is wrong. Like you said , i iterated though and printed each one of them and it works. Thanks again. – sudhir Dec 25 '14 at 05:41
0
  1. Something very basic . Please execute the query on the DB and see what it returns(Sometimes the query might not be correct e.g the table name can be 'users' instead of 'user', just a guess) :-

SELECT * FROM user

  1. If above is fine , then can you please try extracting the rows using 'columnIndex' instead of the 'columnName'. e.g.

    String  name = rs.getString(1);
    String  username = rs.getString(2);
    String  password = rs.getString(3);
    String  email = rs.getString(4);
    

Here i am assuming that the name , username , password and email belong to 1st , 2nd ,3rd and 4th column respectively.

sudhir
  • 46
  • 5