0

I am making a dynamic JComboBox which reads the value from a CSV file and put in it. I am able to get the desired values from the file. However when I am trying to put the fetched value in another array to put it in the combobox it's giving me NullPointerException. Here is the code:

        String[] val = null;
        String[] val2 = null;
        try
        {
            FileInputStream fstream = new FileInputStream("rinku.csv");
            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
            String strLine; 
            int i=0;
           while ((strLine = br.readLine()) != null)
            {
                 val = strLine.split(",");
                 val2[i]=val[2]; //NullPointerException thrown here
                //System.out.println(val[2]);
                //String[] options={"op1","op2"};
                 i++;
            }
        }
        catch(IOException e)
        {

        }
        jb= new JComboBox(val2);
        contentPane.add(jb);

Is there is any other way I can put those val[2] values in my JComboBox?

3 Answers 3

2

You never assigned val2. Additionally, next time attach stack-trace and use the error for the first debugging process.

3
  • I used val2 since I have to put val[2] values in it and redirect it in JComboBox. Apr 19, 2014 at 17:02
  • @user3502063 Your code doesn't show it. It seems that val2 is null and invoking [i] on null like null[i] will throw NPE.
    – Pshemo
    Apr 19, 2014 at 17:07
  • Yeah. I just made a small change according to a deleted answer String[] val2= new String[size]; and it works :) Apr 19, 2014 at 17:09
0

val[2] is throwing the NullPointerException for sure.

First, check the length for string array val, then you will realize the actual thing behind this error.

val[].length // check if it is greater than zero or not. If Yes  - Loop it and check the value for 2.

Ideally , Most of the cases NullPointerException or ArrayOutofBoundException are thrown in this cases.

1
  • Yes for val[2] there exists values. Since I initialized with null only it was throwing NullPointerException. I changed it a bit as in above comment and it works :) Apr 19, 2014 at 17:14
0

Why are you putting the value in an Array?

You can just use:

comboBox.addItem(...);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.