异步任务中的doinbackground()无法正常工作 [英] doinbackground() in async task not working properly

查看:78
本文介绍了异步任务中的doinbackground()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从API中获取一些数据,并将每个项目显示为RecyclerViewPager slide.因此,我在onScrollListener内部做了一个async task来检查滚动操作,并且当用户滑动5个项目时asynctask获取第2页的项目,并且在doInBackGround函数中,数据将添加到数组和数组中将被添加到recycler view pager.

I am fetching some data from API and presenting each item as a RecyclerViewPager slide. So, I have made an async task inside onScrollListener to check scroll actions and when the user slides 5 items asynctask fetches the Items of page 2 and in the doInBackGround function the data will be added to the array and array will be added to the recycler view pager.

一切正常,但我需要在5张幻灯片上停止滚动几秒钟(至少5秒钟),否则recyclerView不会显示第二页幻灯片.

Everything works fine but I need to stop scrolling at 5 slide for a few seconds(Minimum 5 sec) or else the recyclerView won't show the 2nd page slides.

如何解决此问题.这是我用于onScrollListenerasyncTask函数的代码.

How to solve this problem. This is the code I am using for the onScrollListener and asyncTask functions.

代码:

 private void initRecycler(){

       final RecyclerViewPager mRecyclerView = (RecyclerViewPager) findViewById(R.id.list);

// setLayoutManager like normal RecyclerView, you do not need to change any thing.
       final LinearLayoutManager layout = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
       mRecyclerView.setLayoutManager(layout);

//set adapter
//You just need to implement ViewPageAdapter by yourself like a normal RecyclerView.Adpater.
       RecyclerViewAdapter adapter = new RecyclerViewAdapter(ImageUrls, ImageNames, ImageDesc, this);
       mRecyclerView.setAdapter(adapter);

       mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

           @Override
           public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
               super.onScrolled(recyclerView, dx, dy);

              visibleItemCount = layout.getChildCount();
              totalItemCount = layout.getItemCount();
               firstVisibleItem = layout.findFirstVisibleItemPosition();
//               int aaa = totalItemCount - visibleItemCount;
//               int bbb = firstVisibleItem + visibleThreshold;
//               Log.d("tag" ,"totalItemCount : " + totalItemCount + "|  visibleItemCount : " + visibleItemCount);
              Log.d("tag" ,"totalItemCount : " + totalItemCount + "|  previousTotal : " + previousTotal);
               Log.d("tag", "firstVisibleItem :" + firstVisibleItem + " | totalItemCount :" + totalItemCount);
               if (loading) {
                   if (totalItemCount > previousTotal) {
                       loading = false;
                       previousTotal = totalItemCount;
                   }
               }
               if (!loading && (firstVisibleItem + 5)
                       == (totalItemCount)) {

                   Log.i("Ya!", "end called");
                   page += 1;
                   String url = "http://url.in/wp-json/wp/v2/posts?page="+page+"&_embed";
                   Log.d( url ,": ");
                   // Do something
                   final OkHttpClient client2 = new OkHttpClient();
                   final Request request2 = new Request.Builder()
                           .url(url)
                           .build();
                   @SuppressLint("StaticFieldLeak") AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
                       private static final String TAG = "SlideFragment";

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

                           try {

                               Response response2 = client2.newCall(request2).execute();

                               if (!response2.isSuccessful()) {
                                   Log.d(TAG, "doInBackground: REsponse Un Successfull - 56");
                                   response2.body().close();
                                   return null;

                               }
                               String Data2 =  response2.body().string();
                               response2.body().close();
                               return Data2;
                           } catch (Exception e) {
                               e.printStackTrace();
                               Log.d(TAG, "doInBackground: Exceptione on line63");
                               return null;
                           }

                       }

                       @Override
                       protected void onPostExecute(String Data2) {

                           super.onPostExecute(Data2);
                           if (Data2 != null) {
                               Log.d(TAG, "onPostExecute: 188 LINE");
                               try {
                                   JSONArray json = new JSONArray(Data2);
                                   for (int i = 0; i < json.length(); i++) {
                                       JSONObject post = json.getJSONObject(i);
                                       String title = post.getJSONObject("title").getString("rendered");
                                       String description = post.getJSONObject("excerpt").getString("rendered");
                                       String imgURL = post.getJSONObject("_embedded").getJSONArray("wp:featuredmedia").getJSONObject(0).getJSONObject("media_details").getString("file");
                                       String imagUrl = "http://url.in/wp-content/uploads/" + imgURL;
                                       ImageNames.add(title);
                                       ImageDesc.add(description);
                                       ImageUrls.add(imagUrl);
                                       Log.d(TAG, "onPostExecute: arrayList Created" );
                                   }


                               }catch(JSONException j){
                                   j.printStackTrace();
                                   Log.d(TAG, "onPostExecute: on line 121");
                               }
                           }
                       }
                   };
                   asyncTask.execute();
                   loading = true;
               }
           }
       });

   }
}

推荐答案

我猜您应该在再次发出请求之前手动取消任务,因为一个任务只能根据文档中给出的规则执行一次.

I guess you should cancel task manually before making another request, as one task can only be executed once according to rules given in the documentation

这篇关于异步任务中的doinbackground()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