我正在編寫一個android應用程序我使用後臺線程從Web服務中提取JSONArray。然後我需要在主要活動中與該JSONArray進行交互。下面是我現在在做什麼:JSONArray上的NullPointerException在後臺線程中初始化
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;
}
我的問題是,我得到一個NullPointerException在調用
System.out.println("stories.length());
它的作用像一個沒有初始化stories數組,但是在這個調用被創建之前,不應該由後臺線程(在這個行:stories = new JSONArray(result);)處理這些事情嗎?
我有一種感覺,這是因爲線程 - 也許有另一個步驟,我必須採取更新AsyncTask運行後的主要活動?