我正在开展一个小项目来帮助我了解Android。我做了一个小的ListFragment,但我不能让它显示任何东西。我尝试查看日志,但我没有看到任何错误。
ListFragment
public class EspnFragment extends ListFragment {
String URL = "url"
DefaultHttpClient defaultClient = new DefaultHttpClient();
JSONObject jsonObject;
EspnAdapter adapter;
EspnObject object = new EspnObject();
private ArrayList<EspnObject> objects = new ArrayList<EspnObject>();
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = new EspnAdapter(getActivity(), R.layout.list_item_display);
sendRequest();
adapter.addAll(objects);
adapter.notifyDataSetChanged();
setListAdapter(adapter);
setListShown(true);
}
private void sendRequest() {
new Thread(new Runnable() {
@Override
public void run() {
HttpGet request = new HttpGet(URL);
HttpResponse httpResponse = null;
try {
Log.v("ESPN DATA:", "Getting Data");
httpResponse = defaultClient.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
jsonObject = new JSONObject(json);
JSONArray items = jsonObject.getJSONArray("headlines");
for (int i = 0; i < items.length(); i++) {
JSONObject jsonObj = (JSONObject) items.get(i);
String title = jsonObj.getString("headline");
String date = jsonObj.getString("lastModified");
object.setDate(date);
object.setTitle(title);
objects.add(object);
}
Log.v("ESPN DATA:", "Done");
} catch (Exception e) {
e.getStackTrace();
Log.v("ESPN DATA:", "Caught Error" + e.getMessage());
}
}
}).start();
}
}
答案 0 :(得分:0)
当你致电sendRequest
时,它会在一个单独的线程上运行。 addAll
&amp; notifyDataSetChanged
在您致电时objects
无法添加任何内容 adapter.addAll(objects);
adapter.notifyDataSetChanged();
仍为空
移动
{{1}}
到你线程的运行方法