0

I have customized the code of EndlessAdapter in my app but one mistake done by me as this Endless Adapter always download data in the background instead it should download the same after user scroll downs the list and I unable to find the same mistake in our project. Due to this mistake my app sometimes returns OutOfMemoryException which is not acceptable.

Please suggest me any solution regarding the same.

Code: *MyEndlessAdapter:*

 class DemoAdapterCat extends EndlessAdapter {
              private RotateAnimation rotate=null;
              ArrayList<String> tempListNamesCat = new ArrayList<String>();
              ArrayList<String> tempListImagesCat = new ArrayList<String>();
              ArrayList<String> tempListYearCat1 = new ArrayList<String>();
              ArrayList<String> tempListYearCat2 = new ArrayList<String>();
              ArrayList<String> tempListmpgCat1 = new ArrayList<String>();
              ArrayList<String> tempListmpgCat2 = new ArrayList<String>();
              ArrayList<String> tempListpriceCat1 = new ArrayList<String>();
              ArrayList<String> tempListpriceCat2 = new ArrayList<String>();
              ArrayList<String> tempListRatingCat1 = new ArrayList<String>();
              ArrayList<String> tempListRatingCat2 = new ArrayList<String>();

              DemoAdapterCat() {
               super(new CategoryListLazyAdapter(ResearchList.this, countriesSubCat, imagesSubCat, YearSubCat1,YearSubCat2, mpgSubCat1,mpgSubCat2, priceSubCat1,priceSubCat2, ratingSubCat1, ratingSubCat2));
               Utility util = new Utility();
                util.setListViewHeightBasedOnChildren(lvCategory);
               rotate=new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
                 0.5f, Animation.RELATIVE_TO_SELF,
                 0.5f);
               rotate.setDuration(600);
               rotate.setRepeatMode(Animation.RESTART);
               rotate.setRepeatCount(Animation.INFINITE);
              }
            /* 
              @Override
            public int getCount()
              {
                  //return brandList.getDisplayNames().size();
                  return countriesSubCat.size();
              }*/
              @Override
              protected View getPendingView(ViewGroup parent) {
               row=getLayoutInflater().inflate(R.layout.categorylist, null);

               child=row.findViewById(R.id.tv_CategoryItem_Name);
               child.setVisibility(View.GONE);
               child = row.findViewById(R.id.tv_CategoryItem_MPG1);
               child.setVisibility(View.GONE);
               child = row.findViewById(R.id.tv_CategoryItem_MPG2);
               child.setVisibility(View.GONE);
               child = row.findViewById(R.id.tv_CategoryItem_Price1);
               child.setVisibility(View.GONE);
               child = row.findViewById(R.id.tv_CategoryItem_Price2);
               child.setVisibility(View.GONE);
               child = row.findViewById(R.id.tv_CategoryItem_Rating1);
               child.setVisibility(View.GONE);
               child = row.findViewById(R.id.tv_CategoryItem_Rating2);
               child.setVisibility(View.GONE);
               child = row.findViewById(R.id.tv_CategoryItem_Year1);
               child.setVisibility(View.GONE);
               child = row.findViewById(R.id.tv_CategoryItem_Year2);
               child.setVisibility(View.GONE);
               /*child = row.findViewById(R.id.img_CategoryItem);
               child.setVisibility(View.GONE);
               child = row.findViewById(R.id.img_CategoryItem_Arrow);
               child.setVisibility(View.GONE);*/

               /*child = row.findViewById(R.id.linear_main_MPG);
               child.setVisibility(View.GONE);*/
               child=row.findViewById(R.id.throbber);
               child.setVisibility(View.VISIBLE);
               child.startAnimation(rotate);

               return(row);
              }

              @Override
              protected boolean cacheInBackground() {

                    SystemClock.sleep(10000); 
               tempListNamesCat.clear();
               tempListImagesCat.clear();
               tempListmpgCat1.clear();
               tempListmpgCat2.clear();
               tempListpriceCat1.clear();
               tempListpriceCat2.clear();
               tempListYearCat1.clear();
               tempListYearCat2.clear();
               tempListRatingCat1.clear();
               tempListRatingCat2.clear();
               int lastOffset = getLastOffset();
               if(lastOffset < LIST_SIZE){
                int limit = lastOffset + BATCH_SIZE;
                for(int i=(lastOffset+1); (i<=limit && i<LIST_SIZE); i++){
                 tempListNamesCat.add(coll.getDisplayNames().get(i));
                 tempListImagesCat.add(coll.getImages().get(i));
                 tempListmpgCat1.add(coll.getMpg().get(i));
                 tempListmpgCat2.add(coll.getMpg().get(i+1));
                 tempListpriceCat1.add(coll.getPrice().get(i));
                 tempListpriceCat2.add(coll.getPrice().get(i+1));
                 tempListRatingCat1.add(coll.getRating().get(i));
                 tempListRatingCat2.add(coll.getRating().get(i+1));
                 tempListYearCat1.add(coll.getYears().get(i));
                 tempListYearCat2.add(coll.getYears().get(i+1));
                }    
                setLastOffset(limit);

                if(limit<LIST_SIZE){
                 //return true;
                    return(getWrappedAdapter().getCount()<coll.getDisplayNames().size());
                } else {
                 return false;
                }
               } else  {
                return false;
               }
              }


              @Override
              protected void appendCachedData() {

               @SuppressWarnings("unchecked")
               //Activity activity = this;
               //ArrayAdapter<String> arrAdapterNew = (ArrayAdapter<String>)getWrappedAdapter();
             CategoryListLazyAdapter arrAdapterNewCategory = (CategoryListLazyAdapter)getWrappedAdapter();
               //int listLen = tempList.size();
              // int listLen = tempListNames.size();
              countriesSubCat.addAll(tempListNamesCat);
              imagesSubCat.addAll(tempListImagesCat);
              mpgSubCat1.addAll(tempListmpgCat1);
              mpgSubCat2.addAll(tempListmpgCat2);
              priceSubCat1.addAll(tempListpriceCat1);
              priceSubCat2.addAll(tempListpriceCat2);
              ratingSubCat1.addAll(tempListRatingCat1);
              ratingSubCat2.addAll(tempListRatingCat2);
              YearSubCat1.addAll(tempListYearCat1);
              YearSubCat2.addAll(tempListYearCat2);
              arrAdapterNewCategory.notifyDataSetChanged();
              Utility util = new Utility();
              util.setListViewHeightBasedOnChildren(lvCategory);
              /* for(int i=0; i<listLen; i++){
              //  arrAdapterNew.add(tempList.get(i));
               }*/
              }
             }

