我正在编写一个 Android 应用程序,我使用后台线程从 Web 服务中提取 JSONArray。然后我需要与主要 Activity 中的 JSONArray 进行交互。这就是我现在正在做的事情:
public class MainActivity extends Activity {
JSONArray stories;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new getAll().execute();
// try {
System.out.println("stories.length());
// } catch (JSONException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
//}
}
以及后台线程:
private class getAll extends AsyncTask <Void, Void, JSONArray> {
private static final String url = "http://10.0.2.2:8080/CalibServer/webresources/storypkg.story/";
@Override
protected JSONArray doInBackground(Void... params) {
//set up client and prepare request object to accept a json object
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
httpget.addHeader("accept", "application/json");
HttpResponse response;
String resprint = new String();
try {
response = httpclient.execute(httpget);
// Get the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
// get entity contents and convert it to string
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
resprint = result;
// construct a JSON object with result
stories =new JSONArray(result);
// Closing the input stream will trigger connection release
instream.close();
}
}
catch (ClientProtocolException e) {System.out.println("CPE"); e.printStackTrace();}
catch (IOException e) {System.out.println("IOE"); e.printStackTrace();}
catch (JSONException e) { System.out.println("JSONe"); e.printStackTrace();}
System.out.println("FUCKYEAHBG: " + resprint);
// stories = object;
return stories;
}
我的问题是我在调用
时遇到 NullPointerExceptionSystem.out.println("stories.length());
它的行为就像没有初始化故事数组,但是在进行调用之前,后台线程(在行:stories =new JSONArray(result);)不应该处理这个问题吗?
我有一种感觉,这是因为线程 - 也许在 AsyncTask 运行后我还需要采取另一个步骤来更新主 Activity ?
最佳答案
您正在后台线程中初始化变量。这意味着该行
System.out.println(stories.length());
与初始化变量的代码并行执行。因此,这意味着当执行此行时,后台线程很有可能还没有时间初始化变量。
您的代码类似于以下情况:您面前有一个空杯子,请某人去煮点咖啡并给您的杯子倒水。问完之后,你就开始喝酒。显然,杯子里不会有咖啡。
重新阅读 android 文档,了解如何执行异步任务。
关于java - JSONArray 上的 NullPointerException 在后台线程中初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15046989/