我无法让我的ListFragment显示数据android

时间:2014-03-18 05:20:55

标签: java android fragment android-listfragment

我正在开展一个小项目来帮助我了解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();
    }
}

1 个答案:

答案 0 :(得分:0)

当你致电sendRequest时,它会在一个单独的线程上运行。 addAll&amp; notifyDataSetChanged在您致电时objects无法添加任何内容 adapter.addAll(objects); adapter.notifyDataSetChanged(); 仍为空

移动

{{1}}

到你线程的运行方法