是否有可能得到的AsyncTask的结果作为ArrayList的Hashmap [英] Is it Possible to get results of AsyncTask as an Arraylist Hashmap

查看:102
本文介绍了是否有可能得到的AsyncTask的结果作为ArrayList的Hashmap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序至少有三个活动的权利,现在使用的AsyncTask到JSON结果返回到一个ListView控件。我的应用程序开始工作,但他得到了基础知识另一个人将尽快接手开发,所以我想尝试让事情尽可能容易使用。这意味着,我试图把尽可能多的重复code到调用的函数成为可能,因此而无需进行复制/粘贴/重用30-40线$ C $每次他们需要查询web服务时间C,他们可能仅在参数传递给函数。

I have at least three activities in my app right now that use an AsyncTask to return JSON results into an ListView. I've started work on the app, but another person will take over development as soon as he gets the basics down, so I want to try and make things as easy to use as possible. This means that I'm trying to turn as much repeatable code into callable functions as possible, so instead of needing to copy/paste/reuse 30-40 lines of code each time they need query a webservice, they can just pass in parameters to a function.

目前,我有在通过Web服务的PHP从MySQL数据库拉健身课程列表的活动如下:

Currently, I have the following in an activity that pulls a list of gym classes from a mysql database via a php webservice:

    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():

I'd like to move this to another class that I have, called "WebServiceTasks", so that I can call something like this in the activity's 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的错误,或其他的东西不匹配的。

While I've tried this, I get a number of errors related to either defining the asyncTask wrong, or other things not matching up.

下面是我在我的WebServiceTasks试图把类:

Here is what I've tried putting in my "WebServiceTasks" class:

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

    }

}

这是可能的,如果是这样,我究竟做错了什么?

Is this possible, and if so, what am I doing wrong?

推荐答案

好吧,你要使用的AsyncTask的的get()方法,这是因为它可以阻止非常昂贵用户界面,直到你的 onPostExecute()完成。我会坚持你火了广播接收器 onPostExecute()来更新你的UI或创建和接口,并使用该接口结果传递给你的活动你的 onPostExecute()。我刚刚建立了一个小的演示使用广播接收器及接口从 onPostExecute()通过结果的活动。你可以从我的github 在这里找到一个演示源

Well, you are trying to use get() method of AsyncTask which is very expensive because it blocks the UI until your onPostExecute() is completed. I would insist you to fire a BroadCastReceiver in onPostExecute() to update your UI or create and Interface and pass the result to your Activity using that interface in your onPostExecute(). I had just created a small demo for using BroadCastReceiver and Interface for passing result from onPostExecute() to your Activity. You can find a demo source from my github here.

这篇关于是否有可能得到的AsyncTask的结果作为ArrayList的Hashmap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