【问题标题】:How to set the arraylist to object after the postExecute of asyncTask?如何在 asyncTask 的 postExecute 之后将 arraylist 设置为对象?
【发布时间】:2016-07-05 13:22:27
【问题描述】:

我有 2 个异步任务。一个用于 GetCheckLists,另一个用于 GetCheckListItems。 在 CheckList 类中,它有 checkListId、Title 等和 checkListItems 的 arrayList。

首先,我使用 GetCheckListAsyncTask 获取所有检查列表。现在,对于每个 checkList,我都调用 GetCheckListItemsAsync 任务来获取所有 checkListItems。

现在GetCheckListItemsAsyncTask的onPostExecute方法我要设置checkListItemArrayList。

如何确保将 checkListItemArrayList 添加到 checkList 项的对象?

检查列表活动:

    public class CheckListActivity extends AppCompatActivity implements CheckListAdapter.OnItemClickListener{

    private ProgressDialog progressDialog;
    private RecyclerView recyclerView;
    private ArrayList<CheckList> checkLists = new ArrayList<>();
    private CheckList mCheckList;
    private ArrayList<CheckListItem> itemList;
    private ArrayList<CheckList> checkListArrayList;
    private CheckListAdapter mAdapter;
    JSONArray checkListsItemArray,checkListArray;
    public int iterationCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_list);

        checkListArrayList = new ArrayList<>();

        mEventId = mIntent.getStringExtra("eventId");

        mCheckList = new CheckList();

        progressDialog = new ProgressDialog(CheckListActivity.this);

        recyclerView = (RecyclerView)findViewById(R.id.recycler_view);

        mAdapter = new CheckListAdapter(checkListArrayList,CheckListActivity.this,CheckListActivity.this);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);

        GetCheckListAsyncTask getCheckListAsyncTask = new GetCheckListAsyncTask();
        getCheckListAsyncTask.execute(mEventId);

    }

    }

    @Override

    public class GetCheckListsItemAsyncTask extends AsyncTask<String, Void, JSONObject> {

        private String api;
        private JSONObject jsonParams;
        public GetCheckListsItemAsyncTask(){}

        @Override
        protected JSONObject doInBackground(String... params) {
            try {
                api = getResources().getString(R.string.server_url) + "api/checklist_items/getChecklistItems.php";

                jsonParams = new JSONObject();
                String checklistId = params[0];  // params[0] is username
                jsonParams.put("checklistId", checklistId);

                ServerRequest request = new ServerRequest(api, jsonParams);
                return request.sendRequest();
            } catch(JSONException je) {
                return Excpetion2JSON.getJSON(je);
            }
        }  //end of doInBackground

        @Override
        protected void onPostExecute(JSONObject response) {
            super.onPostExecute(response);
            Log.e("ServerResponse", response.toString());
            try {
                int result = response.getInt("result");
                String message = response.getString("message");
                if (result == 1) {
                    Toast.makeText(CheckListActivity.this, message, Toast.LENGTH_LONG).show();
                    //code after getting profile details goes here
                    checkListsItemArray = response.getJSONArray("checklistItems");

                    for (int i = 0; i < checkListsItemArray.length(); i++) {

                        int pendingTasks = 0,completedTasks = 0;

                        itemList = new ArrayList<>();

                        CheckListItem checkListItem = new CheckListItem();

                        JSONObject subObject = checkListsItemArray.getJSONObject(i);
                        String checkListItemName = subObject.getString("text");//name of the attribute in response
                        String checkListItemBudget = subObject.getString("budget");//name of the attribute in response
                        String checkListItemTimedate = subObject.getString("time_due");
                        String checkListItemReminder = subObject.getString("reminder");
                        String checkListItemId = subObject.getString("checklistItemId");
                        String checkListItemStatus = subObject.getString("status");

                        if (checkListItemStatus.equals("1")) {
                            completedTasks++;
                        }
                        if (checkListItemStatus.equals("0")) {
                            pendingTasks++;
                        }

                        checkListItem.setTitle(checkListItemName);
                        checkListItem.setBudget(checkListItemBudget);
                        checkListItem.setDateTime(checkListItemTimedate);
                        checkListItem.setReminder(checkListItemReminder);
                        checkListItem.setCheckListItemId(checkListItemId);
                        checkListItem.setStatus(checkListItemStatus);
                        checkListItem.setPendingItem(pendingTasks);
                        checkListItem.setCompletedItem(completedTasks);

                        itemList.add(checkListItem);//adding string to arraylist
                    }

                    if(checkListArrayList.size() < iterationCount) {
                        iterationCount++;
                        String checkListId =
                                checkListArrayList.get(iterationCount).getCheckListId();
                        CheckList checkList1 = checkListArrayList.get(iterationCount);
                        checkList1.setCheckListItemArrayList(itemList);

                    }

                    mAdapter.notifyDataSetChanged();

                }
                else {
                    Toast.makeText(CheckListActivity.this, message, Toast.LENGTH_LONG).show();
                    //code after failed getting profile details goes here
                }
            } catch(JSONException je) {
                je.printStackTrace();
                Toast.makeText(CheckListActivity.this, je.getMessage(), Toast.LENGTH_LONG).show();
            }
        } //end of onPostExecute
    }



    public class GetCheckListAsyncTask extends AsyncTask<String, Void, JSONObject> {

        private String api;
        private JSONObject jsonParams;
        public GetCheckListAsyncTask(){}

        @Override
        protected JSONObject doInBackground(String... params) {
            try {
                api = getResources().getString(R.string.server_url) + "api/checklist/getChecklists.php";

                jsonParams = new JSONObject();
                String eventId = params[0];  // params[0] is username
                jsonParams.put("eventId", eventId);

                ServerRequest request = new ServerRequest(api, jsonParams);
                return request.sendRequest();
            } catch(JSONException je) {
                return Excpetion2JSON.getJSON(je);
            }
        }  //end of doInBackground

        @Override
        protected void onPostExecute(JSONObject response) {
            super.onPostExecute(response);
            //Log.e("ServerResponse", response.toString());
            try {
                int result = response.getInt("result");
                String message = response.getString("message");
                if (result == 1 ) {
                    Toast.makeText(CheckListActivity.this, message, Toast.LENGTH_LONG).show();
                    //code after getting profile details goes here

                    checkListArray = response.getJSONArray("checklists");

                    for (int i = 0; i < checkListArray.length(); i++) {
                        CheckList checkList = new CheckList();
                        JSONObject subObject = checkListArray.getJSONObject(i);
                        String checkListName = subObject.getString("checklist");//name of the attribute in response
                        String checkListBudget = subObject.getString("budget");//name of the attribute in response
                        String checkListIcon = subObject.getString("icon");
                        String checkListId = subObject.getString("checklistId");

                        checkList.setCheckListTitle(checkListName);
                        checkList.setBudget(checkListBudget);
                        checkList.setImageIcon(checkListIcon);
                        checkList.setCheckListId(checkListId);

                        checkListArrayList.add(checkList);

                        iterationCount++;
                        new GetCheckListsItemAsyncTask().execute(checkListId);

                        mAdapter.notifyDataSetChanged();
                    }

                    if ((progressDialog != null) && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                } else {
                    Toast.makeText(CheckListActivity.this, message, Toast.LENGTH_LONG).show();
                    //code after failed getting profile details goes here
                    if ((progressDialog != null) && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                }
            } catch(JSONException je) {
                je.printStackTrace();
                Toast.makeText(CheckListActivity.this, je.getMessage(), Toast.LENGTH_LONG).show();
            }
        } //end of onPostExecute
        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            progressDialog.setMessage("Loading...");
            progressDialog.show();
        }

    }
}

