简体   繁体   中英

Null Pointer Exception When Writing to ArrayList

I have this code to write a double number inside a txt file located in raw folder and another one to read the file and put all the double number inside the array. I use the array to do a average of the double number in the file.(The double is my ratingbar double) The write is called in a button OnClickListener, after the read.

(Can someone edit this, I don't usually write in english, so i'm sure that it will have some mistakes, even in this quote probably)

Write:

private void writeMyArray(double rate){
        //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("arraymedia.txt", true)));
        //.println(rate);
        double ratex2 = rate * 2;
        int erate = (int)ratex2;
            try
            {
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("myarray.txt", Context.MODE_APPEND));
                outputStreamWriter.append(Integer.toString(erate));
                outputStreamWriter.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

}

Read:

private void readMyArray(ArrayList<Double>array){

    String ret = "";


            try {
                InputStream inputStream = this.getResources().openRawResource(R.raw.myarray);

                if (inputStream != null) {
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String receiveString = "";
                    StringBuilder stringBuilder = new StringBuilder();
                    int enc = 0;
                    while ((receiveString = bufferedReader.readLine()) != null) {
                        stringBuilder.append(receiveString);
                        array.set(enc, Double.parseDouble(bufferedReader.readLine()));
                        ++enc;
                    }
                    inputStream.close();
            }
        } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
}

Average

private double media(ArrayList<Double>array)
{
    double total = 0;
    double media;
    int a = 0;
    for (int i=0; i<array.size(); i++)
    {
        total = total + array.get(i);
        a=i;
    }
    media = total / a;
    return media;
}

Error in the logcat

07-03 09:55:14.496  17307-17307/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.emilio.notification, PID: 17307
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.set(int, java.lang.Object)' on a null object reference
        at com.example.emilio.notification.MainActivity.readMyArray(MainActivity.java:210)
        at com.example.emilio.notification.MainActivity.access$200(MainActivity.java:45)
        at com.example.emilio.notification.MainActivity$2.onClick(MainActivity.java:111)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5257)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Button Click code

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ratingbar.setEnabled(false);
            rating = ratingbar.getRating();

           writeMyArray(rating);
            readMyArray(arraydays);
            button.setText(getText(R.string.obrigado) + "!" + media(arraydays));
            //button.setText(getText(R.string.obrigado)+"!");

            button.setEnabled(false);
        }
    });

UPTADE

when I change the array.set(), it gave me this error:

07-03 10:25:53.576  25334-25334/com.example.emilio.notification E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.emilio.notification, PID: 25334
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
        at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
        at java.util.ArrayList.set(ArrayList.java:481)
        at com.example.emilio.notification.MainActivity.readMyArray(MainActivity.java:210)
        at com.example.emilio.notification.MainActivity.access$200(MainActivity.java:45)
        at com.example.emilio.notification.MainActivity$2.onClick(MainActivity.java:111)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5257)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

The problem is in your while loop

while(receiveString = bufferedReader.readLine()) != null)

This is fine, because it checks for the null .

But in your loop, you then get bufferedReader.readLine() again.

So this means, when the loop is on the last string that is not null .

The code is going to pick up the next string which is now equal to null .

while ((receiveString = bufferedReader.readLine()) != null) {
    stringBuilder.append(receiveString);

    // The next line is the problem
    // bufferedReader.readline() is either null
    // or array is null

    // bufferedReader.readLine() is going to be set to null on the last run.
    array.set(enc, Double.parseDouble(bufferedReader.readLine()));

    ++enc;
}

I think you may be looking for this instead

array.set(enc, Double.parseDouble(receiveString));

or possibly this

string doubleToParse = bufferedReader.readLine();
if(doubleToParse != null) {
    array.set(enc, doubleToParse);
}

Note:
With the second answer, you will be taking two lines from the bufferedReader each time you pass through the loop.

The next problem you might be facing, is setting up your ArrayList .

Make sure you have already called

ArrayList<Double> arrayDays = new ArrayList<Double>();

And if you haven't populated the array already. You should be calling:

array.add(Double.parseDouble(doubleToParse));

On a final note, you must be certain that each string you are parsing actually contains a Double .

Or else you will face a java.lang.NumberFormatException .

try {
    Double d = Double.parseDouble(doubleToParse);
    array.add(d);
} catch (NumberFormatException ex) {
    System.out.println(ex.getMessage());
}

Code seems to be fine try to replace

InputStream inputStream = this.getResources().openRawResource(R.raw.myarray);

to

InputStream inputStream = MainActivity.this.getResources().openRawResource(R.raw.myarray);

Should work for you.

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