[英]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
是异步的,因此data
为null
因为在调用该方法之前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.