如何等到OnRefreshListener()中的方法完成?

时间:2018-08-20 17:28:21

标签: android android-recyclerview android-volley swiperefreshlayout

我正在尝试使用Volley,recycleView和SwipeRefreshLayout进行示例,如下代码所示。我现在面临的问题是,当我向下滑动时,出现SwipeRefresh图标,并且日志记录器显示以下结果:

W/ActMain: POST.Runnable_1
W/ActMain: <fetchJSONObjectRequest.....>
D/ActMain: <fetchJSONObjectRequest> mProductsList.size: 0

由于mProductsList.size = 0,这意味着方法fetchJSONObjectRequest()不会等到http请求完成以获取json数据对象。我打算做的是,当我向下滑动时,应获取JSON数据对象,并应填充recycleView。

我如何找出为什么在滑动布局时不等到fetchJSONObjectRequest()完成?我应该使用AsyncTask吗?

代码

this.mSwipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
 @Override
        public void onRefresh() {
            TextView tv = (TextView) findViewById(R.id.actMainTextViewTest);
            tv.setText("REFRESHED");
            mRecycleView = (RecyclerView) findViewById(R.id.actMainRecyclerView);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            mRecycleView.setLayoutManager(linearLayoutManager);
            this.mSwipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            TextView tv = (TextView) findViewById(R.id.actMainTextViewTest);
            tv.setText("REFRESHED");
            mRecycleView = (RecyclerView) findViewById(R.id.actMainRecyclerView);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            mRecycleView.setLayoutManager(linearLayoutManager);
            new FetchJSONAsync().execute();
        }
    });
        }
        }

        private class FetchJSONAsync extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mSwipeToRefresh.setRefreshing(true);
    }

    @Override
    protected Void doInBackground(Void... params) {
        fetchJSONObjectRequest();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        mSwipeToRefresh.setRefreshing(false);
        Log.d(TAG, "onPostExecute: mProductsList.size(): " + mProductsList.size());
    }
}

