我必须使用 AsyncTask 用结果填充列表视图。这是我的代码:
public class MyActivity extends Activity {
MainActivity ob;
String url_connectX = "http://hosr.com/test/getjson.php";
Httppostaux post;
JSONArray lststat;
public JSONArray liststatus() {
JSONArray jdata=post.getserverdataX(url_connectX);
return jdata;
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.my_new_screen);
post = new Httppostaux();
new asyncpost().execute();
}
//************************************************************************************
class asyncpost extends AsyncTask< String, String, String > {
List<String> listContents;
protected void onPostExecute(String result) {
pDialog.dismiss();
if (result.equals("ok")){
ListView myListView = (ListView) findViewById(R.id.ListView1);
Log.e("JSON log", "This is my problem = "+listContents);
myListView.setAdapter(new ArrayAdapter<String>(MyActivity.this, android.R.layout.simple_list_item_1, listContents));
}else{
Log.e("JSON log", "ListContents has problems."+listContents);
err_getlista();
}
}
protected String doInBackground(String... params) {
lststat = liststatus();
if (lststat != null){
if (lststat != null && lststat.length() > 0){
JSONObject json_data;
try {
int length = lststat.length();
List<String> listContents = new ArrayList<String>(length);
for (int i = 0; i < length; i++)
{
json_data = lststat.getJSONObject(i);
listContents.add(json_data.getString("client_name"));
}
} catch (Exception e) {
Log.e(null, e.toString());
}
}
return "ok";
}else{
return "err";
}
}
public void err_getlista(){
Toast toast1 = Toast.makeText(getApplicationContext(),"Error", Toast.LENGTH_SHORT);
toast1.show();
}
}
//************************************************************************************
}
listContents 最终为 NULL。为什么?似乎在 postExecute 的某个地方,listContent 的值变为 NULL,即使在 doInBackGround 中似乎有一个非 NULL 值。我不明白这个我该如何解决?