2012-06-13 2 views
0

내 앱에서 EndlessAdapter 코드를 사용자 정의했으나이 끝없는 어댑터는 항상 백그라운드에서 데이터를 다운로드하기 때문에 사용자가 실수로 한 실수는 사용자가 스크롤 다운 한 후에도 동일하게 다운로드해야합니다 우리 프로젝트에서 같은 실수를 발견하지 못했습니다. 이 실수로 인해 내 응용 프로그램이 OutOfMemoryException을 반환하는 경우가 있습니다.끝없는 어댑터가 항상 백그라운드에서 데이터를 다운로드하기 위해 실행 중입니다

동일한 해결책을 제안 해주십시오.

코드 : * 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)); 
       }*/ 
       } 
      } 

설정 Demoadapter : 사전에

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(); 
     } 

    } 

감사합니다.

답변

0

나는 우리의 프로젝트

EndlessAdapter 샘플 응용 프로그램에서 같은 실수를 찾을 수 없습니다 여기에 있습니다 : https://github.com/commonsguy/cwac-endless/tree/master/demo.

샘플 앱을 보면 어떤 스레드도 포크하지 않는다는 것을 알 수 있습니다.

당신이 the EndlessAdapter documentation을 읽는다면

, 당신은 볼 수 있습니다 :

귀하의 EndlessAdapter 서브 클래스는() cacheInBackground를 구현해야합니다. 이 메서드는 백그라운드 스레드에서 호출되며 생성자에서 사용한 ListAdapter에 결국 추가되는 데이터를 더 다운로드해야합니다. 데모 응용 프로그램이 10 초 동안 잠자는 동안 실제 응용 프로그램은 웹 서비스 호출을하거나 그렇지 않으면 더 많은 데이터를로드 할 수 있습니다.

이 메서드는 백그라운드 스레드에서 호출되므로 사용자 스레드를 포크 할 필요가 없습니다. 그러나 동시에 UI를 직접 업데이트하지 마십시오.

따라서 프로젝트를 변경하여 자신의 스레드를 포크하지 말고 cacheInBackground()에서 작업하여 다음 데이터 배치를 검색하고 추가하십시오.

이 방법이 앱 실행 방식에 맞지 않는 경우라면 괜찮습니다. 그러나 EndlessAdapter을 사용하는 데 어려움이있을 수 있습니다.

+0

Endlessadapter의 CacheInBackground에는 UI 스레드 업데이트가 없으며 목록에 추가 할 Arraylist 추가 행만 있습니다. 그러므로 제 코드에서 어디서 잘못 될지 간단히 말해주십시오. 그리고 같은 것을위한 해결책이되어야합니다. –

+0

@SanatPandey : "그러나 Endlessadapter의 CacheInBackground에는 UI 스레드 업데이트가 없습니다."- 정확합니다. 이 컴포넌트의 README에 매우 명확하게 설명되어있는 것처럼, 데이터를 잡고 'appendCachedData()'에서 사용한다. "내 코드에서 어디서 잘못 될지 간단히 말해주세요."- 나는 당신이'EndlessAdapter'를 올바르게 사용하고 있다는 것을 제외하고는 전혀 모른다. 'cacheInBackground()'에서'Thread.sleep()'을 제거하는 것은 출발점이 될 것입니다. – CommonsWare

+0

내 프로젝트에서 문제가 발견 된 것 같습니다.endlessadapter에는 아무런 문제가 없습니다. 문제는 CacheInBackground와 AppendCachedData 메소드가 항상 백그라운드에서 실행되기 때문입니다. 왜냐하면 실제 endlessadapter에서는 화면 끝까지 목록을 스크롤 할 때 다음 데이터를 표시하는 progressbar를 표시하지만 내 경우에는 따라서 화면이나 목록의 끝을 찾지 못하므로 항상 진행률 표시 줄과 함께 백그라운드에서 실행됩니다. 그래서 endlessadapter가 화면이나 목록의 끝이 어떻게 감지되는지 말해 줄 수 있습니까? –

관련 문제