在异步任务中更改接口(正确的方式)

changing interface in an asynctask (the right way)

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

这是我的异步任务class

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() 方法中设置您的适配器。

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();
  }
}

这应该会给您思路。阅读内联评论:

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);

    }
}

As 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);    
    }

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