使用AsyncTask結果生成listView,代碼:
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 出現空值,為什麼?請各位幫忙看一下謝謝
在doInBackground中重新聲明listContents。這是一個局部變量,優先級高於類成員。
// should be ...
// listContents = new ArrayList<String>(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"));
}