写入文件时出现Android NullPointerException

时间:2013-12-25 00:27:40

标签: java android json file-io

我在尝试写入内部存储中的文件时得到NullPointerException,我无法弄清楚原因。我阅读了所有文档并使用该代码进行测试,但没有去。

我正在使用HTTP GET request(它是一行,但是采用JSON格式)拉一个字符串,并尝试将该字符串写入内部存储器中的JSON文件。

我知道HTTP GET请求正常工作,因为我能够将其记录到LogCat中,但是我被困在我想将其写入JSON文件的部分。

主要活动

    @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;
}

堆栈跟踪

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

新编辑代码 - 主要活动

    @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();
        }
    }
}

编辑:新的onPostExecute 有效!忘了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;
    }

1 个答案:

答案 0 :(得分:1)

由于AsyncTask是异步的,datanull,因为AsyncTask在调用该方法之前尚未完成。从writeToJSON()的{​​{1}}致电onPostExecute(),以便在AsyncTask有值之前不会致电。{/ p>

此外,data会返回doInBackground(),但根据您的任务声明,

null

public class BackgroundTask extends AsyncTask<String, Void, String> { 应该期待onPostExecute()。最后String应该是param,或者您应该从Void返回String