写入文件时的Andr​​oid NullPointerException异常 [英] Android NullPointerException when writing to file

查看:312
本文介绍了写入文件时的Andr​​oid NullPointerException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个 NullPointerException异常时,试图写在内部存储的文件,我想不通为什么。我读了所有的文件和正在使用code测试,但没有去。

我拉着一个字符串 HTTP GET请求(它是一个单一的线,但在JSON格式),我试图将该字符串写入到 JSON 文件中的内部存储器。

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

主要活动

  @覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_new_checklist);
    mGestureDetector = createGestureDetector(本);// JSONReader jsonReader =新JSONReader(this.getApplicationContext());
// jsonReader.readJson();
// jsonReader.getData();    新BackgroundTask()执行();    尝试{
        writeToJSON();
    }赶上(IOException异常五){
        e.printStackTrace();
    }}公共无效writeToJSON()抛出IOException
    字符串文件名=test.json;
    FOS的FileOutputStream = openFileOutput(文件名,Context.MODE_PRIVATE);
    fos.write(data.getBytes());
    fos.close();
}公共类BackgroundTask扩展的AsyncTask<弦乐,太虚,字符串> {
    @覆盖
    保护字符串doInBackground(字符串... PARAMS){
        HTT prequest要求=新HTT prequest(1,2);        尝试{
            数据= request.GetRequest();
            Log.v(测试,数据);
// request.writeToJSON();
        }赶上(MalformedURLException的E){
            e.printStackTrace();
        }赶上(IOException异常五){
            e.printStackTrace();
        }
        返回null;
    }}

HTT prequest

 公共字符串的GetRequest()抛出MalformedURLException的,IOException异常{
    字符串charset =UTF-8;
    URLConnection的连接=新的URL(listOfChecklistsURL).openConnection();
    InputStream的响应= connection.getInputStream();
    字符串的contentType = connection.getHeaderField(内容类型);
    为(字符串参数:contentType.replace(,).split(;)){
        如果(param.startsWith(字符集=)){
            字符集= param.split(=,2)[1];
            打破;
        }
    }    如果(字符集!= NULL){
        读者的BufferedReader =新的BufferedReader(新的InputStreamReader(响应,字符集));
        尝试{
            为(字符串线;(线= reader.readLine())=无效;!){
//的System.out.println(线);
                数据=行;
            }
        }
        最后{
            尝试{reader.close(); }赶上(IOException异常logOrIgnore){}
        }
    }    返回的数据;
}

堆栈跟踪

  16 12-24:32:12.159:E / AndroidRuntime(4301):致命异常:主要
12-24 16:32:12.159:E / AndroidRuntime(4301):了java.lang.RuntimeException:无法启动活动ComponentInfo {com.medusa.checkit / com.medusa.checkit.NewChecklistActivity}:显示java.lang.NullPointerException
12-24 16:32:12.159:E / AndroidRuntime(4301):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
12-24 16:32:12.159:E / AndroidRuntime(4301):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
12-24 16:32:12.159:E / AndroidRuntime(4301):在android.app.ActivityThread.access $ 600(ActivityThread.java:123)
12-24 16:32:12.159:E / AndroidRuntime(4301):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1147)
12-24 16:32:12.159:E / AndroidRuntime(4301):在android.os.Handler.dispatchMessage(Handler.java:99)
12-24 16:32:12.159:E / AndroidRuntime(4301):在android.os.Looper.loop(Looper.java:137)
12-24 16:32:12.159:E / AndroidRuntime(4301):在android.app.ActivityThread.main(ActivityThread.java:4424)
12-24 16:32:12.159:E / AndroidRuntime(4301):在java.lang.reflect.Method.invokeNative(本机方法)
12-24 16:32:12.159:E / AndroidRuntime(4301):在java.lang.reflect.Method.invoke(Method.java:511)
12-24 16:32:12.159:E / AndroidRuntime(4301):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)
12-24 16:32:12.159:E / AndroidRuntime(4301):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-24 16:32:12.159:E / AndroidRuntime(4301):在dalvik.system.NativeStart.main(本机方法)
12-24 16:32:12.159:E / AndroidRuntime(4301):因:显示java.lang.NullPointerException
12-24 16:32:12.159:E / AndroidRuntime(4301):在com.medusa.checkit.NewChecklistActivity.writeToJSON(NewChecklistActivity.java:52)
12-24 16:32:12.159:E / AndroidRuntime(4301):在com.medusa.checkit.NewChecklistActivity.onCreate(NewChecklistActivity.java:42)
12-24 16:32:12.159:E / AndroidRuntime(4301):在android.app.Activity.performCreate(Activity.java:4470)
12-24 16:32:12.159:E / AndroidRuntime(4301):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
12-24 16:32:12.159:E / AndroidRuntime(4301):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
12-24 16:32:12.159:E / AndroidRuntime(4301):11 ...更多

新编code - 主要活动

  @覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_new_checklist);
    mGestureDetector = createGestureDetector(本);
    新BackgroundTask();}公共无效writeToJSON()抛出IOException
    字符串文件名=test.json;
    FOS的FileOutputStream = openFileOutput(文件名,Context.MODE_PRIVATE);
    fos.write(data.getBytes());
    fos.close();
}公共类BackgroundTask扩展的AsyncTask<太虚,太虚,太虚> {    保护无效doInBackground(虚空...... PARAMS){
        HTT prequest要求=新HTT prequest(1,2);        尝试{
            数据= request.GetRequest();
            Log.v(测试,数据);
        }赶上(MalformedURLException的E){
            e.printStackTrace();
        }赶上(IOException异常五){
            e.printStackTrace();
        }
        返回null;
    }    保护无效onPostExecute(){
        尝试{
            writeToJSON();
        }赶上(IOException异常五){
            e.printStackTrace();
        }
    }
}

编辑:新onPostExecute 的作品!忘了收益

 保护无效onPostExecute(虚空结果){
        尝试{
            Log.v(onPostExecute,写JSON);
            JSONWriter作家=新JSONWriter(上下文,数据);
            writer.writeToJSON();
        }赶上(IOException异常五){
            e.printStackTrace();
        }
        返回;
    }


解决方案

由于一个的AsyncTask 是异步的,数据因为的AsyncTask 还没有完成之前,该方法被调用。呼叫 writeToJSON() onPostExecute()你的的AsyncTask 所以它不会被调用,直到数据有一个值。

此外, doInBackground()收益而是根据你的任务声明,

 公共类BackgroundTask扩展的AsyncTask<弦乐,太虚,字符串> {

onPostExecute()应该期待一个字符串。最后一个参数要么是虚空或你应该返回一个字符串 doInBackground()

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().

这篇关于写入文件时的Andr​​oid NullPointerException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