我正在尝试将 JSON 数据从我的 AsyncTask 扩展类返回到我的 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'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"
}
}
]
Log.e("JSON check in JSONFeedBack(): ", jsonData.toString());
因此,在JSONFeedBack
我的 Activity 类中调用时,我得到了一个空指针异常。
我已确认在 AsynchClass 中获取了 JSON 数据,但我尝试将其发送到活动时仍会导致空指针异常。