我試圖顯示一組提取結果作爲列表。每當我嘗試使用虛擬數據時,它都會正確顯示,但是當我將其更改爲從服務器檢索到的數據時,什麼都不會發生。我沒有得到任何錯誤,所以這是非常混亂setListAdapter not displayed
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class BlogFragment extends ListFragment {
String[] countries = new String[] {
"India",
"Pakistan",
"Sri Lanka",
"China",
"Bangladesh",
"Nepal",
"Afghanistan",
"North Korea",
"South Korea",
"Japan"
};
String [] titles ={};
ArrayAdapter<String> adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
/** Creating an array adapter to store the list of countries **/
new AsyncFetchData().execute();
adapter = new ArrayAdapter<String>(inflater.getContext(), android.R.layout.simple_list_item_1,titles);
return super.onCreateView(inflater, container, savedInstanceState);
}
private class AsyncFetchData extends AsyncTask
{
@Override
protected Object doInBackground(Object... arg0) {
JSONArray a = new JSONArray();
ArrayList<String> aList = new ArrayList<String>();
a = ServerAPI.getData();
for (int i = 0; i < a.length(); i++) {
String title = null;
String content = null;
try {
title = a.getJSONObject(i).getString("title");
content = a.getJSONObject(i).getString("content");
aList.add(title);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(title);
// System.out.println(content);
}
titles = aList.toArray(new String[aList.size()]);
/** Setting the list adapter for the ListFragment */
return null;
}
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
ArrayAdapter aa = new ArrayAdapter(getActivity().getBaseContext(), android.R.layout.simple_list_item_1, titles);
aa.notifyDataSetChanged();
setListAdapter(aa);
}
}
}
正確地顯示在runOnUiThread
法陣countries
而標題沒有的字符串。我檢查放置在標題字符串數組中的數據,它是有效的。 任何想法爲什麼發生這種情況?
你在'setListAdapter'調用之前嘗試'adapter.notifyDatasetChanged()'嗎? –
@MysticMagic沒有任何反應。 – omarsafwany
然後調用listView.invalidateViews();只是在notifyDatasetChanged後 –