是否可以将 AsyncTask 的结果作为 Arraylist Hashmap 获取 [英] Is it Possible to get results of AsyncTask as an Arraylist Hashmap

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

问题描述

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

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.

目前,我在通过 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() 方法,这是非常昂贵的,因为它会阻塞 UI,直到您的 onPostExecute() 完成.我会坚持你在 onPostExecute() 中触发一个 BroadCastReceiver 来更新你的 UI 或创建和 Interface 并使用它将结果传递给你的 ActivityonPostExecute() 中的接口.我刚刚创建了一个小演示,用于使用 BroadCastReceiver 和接口将结果从 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天全站免登陆