通过侦听器将HTTP-JSON数据从asyncTask返回到Activity

时间:2013-10-26 00:46:30

标签: android json

我正在尝试将我的AsyncTask扩展类中的JSON数据返回到我的Activity。 我的活动代码如下:

  public class MainActivity extends Activity implements JSONListener{

        private JSONObject jsonData = null;

        @Override
        public void JSONFeedBack(JSONObject jsonData) {
            // TODO Auto-generated method stub
            this.jsonData = jsonData;
            Log.e("JSON check in JSONFeedBack(): ", jsonData.toString()  );
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            new JsonObj(this).execute("http://xml/url");

        }
    }

我的JSONListener如下:

import org.json.JSONObject;

public interface JSONListener {
    void JSONFeedBack(JSONObject jsonObj);
}

我的asyncTask类如下:

public class JsonObj extends AsyncTask<String, Void, JSONObject>{
    MainActivity activity;
    JSONListener jsonListener;
    int tid;
    String term;

    public JsonObj(JSONListener jsonListener){
        this.jsonListener = jsonListener;
    }

    @Override
    protected JSONObject doInBackground(String... url) {

        // TODO Auto-generated method stub
        DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
        HttpPost httppost = new HttpPost(url[0]);
        JSONObject jsonObject = null;
        // Depends on your web service
        httppost.setHeader("Content-type", "application/json");

        InputStream inputStream = null;
        String result = null;
        try {
            HttpResponse response = httpclient.execute(httppost);           
            HttpEntity entity = response.getEntity();

            inputStream = entity.getContent();
            // json is UTF-8 by default
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null){
                sb.append(line + "\n");
            }
            result = sb.toString();
            Log.e("JSON-Test [RESULT]: ", result);
            jsonObject = new JSONObject(result);


        } catch (Exception e) { 
            Log.e("JSON-Test [exception]: ", e.toString());
        }
        finally {
            try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
        }

        return jsonObject;
    }

    @Override
    protected void onPostExecute(JSONObject result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        this.jsonListener.JSONFeedBack(result);
        Log.e("OnPostExecute TEST: ", result.toString());

    }
}

HTTP-REQUEST获取的实际JSON数据如下:

[
{
"data": {
"term": "All Nations Praise",
"tid": "10"
}
},
{
"data": {
"term": "Classified Advertisements",
"tid": "16"
}
},
{
"data": {
"term": "Kid&#039;s",
"tid": "11"
}
},
{
"data": {
"term": "KT Creative",
"tid": "9"
}
},
{
"data": {
"term": "KT Diary",
"tid": "8"
}
},
{
"data": {
"term": "Live at the Coronet",
"tid": "14"
}
},
{
"data": {
"term": "Situations Vacant",
"tid": "15"
}
},
{
"data": {
"term": "X:Change",
"tid": "13"
}
},
{
"data": {
"term": "Youth",
"tid": "12"
}
}
]

因此,在我的Activity类Log.e("JSON check in JSONFeedBack(): ", jsonData.toString());中调用JSONFeedBack时,我收到空指针异常。

我已经确认在AsynchClass中提取了JSON数据,但我尝试将其发送到活动会导致空指针异常。

2 个答案:

答案 0 :(得分:0)

我刚刚使用我的一项服务运行您的代码更改网址并且工作正常...我认为创建JSONObject

时出现问题
jsonObject = new JSONObject(result);

您确定不记录此行:

Log.e("JSON-Test [exception]: ", e.toString());

即。如果我使用此网址http://puppygifs.tumblr.com/api/read/json,我会获得创建JSONObject的异常,然后是您获得的NPE。

我很确定AsynchTask和Activity之间的通信有效,问题出在你的回复中或者你是如何解析的。

答案 1 :(得分:0)

不要在Json字符串中添加换行符。

 String line = null;
     while ((line = reader.readLine()) != null){
     sb.append(line); // remove + "\n" here
 }

修改:您应该在Log.e("JSON-Test [exception]: ", e.toString());

处看到异常