是否可以将AsyncTask的结果作为Arraylist Hashmap

时间:2012-09-17 05:07:40

标签: android arraylist android-asynctask

我的应用程序中至少有三个活动,它们使用AsyncTask将JSON结果返回到ListView。我已经开始研究应用程序了,但是一旦他掌握了基础知识,另一个人就会接管开发,所以我想尝试让事情变得尽可能容易。这意味着我正在尝试将尽可能多的可重复代码转换为可调用函数,因此每次需要查询Web服务时,不需要复制/粘贴/重用30-40行代码,而只需将参数传递给一个功能。

目前,我在一个活动中有以下内容,该活动通过php webservice从mysql数据库中提取健身类的列表:

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

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //          pDialog = new ProgressDialog(Checkin.this);
        //          pDialog.setMessage("Loading products. Please wait...");
        //          pDialog.setIndeterminate(false);
        //          pDialog.setCancelable(false);
        //          pDialog.show();
    }

    /**
     * getting All products from url
     * */
    @Override
    protected String doInBackground(String... args) {
        // Building Parameters

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", getclasses_tag));
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(SmashGyms.WEBSERVICE_URL,
                "POST", params);

        // Check your log cat for JSON response
        Log.d("CheckinDialog", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // classes found
                // Getting Array of Classes
                classes2 = json.getJSONArray(TAG_CLASSES);

                // looping through All Classes
                for (int i = 0; i < classes2.length(); i++) {
                    JSONObject c = classes2.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_CLASSID);
                    String name = c.getString(TAG_CLASSNAME);
                    //String day = c.getString(TAG_DAY);

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

                    // adding each child node to HashMap key => value
                    map.put(TAG_CLASSID, id);
                    map.put(TAG_CLASSNAME, name);
                    //map.put(TAG_DAY, day);
                    // adding HashList to ArrayList
                    allclasseslist.add(map);
                    Log.d("map: ", map.toString());

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

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                adapter = new SimpleAdapter(CheckinDialog.this,
                        allclasseslist, R.layout.checkin_item,
                        new String[] { TAG_CLASSID, TAG_CLASSNAME },
                        new int[] { R.id.pid, R.id.name });

                setListAdapter(adapter);
            }
        });

        //pDialog.dismiss();
        // updating UI from Background Thread

    }

}

我想把它移到我所拥有的另一个类,称为“WebServiceTasks”,这样我就可以在活动的OnCreate()中调用类似的东西:

allclasseslist = new ArrayList<HashMap<String, String>>();
allclasseslist = new WebServiceTasks.LoadAllClasses().get();
    adapter = new SimpleAdapter(CheckinDialog.this,
            allclasseslist, R.layout.checkin_item,
            new String[] { TAG_CLASSID, TAG_CLASSNAME },
            new int[] { R.id.pid, R.id.name });

    setListAdapter(adapter);

虽然我已经尝试了这个,但是我得到了许多与定义asyncTask错误相关的错误,或者其他与之不匹配的错误。

以下是我在“WebServiceTasks”课程中尝试的内容:

public static class LoadAllClasses extends
        AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> allclasseslist;
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_CLASSES = "classes";
    private static final String TAG_CLASSID = "id";
    private static final String TAG_CLASSNAME = "class";
    private static final String getclasses_tag = "getclasses";

    JSONArray classes2 = null;

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //          pDialog = new ProgressDialog(Checkin.this);
        //          pDialog.setMessage("Loading products. Please wait...");
        //          pDialog.setIndeterminate(false);
        //          pDialog.setCancelable(false);
        //          pDialog.show();
    }

    /**
     * getting All classes from url
     * */
    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(
            String... args) {
        // Building Parameters

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", getclasses_tag));
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(SmashGyms.WEBSERVICE_URL,
                "POST", params);

        // Check your log cat for JSON response
        Log.d("CheckinDialog", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // classes found
                // Getting Array of Classes
                classes2 = json.getJSONArray(TAG_CLASSES);

                // looping through All Classes
                for (int i = 0; i < classes2.length(); i++) {
                    JSONObject c = classes2.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_CLASSID);
                    String name = c.getString(TAG_CLASSNAME);
                    //String day = c.getString(TAG_DAY);

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

                    // adding each child node to HashMap key => value
                    map.put(TAG_CLASSID, id);
                    map.put(TAG_CLASSNAME, name);
                    //map.put(TAG_DAY, day);
                    // adding HashList to ArrayList
                    allclasseslist.add(map);
                    Log.d("map: ", map.toString());

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

        return allclasseslist;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(
            ArrayList<HashMap<String, String>> allclasses) {
        // dismiss the dialog after getting all products

        //pDialog.dismiss();
        // updating UI from Background Thread

    }

}

这是可能的,如果是的话,我做错了什么?

3 个答案:

答案 0 :(得分:1)

好吧,您正在尝试使用非常昂贵的get()方法,因为它会阻止用户界面,直到onPostExecute()完成。我会坚持要在BroadCastReceiveronPostExecute()更新您的用户界面或创建Interface并使用onPostExecute()中的该界面将结果传递给您的活动。我刚刚创建了一个小型演示,用于使用BroadCastReceiver和Interface将结果从onPostExecute()传递给您的Activity。你可以从我的github here找到一个演示源。

答案 1 :(得分:0)

您可以创建一个Bean类来存储来自异步任务的所有值,以便您可以将它接收到我的朋友的另一个类

答案 2 :(得分:0)

对于任何想要复制此内容的人来说,以下是我使用Lalit和Samir的例子解决这个问题的方法:

在我的活动中:

public class CheckinDialog extends ListActivity implements
    AsyncTaskCompleteListener {

WebServiceTasks.LoadAllClasses objAsyncTask = new WebServiceTasks.LoadAllClasses(
            this);
    objAsyncTask.execute();

@Override
public void onTaskComplete(ArrayList<HashMap<String, String>> allclasseslist) {
    // TODO Auto-generated method stub
    adapter = new SimpleAdapter(CheckinDialog.this, allclasseslist,
            R.layout.checkin_item, new String[] { TAG_CLASSID,
                    TAG_CLASSNAME }, new int[] { R.id.pid, R.id.name });

    setListAdapter(adapter);
    Log.d("OnTaskComplete", "taskcomplete");

}

在名为&#34; AsyncTaskCompleteListener&#34;的接口中:

public interface AsyncTaskCompleteListener {
    void onTaskComplete(ArrayList<HashMap<String, String>> allclasseslist);
}

和单独的WebServiceTasks类:

    public static class LoadAllClasses extends
        AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
    JSONParser jParser = new JSONParser();
    private final AsyncTaskCompleteListener callback;
    private final Activity activity;

    public LoadAllClasses(Activity act) {
        this.activity = act;
        this.callback = (AsyncTaskCompleteListener) act;
    }

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_CLASSES = "classes";
    private static final String TAG_CLASSID = "id";
    private static final String TAG_CLASSNAME = "class";
    private static final String getclasses_tag = "getclasses";

    JSONArray classes2 = null;

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    /**
     * getting All classes from url
     * */
    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(
            String... args) {
        // Building Parameters
        ArrayList<HashMap<String, String>> allclasseslist = null;
        allclasseslist = new ArrayList<HashMap<String, String>>();
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", getclasses_tag));
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(SmashGyms.WEBSERVICE_URL,
                "POST", params);

        // Check your log cat for JSON response
        Log.d("CheckinDialog", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // classes found
                // Getting Array of Classes
                classes2 = json.getJSONArray(TAG_CLASSES);
                Log.d("JSONArray", json.getJSONArray(TAG_CLASSES)
                        .toString());
                // looping through All Classes
                for (int i = 0; i < classes2.length(); i++) {
                    JSONObject c = classes2.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_CLASSID);
                    String name = c.getString(TAG_CLASSNAME);
                    //String day = c.getString(TAG_DAY);

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

                    // adding each child node to HashMap key => value
                    map.put(TAG_CLASSID, id);
                    map.put(TAG_CLASSNAME, name);
                    //map.put(TAG_DAY, day);
                    // adding HashList to ArrayList
                    allclasseslist.add(map);
                    //Log.d("map: ", map.toString());

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

        return allclasseslist;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(
            ArrayList<HashMap<String, String>> allclasseslist) {
        super.onPostExecute(allclasseslist);
        // dismiss the dialog after getting all classes
        callback.onTaskComplete(allclasseslist);
    }

}

感谢大家的快速帮助。最终在使用此代码的每个活动中保存了超过120行重复代码。