Set Demoadapter to the list:

public void setValuesInCategoryChildSortByAZ(String url,final String filter, final String from, final String to)
    {
        if(isOnline())
        {
            final ProgressDialog dialog = ProgressDialog.show(
                    ResearchList.this, "Research List       ",
                    "Please wait...   ", true);

            final Handler handler = new Handler() {

                public void handleMessage(Message msg) {

                    // System.out.println("The id after Save:"+id.get(0).toString());

                    // catagory.addAll(keyword_vector1);
                    linear_Category_Child.setVisibility(View.GONE);
                    linear_Category_Child_Child.setVisibility(View.VISIBLE);
                    //tv_Child_Header.setText("Volvo");
                    /*adapter = new CategoryListLazyAdapter(
                            ResearchList.this);
                    lvCategory.setAdapter(adapter);*/
                    demoAdapterCat.notifyDataSetChanged();
                    Utility util = new Utility();
                    util.setListViewHeightBasedOnChildren(lvCategory);
                    dialog.dismiss();
                }
            };

            final Thread checkUpdate = new Thread() {

                public void run() {
                    try {
                        String sortEncode = URLEncoder.encode("alpha");
                        String filterEncode = URLEncoder.encode(filter);
                        String clientEncode = URLEncoder.encode("10030812");
                        String fromEncode = URLEncoder.encode(from);
                        String toEncode = URLEncoder.encode(to);
                        String catUrl = "/v1/vehicles/get-make-models.json?sort="+sortEncode+"&filter="+filterEncode+"&client-id="+clientEncode+"&from="+fromEncode;
                        genSig = new GetSignature(catUrl, "acura");
                        try {
                            signature = genSig.getUrlFromString();
                        } catch (InvalidKeyException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        } catch (NoSuchAlgorithmException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                        // jsonString =
                        // getJsonSring("http://api.highgearmedia.com/v1/vehicles/get-models.json?make=acura&client-id=10030812&signature=LWQbdAlJVxlXZ1VO2mfqAA==");
                        //String signatureEncode = URLEncoder.encode(signature);
                        String urlEncode = URLEncoder.encode(catUrl+"&signature="+signature);
                        jsonString = getJsonSring("http://apibeta.highgearmedia.com"+catUrl+"&signature="+signature);
                        System.out.println("The json category:===>"+jsonString);
                    } catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (URISyntaxException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    JsonParse json = new JsonParse(jsonString);
                    json.parseCat();
                    handler.sendEmptyMessage(0);

                }

            };
            checkUpdate.start();
        }else
        {
            AlertDialog.Builder builder = new Builder(ResearchList.this);
            builder.setTitle("Attention!");
            builder.setMessage("Network Connection unavailable.");
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {


                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                }
            });


            builder.create().show();
        }

    }

