外部AsyncTask从Fragment填充ListView

时间:2012-11-20 13:14:39

标签: android android-asynctask android-fragments

我正在开发基于片段的应用程序。使用AsyncTask从数据库收集这些片段的许多内容。因此,我试图外化“获取数据”类,以便可以重用它。我的片段如下:

public class LocalFragment extends SherlockListFragment {

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

        LoadDataFromURL url_data = new LoadDataFromURL();
        url_data.setContext(getSherlockActivity());
        url_data.setURL("http://url.com/get_data/");
        url_data.execute();

    }

} 

我的LoadDataFromURL课程如下:

class LoadDataFromURL extends AsyncTask<String, String, String>{

    String our_url;
    ListActivity our_context;
    private ProgressDialog pDialog;
    JSONParser jParser = new JSONParser();
    JSONArray results = null;
    List<PubListDetails> pubs = new ArrayList<PubListDetails>();
    Handler mHandler;

    public void setContext(ListActivity context){
        our_context = context;
    }

    public void setURL(String url){
        our_url = url;
    }

    ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String, String>>();

    @Override
    protected void onPreExecute() {

        // TODO Auto-generated method stub
        super.onPreExecute();

        mHandler = new Handler();

        pDialog = new ProgressDialog(our_context);
        pDialog.setMessage("Loading pubs please wait..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub

        List<NameValuePair> params = new ArrayList<NameValuePair>();

        JSONArray json = jParser.makeHttpRequest(our_url, "GET", params);


        Log.d("All Products: ", json.toString());


        try {
            int success = json.length();

            if (success != 0){
                results = json;

                pubs.clear();


                for (int i = 0; i <results.length(); i++){
                    JSONObject c = results.getJSONObject(i);

                    String id = c.getString("id");
                    String name = c.getString("name");
                    String town = c.getString("town");
                    String county = c.getString("county");

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


                    pubs.add(new PubListDetails(id,name,town,county));
                    //map.put(TAG_PID, id);
                    //map.put(TAG_NAME, name);

                    //productsList.add(map);
                }
                }else{
                    Intent i = new Intent(our_context,MainMenu.class);

                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    our_context.startActivity(i);
                }
            } catch (JSONException e){
                e.printStackTrace();
                }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(our_context, "ff", Toast.LENGTH_SHORT).show();
        // TODO Auto-generated method stub
        pDialog.dismiss();

our_context.runOnUiThread(new Runnable(){

    @Override
    public void run() {
        // TODO Auto-generated method stub
        ListAdapter adapter = new PubListAdapter(our_context, pubs);
        our_context.setListAdapter(adapter);
    }});

    }   

}

由于getSherlockActivity未通过ListActivity setListAdapter所需的AsyncTask,因此误给我错误。

独立于此,我感觉越来越多,我在概念上错过了这一点,这不是实现我想要的理想方式。

有人可以建议我如何通过片段调用外部ListView来收集数据然后用它填充{{1}}吗?

1 个答案:

答案 0 :(得分:2)

首先,您要在SherlockListFragment上设置数据,以便您的业务不在Activity

  

独立于此,我感觉越来越多   概念上错过了这一点,这不是理想的实现方式   我想要的是什么。

     

有人可以告诉我如何从片段中调用外部信息   AsyncTask将收集数据,然后填充列表视图   它..?

只需实现一个回调接口。

public interface OnLoadDataListener {
      public onLoadComplete(List<PubListDetails> data);
}

让你的片段类实现这个接口:

public class LocalFragment extends SherlockListFragment implements OnLoadDataListener {

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {    
        super.onActivityCreated(savedInstanceState);
        LoadDataFromURL url_data = new LoadDataFromURL();
        url_data.setContext(getSherlockActivity());
        url_data.setURL("http://url.com/get_data/");
        url_data.setListener(this); // you could unite the setContext() method in the listener registration
        url_data.execute();
    }

    @Override
    public void onLoadComplete(List<PubListDetails> data) {
         ListAdapter adapter = new PubListAdapter(getSherlockActivity(), pubs);
         our_context.setListAdapter(adapter);
    }
}

在您的AsyncTask

private OnLoadDataListener mListener

public void setListener(OnLoadDataListener listener){
    mListener = listener;
}

并在onPostExecute中将数据发送给侦听器:

@Override
protected void onPostExecute(String result) {
    Toast.makeText(our_context, "ff", Toast.LENGTH_SHORT).show();
    // TODO Auto-generated method stub
    pDialog.dismiss();
    if (mListener != null) {
        mListener.onLoadComplete(pubs);
    }
}