fetchJSONObjectRequest

 private List<Products> fetchJSONObjectRequest() {
    Log.w(TAG, "<fetchJSONObjectRequest.....>");
    this.mJSONObjectRequest = new JsonObjectRequest(Request.Method.GET, this.BASE_URL, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.w(TAG, "<onResponse> response: " + response);
            Iterator<String> JSONObjectKeys = response.keys();
            String key = null;
            try {
                while (JSONObjectKeys.hasNext()) {
                    key = JSONObjectKeys.next();
                    Log.d(TAG, "<onResponse> key: " + key);
                    if (key.equals(NAME_JSON_ARRAY_PRODUCTS) && getTypeOfJSONObjectForKey(response.get(key)).equals(TYPE_JSON_ARRAY)) {
                        this.parseDataFromJSONArray(response.getJSONArray(key));
                        break;
                    }
                }
                this.assignEntriesToModel();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            mSwipeToRefresh.setRefreshing(false);
        }

        private void assignEntriesToModel() {
            Log.w(TAG, "<assignEntriesToModel>");
            for (int i = 0; i < mJSONObjectEntriesList.size(); i++) {
                String name = String.valueOf(mJSONObjectEntriesList.get(i)[0]);
                Long releaseDate = Long.valueOf(mJSONObjectEntriesList.get(i)[1].toString());
                Boolean isAvailable = Boolean.valueOf(mJSONObjectEntriesList.get(i)[2].toString());
                String description = String.valueOf(mJSONObjectEntriesList.get(i)[3]);
                String imageURL = String.valueOf(mJSONObjectEntriesList.get(i)[4]);
                JSONObject price = (JSONObject) mJSONObjectEntriesList.get(i)[5];
                Float priceValue = Float.valueOf(mJSONObjectEntriesList.get(i)[6].toString());
                String priceCurrency = String.valueOf(mJSONObjectEntriesList.get(i)[7]);
                String rating = String.valueOf(mJSONObjectEntriesList.get(i)[8]);

                mProductsList.add(new Products(name, releaseDate, isAvailable, description, imageURL, priceValue,
                        priceCurrency, rating));
            }
            Log.d(TAG, "mProductsList.size: " + mProductsList.size());
        }

        private void parseDataFromJSONArray(JSONArray jsonArray) throws JSONException {
            Log.w(TAG, "<parseDataFromJSONArray> jsonArray: " + jsonArray);
            for (int i = 0; i < jsonArray.length(); i++) {
                Log.d(TAG, "+++++++++++++++++++++++++++++++++++Beginning Of Iteration " + i + " +++++++++++++++++++++++++++++++++++++++++++");
                jsonObject = this.getObjectsFromJSONArrayForIndex(jsonArray, i);
                mJSONObjectEntriesList.add(this.getEntriesFromJSONObject(jsonObject));
                Log.d(TAG, "number of entries in list: " + mJSONObjectEntriesList.size());
                Log.d(TAG, "+++++++++++++++++++++++++++++++++++Eno Of Iteration " + i + "+++++++++++++++++++++++++++++++++++++++++++");
            }
        }

        private Object[] getEntriesFromJSONObject(JSONObject jsonObject) throws JSONException {
            Object[] jsonObjectsArray = new Object[9];
            namePropertyValue = jsonObject.get(JSON_PROP_IN_ARRAY_NAME);
            releaseDatePropertyValue = jsonObject.get(JSON_PROP_IN_ARRAY_RELEASE_DATE);
            availablePropertyValue = jsonObject.get(JSON_PROP_IN_ARRAY_AVAILABLE);
            descriptionPropertyValue = jsonObject.get(JSON_PROP_IN_ARRAY_DESCR);
            imageURLPropertyValue = jsonObject.get(JSON_PROP_IN_ARRAY_IMAGE_URL);
            pricePropertyValue = jsonObject.get(JSON_PROP_IN_ARRAY_PRICE);
            valuePropertyValue = jsonObject.getJSONObject(JSON_PROP_IN_ARRAY_PRICE).get(JSON_PROP_IN_ARRAY_PRICE_OBJ_VALUE);
            currencyPropertyValue = jsonObject.getJSONObject(JSON_PROP_IN_ARRAY_PRICE).get(JSON_PROP_IN_ARRAY_PRICE_OBJ_CURRENCY);
            ratingPropertyValue = jsonObject.get(JSON_PROP_IN_ARRAY_RATING);

            jsonObjectsArray[0] = namePropertyValue;
            jsonObjectsArray[1] = releaseDatePropertyValue;
            jsonObjectsArray[2] = availablePropertyValue;
            jsonObjectsArray[3] = descriptionPropertyValue;
            jsonObjectsArray[4] = imageURLPropertyValue;
            jsonObjectsArray[5] = pricePropertyValue;
            jsonObjectsArray[6] = valuePropertyValue;
            jsonObjectsArray[7] = currencyPropertyValue;
            jsonObjectsArray[8] = ratingPropertyValue;

            Log.v(TAG, "<getEntriesFromJSONObject> name: " + namePropertyValue);
            Log.v(TAG, "<getEntriesFromJSONObject> releaseDate: " + releaseDatePropertyValue);
            Log.v(TAG, "<getEntriesFromJSONObject> available: " + availablePropertyValue);
            Log.v(TAG, "<getEntriesFromJSONObject> description: " + descriptionPropertyValue);
            Log.v(TAG, "<getEntriesFromJSONObject> imageURL: " + imageURLPropertyValue);
            Log.v(TAG, "<getEntriesFromJSONObject> price: " + pricePropertyValue);
            Log.v(TAG, "<getEntriesFromJSONObject> value: " + valuePropertyValue);
            Log.v(TAG, "<getEntriesFromJSONObject> currency: " + currencyPropertyValue);
            Log.v(TAG, "<getEntriesFromJSONObject> rating: " + ratingPropertyValue);
            return jsonObjectsArray;
        }

        private JSONObject getObjectsFromJSONArrayForIndex(JSONArray jsonArray, int index) throws JSONException {
            return jsonArray.getJSONObject(index);
        }

        private String getTypeOfJSONObjectForKey(Object data) throws JSONException {
            Object json = new JSONTokener(data.toString()).nextValue();
            if (json instanceof JSONArray) {
                Log.d(TAG, "<getTypeOfJSONObjectForKey> JSON_TYPE: " + TYPE_JSON_ARRAY);
                return TYPE_JSON_ARRAY;
            } else {
                Log.i(TAG, "<getTypeOfJSONObjectForKey> JSON_TYPE: " + TYPE_JSON_ARRAY);
                return TYPE_JSON_OBJECT;
            }
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mSwipeToRefresh.setRefreshing(false);
        }
    });
    Log.d(TAG, "<fetchJSONObjectRequest> mProductsList.size: " + mProductsList.size());
    this.mRequestQueue.add(this.mJSONObjectRequest);
    return mProductsList;
}

1 个答案:

答案 0 :(得分:0)

您必须实现回调接口,我已经在此处Android kotlin - get simple string from url给出了示例代码