2

我有一个扩展片段的类。我会在 Fragment 中调用我的 AsyncTask 类。我在 mylogcat 中没有收到任何错误,但我的列表视图中没有显示 null。下面粘贴我使用的代码,代码更简单,读取一个 json 文件并将其插入到自定义列表视图中。如果更改 Activity 中的类,则此代码有效,但我想在片段中转换我的 Activity。

提前致谢。

    public class MyFragment extends Fragment {

JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> uniList;
JSONArray articles = null;

ListView list;
ListUniAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    new LoadNews().execute();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    LinearLayout ll = (LinearLayout)inflater.inflate(R.layout.uni_list, container, false);
    list = (ListView) ll.findViewById(android.R.id.list);
    return ll;
}

class LoadNews extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    protected String doInBackground(String... args) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("s", "s"));

        String json = jsonParser.makeHttpRequest(Variable.URL_UNIVERSITOMETRO, "GET",
                params);

        try {
            uniList = new ArrayList<HashMap<String, String>>();
            articles = new JSONArray(json);

            if (articles != null) {
                for (int i = 0; i < articles.length(); i++) {
                    JSONObject c = articles.getJSONObject(i);

                    String title = c.getString(Variable.UNI_NAME);
                    String voto = c.getString(Variable.UNI_VOTO);

                    HashMap<String, String> map = new HashMap<String, String>();

                    map.put(Variable.UNI_NAME, title);
                    map.put(Variable.UNI_VOTO, voto);

                    uniList.add(map);

                    if (isCancelled()) break;
                }
            } else {
                Log.d("articles: ", "null");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(String file_url) {

        list.setScrollingCacheEnabled(false);
        adapter = new ListUniAdapter(getActivity(), uniList);
        list.setAdapter(adapter);

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {  }
        });

    }
}

}

4

0 回答 0