如何将 CheckListItemsArrayList 设置为 checkListArrayList 顺序的对象?请帮忙。谢谢。。

【问题讨论】:

    标签: java android arraylist android-asynctask


    【解决方案1】:

    您需要详细说明您的问题。这很混乱。

    但我认为您想将项目添加到 AsyncTask 类中。

    您可以为此使用构造方法

    GetCheckListAsyncTask getCheckListAsyncTask = new GetCheckListAsyncTask(checkListsItemArray);
            getCheckListAsyncTask.execute(mEventId);
    

    对于 AsyncTask 只需添加:

    JSONArray m_checkListsItemArray;
    
    public GetCheckListsItemAsyncTask(JSONArray checkListsItemArray){
           m_checkListsItemArray = checkListsItemArray; 
           //Do something here with checkListsItemArray;
    }
    

    并在 AsycTask 类的任何地方使用 m_checkListsItemArray。

    【讨论】:

    • 不,我想将 checkListItemArrays 设置为 checkListArrayList 的对象。@Saini
    • 对不起,我对你的概念有点困惑。
    • 你能简单解释一下吗?
    • 你在这里使用的变量名,比如checkListItemArrays,checkListArrayList的有点混乱..用简单的话告诉我你想让程序做什么。
    【解决方案2】:

    每次您开始一项任务时,您都无法控制它何时结束。这些任务是异步运行的,因此它们不会按照您启动它们的顺序结束。也许有一个字段级别的 Array 或 ArrayList,每次任务结束时都会添加结果,然后当一切都结束时,您可以使用数组结果。

    【讨论】:

    • 能否通过代码解释一下?这就是我试图做的。在迭代计数变量上创建并在 GeckCheckListAsyncTask 的 postExecute 方法中增加它。并尝试在 GetCheckListItemsAsyncTask 中访问它并在 checkList 的对象中设置 arraylist。但它抛出的索引超出范围异常。@usajnf
    • 哪一行生成索引越界异常?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 2015-12-13
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多