Thanks in advance.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
Sanat Pandey
  • 4,081
  • 17
  • 75
  • 132

1 Answers1

0

I unable to find the same mistake in our project

The EndlessAdapter sample app is here: https://github.com/commonsguy/cwac-endless/tree/master/demo.

If you look at that sample app, you will notice that it does not fork any threads.

If you read the EndlessAdapter documentation, you will see:

Your EndlessAdapter subclass also needs to implement cacheInBackground(). This method will be called from a background thread, and it needs to download more data that will eventually be added to the ListAdapter you used in the constructor. While the demo application simply sleeps for 10 seconds, a real application might make a Web service call or otherwise load in more data.

Since this method is called on a background thread, you do not need to fork your own thread. However, at the same time, do not try to update the UI directly.

So, change your project to not fork your own thread, but instead do your work in cacheInBackground() to retrieve and add the next batch of data.

If that approach does not fit the way your app needs to run, that is fine, but you may have difficulty in using EndlessAdapter.

Community
  • 1
  • 1
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • But there is no any UI thread updation in CacheInBackground of Endlessadapter, there are only Arraylist adding lines are written which will be going to add in the list. So please tell me briefly where I am going wrong in my code. and What should be the solution for the same. – Sanat Pandey Jun 15 '12 at 01:01
  • @SanatPandey: "But there is no any UI thread updation in CacheInBackground of Endlessadapter" -- correct. You hold onto the data and use it in `appendCachedData()`, as is very clearly described in the README for this component. " So please tell me briefly where I am going wrong in my code" -- I have no idea, other than that you are not using `EndlessAdapter` correctly. Getting rid of the `Thread.sleep()` in `cacheInBackground()` would be a starting point. – CommonsWare Jun 15 '12 at 09:47
  • I think I found the problem in my project. There is no problem with endlessadapter, problem is that The CacheInBackground and AppendCachedData Method always running in background because In real endlessadapter when we scroll the list till the end of the screen then it shows a progressbar to show the next data, but in my case it doesn't find the end of the screen or list therefore it always running in background with progress bar. So can u tell me that how endlessadapter detect that the end of screen or list comes? – Sanat Pandey Jun 15 '12 at 18:15
  • @SanatPandey: "So can u tell me that how endlessadapter detect that the end of screen or list comes?" -- `EndlessAdapter` will detect the end of the list based upon the user scrolling to the bottom and displaying the pending view. – CommonsWare Jun 15 '12 at 19:39
  • "EndlessAdapter will detect the end of the list based upon the user scrolling to the bottom"-- how we detect the same? please help me out? – Sanat Pandey Jun 15 '12 at 23:57