android - 在 AsyncTask 中获取 IndexOutOfBoundException

标签 android arraylist android-asynctask position indexoutofboundsexception

我有一类CheckList。它有 checkListIdtitle 和一个 CheckListItemArrayList

我有 2 个异步任务。一个用于 GetCheckLists,另一个用于 GetCheckListItems。在CheckList类中,它有checkListIdTitlecheckListItemsarrayList

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

现在 GetCheckListItemsAsyncTaskonPostExecute 方法我想将 checkListItemArrayList 设置为 CheckList 的对象。

检查列表 Activity :

public class CheckListActivity extends AppCompatActivity implements CheckListAdapter.OnItemClickListener{

    public int iterationCount = 0;

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

        mIntent = getIntent();

        checkListArrayList = new ArrayList<>();

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

    }

    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

                        checkListItem.setTitle(checkListItemName);
                        checkListItem.setBudget(checkListItemBudget);

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

                    CheckList checkList = new CheckList();

                    for(int i = 0; i <= iterationCount; i++ ) {

                        String checkListId = checkListArrayList.get(iterationCount).getCheckListId();

                        checkListArrayList.get(iterationCount).setCheckListItemArrayList(itemList);
                    }

                    mAdapter.notifyDataSetChanged();

                }
                else {

                    //code after failed getting profile details goes here
                }
            } catch(JSONException je) {
            }
        } //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

                        checkList.setCheckListTitle(checkListName);
                        checkList.setBudget(checkListBudget);

                        checkListArrayList.add(checkList);

                         if(checkListArrayList.size() > iterationCount) {

                            String checkListId1 = checkListArrayList.get(iterationCount).getCheckListId();
                            new GetCheckListsItemAsyncTask().execute(checkListId1);

                            iterationCount ++;
                        }

                        mAdapter.notifyDataSetChanged();

                    }
                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) {
            }
        } //end of onPostExecute

    }
}

为了获得 checkListArrayList 的位置,我创建了一个迭代计数变量并在 GeckCheckListAsyncTaskpostExecute 方法中增加了它。并尝试在 GetCheckListItemsAsyncTask 中访问它,并在 checkList 的对象中设置数组列表。

但如果 for 循环 GetCheckListItemAsyncTask,它会抛出索引超出绑定(bind)异常。我应该如何获取 checkListArray 的索引以将 CheckListItemArray 设置到与 checkListArrayList 相同的位置?

日志:

Process: com.example.siddhi.meavita, PID: 20503
    java.lang.IndexOutOfBoundsException: Invalid index 5, size is 5
    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
    at java.util.ArrayList.get(ArrayList.java:308)
    at com.example.siddhi.meavita.Activities.CheckListActivity$GetCheckListsItemAsyncTask.onPostExecute(CheckListActivity.java:336)
    at com.example.siddhi.meavita.Activities.CheckListActivity$GetCheckListsItemAsyncTask.onPostExecute(CheckListActivity.java:261)

最佳答案

更改为:

for(int i = 0; i < iterationCount; i++ ) {

    String checkListId = checkListArrayList.get(i).getCheckListId();
    checkListArrayList.get(i).setCheckListItemArrayList(itemList);
}

您正在从 0 迭代 iiterationCount。但是,在循环内部,您始终使用 iterationCount 而不是 i

关于android - 在 AsyncTask 中获取 IndexOutOfBoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38211330/

相关文章:

java - Android-Jacoco代码覆盖率忽略了Robolectric测试

android - 将公共(public)属性和方法暴露给主 Activity 中的 fragment 是否是一种不好的形式?

java - 如何实现ListIterator?

php - 如何将 BackgroundWorker 的结果设置为 TextView

android - 如何将 View 设置为 TabSpec 的内容?

java - 应用程序崩溃并出现 java.lang.RuntimeException : Unable to start activity ComponentInfo error

java - 对象的Arraylist查找所有不同属性的对象

Java,通过arraylist调用对象方法

java - AsyncTask 接口(interface)中的 NullPointerException

android - 正确使用 AsyncTask get()