在后台线程中初始化的JSONArray上的NullPointerException

时间:2013-02-23 23:34:37

标签: java android

我正在编写一个Android应用程序,我使用后台线程从Web服务中提取JSONArray。然后我需要在主要活动中与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;
    }

我的问题是我在调用

时遇到NullPointerException
System.out.println("stories.length());

它表现得像是没有初始化故事数组,但是在进行该调用之前,不应该由后台线程(在行:stories = new JSONArray(result);)进行处理吗?

我有一种感觉,这是因为线程化 - 也许在AsyncTask运行后我必须采取另一步来更新主要活动?

2 个答案:

答案 0 :(得分:2)

您正在后台线程中初始化变量。这意味着该行

System.out.println(stories.length());

与初始化变量的代码并行执行。这意味着当执行此行时,后台线程很可能没有时间初始化变量。

您的代码类似于以下情况:您面前有一个空杯子,并要求某人去煮咖啡并填满您的杯子。在询问后立即开始饮酒。显然,杯子里面没有咖啡。

重新阅读有关如何执行异步任务的android文档。

答案 1 :(得分:1)

当运行并行单独的线程初始化并更新stories时,您无法依赖stories进行初始化。

  

也许我需要采取另一个步骤来更新主要内容   AsyncTask运行后的活动?

AsyncTask的

onPostExecute()。做你需要的任何UI更新。由于getAll已经是私有内部类,因此您可以完全访问该活动。您已经将stories返回到该(unoverriden)方法,因此这应该是一个小的更改。

@Override
protected void onPostExecute (JSONArray stories)
{
  //use the now initialized stories
}