我試圖從我的AsyncTask擴展類中返回JSON數據到我的Activity。 我的活動代碼如下:從asyncTask通過監聽器返回HTTP-JSON數據到活動
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類如下:通過HTTP
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());
}
}
實際JSON數據取 - 請求如下:
[
{
"data": {
"term": "All Nations Praise",
"tid": "10"
}
},
{
"data": {
"term": "Classified Advertisements",
"tid": "16"
}
},
{
"data": {
"term": "Kid'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類的JSONFeedBack
中調用Log.e("JSON check in JSONFeedBack(): ", jsonData.toString());
時遇到空指針異常。
我已經確認JSON數據是在AsynchClass中獲取的,但是我嘗試將它發送到活動會導致空指針異常。
看到因爲這個異常你試圖把'Log.e( 「OnPostExecute TEST:」 result.toString());''之前這.jsonListener.JSONFeedBack(result);'確定'result'不是null? – DrChivas