【问题标题】:changing interface in an asynctask (the right way)在异步任务中更改接口(正确的方式)
【发布时间】:2015-01-14 10:28:57
【问题描述】:

我正在尝试将检索到的流程数据更改为列表视图。数据被正确接收。但我没有以正确的方式组成列表视图。

这是我的异步任务类

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

    String id = "";
    String fullName = "";
    String birthday = "";

    protected void onPreExecute() {
        super.onPreExecute();
        pd_GetData = new ProgressDialog(MainActivity.this);
        pd_GetData.setMessage("Getting friend data");
        pd_GetData.setIndeterminate(false);
        pd_GetData.setCancelable(true);
        pd_GetData.show();
    }

    @Override
    protected String doInBackground(String... params) {

        JSONArray friendArray;

        List<NameValuePair> param = new ArrayList<NameValuePair>();
        param.add(new BasicNameValuePair("user_id", id));
        param.add(new BasicNameValuePair("user_id", fullName));
        param.add(new BasicNameValuePair("user_id", birthday));

        JSONObject jsonObject = jsonParser.makeHttpRequest(url_get_birthdays,"GET", param);

        try{
            int success = jsonObject.getInt(TAG_SUCCESS);

            if (success == 1){
                Log.d("PHP Server [GET]", "Retrieved user data");

                String jsonString = jsonObject.getString("message");
                friendArray = new JSONArray(jsonString);

                String[] names = new String[friendArray.length()];
                String[] birthdays = new String[friendArray.length()];
                String[] ids = new String[friendArray.length()];

                for(int i=0; i<friendArray.length(); i++) {
                    JSONObject friend = friendArray.getJSONObject(i);
                    String friend_id = friend.getString("id");
                    ids[i] = friend_id;
                    String friend_name = friend.getString("fullName");
                    names[i] = friend_name;
                    String friend_birthday = friend.getString("birthday");
                    birthdays[i] = friend_birthday;
                }

                Log.i("friend:", Arrays.toString(ids) + " " + Arrays.toString(names) + " " + Arrays.toString(birthdays));

               List<HashMap<String, String>> birthday = new ArrayList<HashMap<String, String>>();

                for (int i=0;i<names.length;i++){
                    HashMap<String, String> hm = new HashMap<String, String>();
                    hm.put("names", names[i]);
                    hm.put("ids", ids[i]);
                    hm.put("birthdays", birthdays[i]);
                    birthday.add(hm);
                }

                String[] from = {"names", "ids", "birthdays"};
                int[] to = {R.id.text1, R.id.im_ProfilePic, R.id.text2};

                SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, birthday, R.layout.listitem_birthday, from, to);
                HorizontalListView featuredList = (HorizontalListView) findViewById(R.id.lv_Birthdays);
                featuredList.setAdapter(adapter);

            }else{
                Log.d("PHP Server [GET]", "Failed retrieve user data");
            }
        }catch (JSONException e){
            e.printStackTrace();
        }catch (RuntimeException e){
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(JSONArray result) {
        // dismiss the dialog once done


        pd_GetData.dismiss();
    }
}

我知道我不应该在 doInBackground 中创建列表视图。但我不知道该怎么做。

【问题讨论】:

  • onPostExecute做吧
  • @nasir 如何将收到的数据发送到 onPostExecute?
  • AsyncTask#doInBackGRound 不在 UI Thread 中执行,但 AsyncTask#onPostExecute 是

标签: java android json android-listview android-asynctask


【解决方案1】:

这应该给你的想法。阅读内联 cmets:

class GetFriendsInfo extends AsyncTask<Void, Void, JSONObject> {
    private String url;
    public GetFriendsInfo(String url_get_birthdays) {
        this.url = url_get_birthdays;
    }
    @Override
    protected JSONObject doInBackground(Void... params) {
        // Make your network call and get your JSONObject
        JSONObject jsonObject = jsonParser.makeHttpRequest(url_get_birthdays,"GET", param);

        return jsonObject;
    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        // Here you get your jsonObject on the main thread. You can  parse it and update your UI
        // Convert your jsonObject to what you want and then show the dialog


String[] from = {"names", "ids", "birthdays"};
        int[] to = {R.id.text1, R.id.im_ProfilePic, R.id.text2};

        SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, birthday,   R.layout.listitem_birthday, from, to);
        HorizontalListView featuredList = (HorizontalListView) findViewById(R.id.lv_Birthdays);
        featuredList.setAdapter(adapter);

    }
}

