简体   繁体   English

写入文件时,Android NullPointerException

[英]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. 尝试写入内部存储中的文件时出现NullPointerException ,我不知道为什么。 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. 我正在使用HTTP GET request提取一个字符串(它是一行,但是为JSON格式),并试图将该字符串写入内部存储器的JSON文件中。

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. 我知道HTTP GET请求能够正常工作,因为我能够将其登录到LogCat中,但是我停留在想将其写入JSON文件的部分。

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 的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! 编辑:新的onPostExecute作品! forgot to return 忘了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. 由于AsyncTask是异步的,因此datanull因为在调用该方法之前AsyncTask尚未完成。 Call writeToJSON() from onPostExecute() of your AsyncTask so it won't be called until data has a value. AsyncTask onPostExecute()调用writeToJSON() ,直到data具有值才调用它。

Also, doInBackground() returns null but according to your task declaration, 另外, doInBackground()返回null但是根据您的任务声明,

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

onPostExecute() should expect a String . onPostExecute()应该包含String The last param should either be Void or you should return a String from doInBackground() . 最后一个param应该是Void或者应该从doInBackground()返回一个String

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将信息从linkedhashmap写入文件时,发生NullPointerException - NullPointerException when writing information from linkedhashmap to a file 写入RandomAccessFile时发生NullPointerException - NullPointerException When Writing to a RandomAccessFile 在Android应用程序中使用属性文件时发生NullPointerException - NullPointerException when using properties file in android application 使用Android FileProvider删除文件时出现NullPointerException - NullPointerException when deleting file with Android FileProvider Android:读取txt文件时出现NullPointerException - Android: NullPointerException when reading a txt file 在File Android中读取时极其奇怪的NullPointerException - Extremely weird NullPointerException when reading in a File Android findViewById时的Android NullPointerException - Android NullPointerException when findViewById 在 Android 设备上转换和保存图像文件时出现 NullPointerException - NullPointerException when convert and save Image file on Android device 应用程序尝试加密.txt文件时,Android:NullPointerException - Android: NullPointerException when the application attempts to encrypt .txt file 上载文件时出现NullPointerException - NullPointerException when uploading a file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM