简体   繁体   中英

Null Pointer Exception Thrown

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?

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

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.

Why are you putting the value in an Array?

You can just use:

comboBox.addItem(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM