简体   繁体   中英

Android NullPointerException when writing to file

I'm getting a NullPointerException when trying to write to a file in the internal storage and I can't figure out why. I read all the documentation and am using that code to test, but no go.

I am pulling a string with a HTTP GET request (it's one single line, but in the JSON format) and am trying to write that string into a JSON file in the internal memory.

I know the HTTP GET request is working correctly as I was able to log that into the LogCat, but I am stuck on the part where I want to write it to a JSON file.

Main Activity

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_checklist);
    mGestureDetector = createGestureDetector(this);

//      JSONReader jsonReader = new JSONReader(this.getApplicationContext());
//      jsonReader.readJson();
//      jsonReader.getData();

    new BackgroundTask().execute("");

    try {
        writeToJSON();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

public void writeToJSON() throws IOException {
    String filename = "test.json";
    FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
    fos.write(data.getBytes());
    fos.close();
}

public class BackgroundTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        HTTPRequest request = new HTTPRequest(1, 2);

        try {
            data = request.GetRequest();
            Log.v("testing", data);
//              request.writeToJSON();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

HTTPRequest

    public String GetRequest() throws MalformedURLException, IOException {
    String charset = "UTF-8";
    URLConnection connection = new URL(listOfChecklistsURL).openConnection();
    InputStream response = connection.getInputStream();
    String contentType = connection.getHeaderField("Content-Type");
    for (String param : contentType.replace(" ", "").split(";")) {
        if (param.startsWith("charset=")) {
            charset = param.split("=", 2)[1];
            break;
        }
    }

    if (charset != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset));
        try {
            for (String line; (line = reader.readLine()) != null;) {
//                  System.out.println(line);
                data = line;
            }
        }
        finally {
            try { reader.close(); } catch (IOException logOrIgnore) {}
        }
    }

    return data;
}

Stack Trace

12-24 16:32:12.159: E/AndroidRuntime(4301): FATAL EXCEPTION: main
12-24 16:32:12.159: E/AndroidRuntime(4301): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.medusa.checkit/com.medusa.checkit.NewChecklistActivity}: java.lang.NullPointerException
12-24 16:32:12.159: E/AndroidRuntime(4301):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
12-24 16:32:12.159: E/AndroidRuntime(4301):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
12-24 16:32:12.159: E/AndroidRuntime(4301):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
12-24 16:32:12.159: E/AndroidRuntime(4301):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
12-24 16:32:12.159: E/AndroidRuntime(4301):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-24 16:32:12.159: E/AndroidRuntime(4301):     at android.os.Looper.loop(Looper.java:137)
12-24 16:32:12.159: E/AndroidRuntime(4301):     at android.app.ActivityThread.main(ActivityThread.java:4424)
12-24 16:32:12.159: E/AndroidRuntime(4301):     at java.lang.reflect.Method.invokeNative(Native Method)
12-24 16:32:12.159: E/AndroidRuntime(4301):     at java.lang.reflect.Method.invoke(Method.java:511)
12-24 16:32:12.159: E/AndroidRuntime(4301):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-24 16:32:12.159: E/AndroidRuntime(4301):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-24 16:32:12.159: E/AndroidRuntime(4301):     at dalvik.system.NativeStart.main(Native Method)
12-24 16:32:12.159: E/AndroidRuntime(4301): Caused by: java.lang.NullPointerException
12-24 16:32:12.159: E/AndroidRuntime(4301):     at com.medusa.checkit.NewChecklistActivity.writeToJSON(NewChecklistActivity.java:52)
12-24 16:32:12.159: E/AndroidRuntime(4301):     at com.medusa.checkit.NewChecklistActivity.onCreate(NewChecklistActivity.java:42)
12-24 16:32:12.159: E/AndroidRuntime(4301):     at android.app.Activity.performCreate(Activity.java:4470)
12-24 16:32:12.159: E/AndroidRuntime(4301):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
12-24 16:32:12.159: E/AndroidRuntime(4301):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
12-24 16:32:12.159: E/AndroidRuntime(4301):     ... 11 more

NEW EDITED CODE - Main Activity

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_checklist);
    mGestureDetector = createGestureDetector(this);


    new BackgroundTask();

}

public void writeToJSON() throws IOException {
    String filename = "test.json";
    FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
    fos.write(data.getBytes());
    fos.close();
}

public class BackgroundTask extends AsyncTask<Void, Void, Void> {

    protected Void doInBackground(Void... params) {
        HTTPRequest request = new HTTPRequest(1, 2);

        try {
            data = request.GetRequest();
            Log.v("testing", data);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute() {
        try {
            writeToJSON();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

EDIT: New onPostExecute works! forgot to return

protected void onPostExecute(Void result) {
        try {
            Log.v("onPostExecute", "writing to JSON");
            JSONWriter writer = new JSONWriter(context, data);
            writer.writeToJSON();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

Since an AsyncTask is asynchronous, data is null because the AsyncTask hasn't finished before that method is called. Call writeToJSON() from onPostExecute() of your AsyncTask so it won't be called until data has a value.

Also, doInBackground() returns null but according to your task declaration,

public class BackgroundTask extends AsyncTask<String, Void, String> {

onPostExecute() should expect a String . The last param should either be Void or you should return a String from doInBackground() .

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