【讨论】:

    【解决方案2】:

    在 onPostExecute() 方法中设置您的适配器。

    class GetFriendsInfo extends AsyncTask<String, String, String>{
    
    String id = "";
    String fullName = "";
    String birthday = "";
    List<HashMap<String, String>> birthday;
    
    protected void onPreExecute() {
        super.onPreExecute();
        pd_GetData = new ProgressDialog(MainActivity.this);
        pd_GetData.setMessage("Getting friend data");
        pd_GetData.setIndeterminate(false);
        pd_GetData.setCancelable(true);
        pd_GetData.show();
    }
    
    @Override
    protected String doInBackground(String... params) {
    
        JSONArray friendArray;
    
        List<NameValuePair> param = new ArrayList<NameValuePair>();
        param.add(new BasicNameValuePair("user_id", id));
        param.add(new BasicNameValuePair("user_id", fullName));
        param.add(new BasicNameValuePair("user_id", birthday));
    
        JSONObject jsonObject = jsonParser.makeHttpRequest(url_get_birthdays,"GET", param);
    
        try{
            int success = jsonObject.getInt(TAG_SUCCESS);
    
            if (success == 1){
                Log.d("PHP Server [GET]", "Retrieved user data");
    
                String jsonString = jsonObject.getString("message");
                friendArray = new JSONArray(jsonString);
    
                String[] names = new String[friendArray.length()];
                String[] birthdays = new String[friendArray.length()];
                String[] ids = new String[friendArray.length()];
    
                for(int i=0; i<friendArray.length(); i++) {
                    JSONObject friend = friendArray.getJSONObject(i);
                    String friend_id = friend.getString("id");
                    ids[i] = friend_id;
                    String friend_name = friend.getString("fullName");
                    names[i] = friend_name;
                    String friend_birthday = friend.getString("birthday");
                    birthdays[i] = friend_birthday;
                }
    
                Log.i("friend:", Arrays.toString(ids) + " " + Arrays.toString(names) + " " + Arrays.toString(birthdays));
    
                birthday = new ArrayList<HashMap<String, String>>();
    
                for (int i=0;i<names.length;i++){
                    HashMap<String, String> hm = new HashMap<String, String>();
                    hm.put("names", names[i]);
                    hm.put("ids", ids[i]);
                    hm.put("birthdays", birthdays[i]);
                    birthday.add(hm);
                }
    
    
    
            }else{
                Log.d("PHP Server [GET]", "Failed retrieve user data");
            }
        }catch (JSONException e){
            e.printStackTrace();
        }catch (RuntimeException e){
            e.printStackTrace();
        }
    
        return null;
    }
    
    protected void onPostExecute(JSONArray result) {
        // dismiss the dialog once done
    
        String[] from = {"names", "ids", "birthdays"};
                int[] to = {R.id.text1, R.id.im_ProfilePic, R.id.text2};
    
                SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, birthday,   R.layout.listitem_birthday, from, to);
                HorizontalListView featuredList = (HorizontalListView) findViewById(R.id.lv_Birthdays);
                featuredList.setAdapter(adapter);
    
          pd_GetData.dismiss();
      }
    }
    

    【讨论】:

      【解决方案3】:

      由于 UI 操作无法在 doinbackground 中进行。所以首先在 asyntask 中将生日列表设为全局。

      List<HashMap<String, String>> birthday = new ArrayList<HashMap<String, String>>(); // make it Global.
      

      将下面的部分从doinbackground移到

      protected void onPostExecute(JSONArray result) {
              // dismiss the dialog once done
      
              pd_GetData.dismiss();
      
          String[] from = {"names", "ids", "birthdays"};
                      int[] to = {R.id.text1, R.id.im_ProfilePic, R.id.text2};
      
                      SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, birthday, R.layout.listitem_birthday, from, to);
                      HorizontalListView featuredList = (HorizontalListView) findViewById(R.id.lv_Birthdays);
                      featuredList.setAdapter(adapter);    
          }
      

      如果您仍有疑问,请告诉我。

      【讨论】:

      • 谢谢,这确实是解决方案
      猜你喜欢
      • 1970-01-01
      • 2019-01-22
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 2016-07-16
      • 1970-01-01
      相关资源
      最近更新 更多