Asyntask完成后,如何保持数据值并将数据返回到主UI?

时间:2013-04-21 19:48:22

标签: android android-asynctask

我正在尝试从AsyncTask类中获取值以返回到主UI,即使在完成AsyncTask类之后也是如此。来自onPostExectute()的字符串值将保存到 json_string 供以后使用。但是,当我尝试运行此代码时,它会给我 NullPointerException

我现在已经尝试了3天,仍然无法弄清楚如何解决这个问题:(有人请帮忙。我真的很感谢你的帮助。

P.S:我遵循http://www.androidhive.info/2012/01/android-json-parsing-tutorial/的教程,不过我制作了这个简单的版本进行测试。

public class ParsingJSONDataSample extends Activity {

    // url to make request
    private static String url = "http://api.androidhive.info/contacts/";

    // JSON Node names
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";

    static TextView textId, textName;

    // contacts JSONArray
    static JSONArray contacts = null;

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json_string;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.json_listview_sample);

        textId = (TextView) findViewById(R.id.textView1);
        textName = (TextView) findViewById(R.id.textView2);

        new ReadJSONWebServiceFeedFromURL().execute(url);

        jObj = new JSONObject(json_string);

        // Getting Array of Contacts
        contacts = jObj.getJSONArray(TAG_CONTACTS);
        JSONObject c = contacts.getJSONObject(0);
        textId.setText(c.getString(TAG_ID));
        textName.setText(c.getString(TAG_NAME));        
        }
    }

    //get the JSON webservice from URL
    public String getJSONFromUrl(String url) {

        StringBuilder sb = new StringBuilder();
        String json;
        // Making HTTP request
        try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                StatusLine statusLine = httpResponse.getStatusLine();
                int statuscode = statusLine.getStatusCode();

                if (statuscode == 200){
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent(); 

                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));

                    String line = null;

                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();
                    json = sb.toString();
                }
                else{
                    Log.d("readJSONFeed", "Failed to download file");
                }

        } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
        } catch (ClientProtocolException e) {
                e.printStackTrace();
        } catch (IOException e) {
                e.printStackTrace();
        }

        // return JSON String
        return json;
    }

    //Asynctask class to read the JSON webservice in background
    private class ReadJSONWebServiceFeedFromURL extends AsyncTask<String, Void, String>{

        protected String doInBackground(String... urls) {
            // TODO Auto-generated method stub
            return getJSONFromUrl(urls[0]);
        }

        protected void onPostExecute(String result){
            json_string = result;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

String json;将它用作全局

干杯,