2012-12-19 54 views
1

我想創建infinie GridView控件,當我滾動,如果onScroll方法不 logcat中添加的Android動態的GridView

adapter = new ImageAdapter(); 
      grid.setAdapter(adapter); 

我的應用程序崩潰:

FATAL EXCEPTION: main 
java.lang.IndexOutOfBoundsException: Invalid index 46, size is 46 
    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251) 
    at java.util.ArrayList.get(ArrayList.java:304) 
    at com.example.tectob6iu.MainActivity$ImageAdapter.getView(MainActivity.java:98) 
    at android.widget.AbsListView.obtainView(AbsListView.java:2143) 
    at android.widget.GridView.makeAndAddView(GridView.java:1341) 
    at android.widget.GridView.makeRow(GridView.java:341) 
    at android.widget.GridView.fillDown(GridView.java:283) 
    at android.widget.GridView.fillGap(GridView.java:243) 
    at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4930) 
    at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:4087) 
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749) 
    at android.view.Choreographer.doCallbacks(Choreographer.java:562) 
    at android.view.Choreographer.doFrame(Choreographer.java:531) 
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735) 
    at android.os.Handler.handleCallback(Handler.java:725) 
    at android.os.Handler.dispatchMessage(Handler.java:92) 
    at android.os.Looper.loop(Looper.java:137) 
    at android.app.ActivityThread.main(ActivityThread.java:5191) 
    at java.lang.reflect.Method.invokeNative(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:511) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562) 
    at dalvik.system.NativeStart.main(Native Method) 

MainActivity。類

public class MainActivity extends Activity implements OnScrollListener{ 
    private class ImageAdapter extends BaseAdapter { 
     private List<String> list; 
     private ImageLoader loader; 
     private DisplayImageOptions options; 


     public ImageAdapter() { 
      this(new ArrayList<String>()); 

      options = new DisplayImageOptions.Builder() 
      .cacheInMemory() 
      .cacheOnDisc() 
      .bitmapConfig(Bitmap.Config.RGB_565) 
      .displayer(new FadeInBitmapDisplayer(250)) 
      .build(); 

      loader = ImageLoader.getInstance(); 
      loader.init(ImageLoaderConfiguration.createDefault(MainActivity.this)); 
     } 

     public void clear() { 
      list.clear(); 
      notifyDataSetChanged(); 
     } 

     public void add(List<String> rows) { 
      list.addAll(rows); 
      notifyDataSetChanged(); 
     } 



     @Override 
     public int getCount() { 
      return list.size(); 
     } 

     @Override 
     public long getItemId(int position) { 
      return position; 
     } 

     @Override 
     public String getItem(int position) { 
      return list.get(position); 
     } 

     public View getView(int position, View view, ViewGroup container) { 
      if (view == null) { 
       view = getLayoutInflater().inflate(R.layout.grid_item, container, false); 
      } 

      ImageView image = (ImageView)view.findViewById(R.id.imageGrid); 
      // Bind row on your view here  97 
      //98 
      if(str.size() > 0){ 
        loader.displayImage(str.get(position), image, options); 
      } 
      else{ 
       image.setImageResource(R.drawable.ic_launcher); 
      } 
      return view; 
     } 

     public ImageAdapter(List<String> list) { 
      this.list = list; 
     } 
    } 

    class LoadTask extends AsyncTask<Void, Void, List<String>> { 

     private int page = 1; 

     public int addPage(int i){ 
      return page = i; 
     } 

     @Override 
     protected List<String> doInBackground(Void... params) { 

      InputStream ips = null; 
      JSONObject jsonObj = null; 
      String json = "";  
      try { 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       HttpResponse response = httpClient.execute(new HttpPost("http://iapp.gazeta.uz/fotolenta?page="+page)); 
       ips = response.getEntity().getContent(); 
      } catch (ClientProtocolException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

      try { 
       BufferedReader bufff = new BufferedReader(new InputStreamReader(ips, "UTF-8")); 
       StringBuilder sb = new StringBuilder(); 
       String line = null; 

       while ((line = bufff.readLine()) != null){ 
        sb.append(line + "\n");     
       } 
       ips.close(); 
       json = sb.toString();  
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

      try { 
       jsonObj = new JSONObject(json); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      JSONArray array = null; 
      array = jsonObj.optJSONArray("img_list"); 


       for (int i = 0; i < array.length(); i++) { 
        str.add(array.optJSONObject(i).optString("thumbnail"));    
       } 
      return str; 
     } 

     @Override 
     protected void onPostExecute(List<String> result) { 
      adapter.add(result); 
     } 
    } 

    ArrayList<String> str = new ArrayList<String>(); 

    private GridView grid; 
    private ImageAdapter adapter; 
    private int page; 

    private int mVisibleThreshold = 5; 
    private int mCurrentPage = 0; 
    private int mPreviousTotal = 0; 
    private boolean mLoading = true; 
    private boolean mLastPage = false; 

    public void refresh(int i){ 
     LoadTask task = new LoadTask(); 
     task.addPage(i); 
     task.execute(); 
    } 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     page = 1; 
     refresh(page);  

     setContentView(R.layout.main); 
     grid = (GridView) findViewById(R.id.grid); 

     adapter = new ImageAdapter(); 
     grid.setAdapter(adapter); 

     grid.setOnScrollListener(this); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu){ 

     getMenuInflater().inflate(R.menu.activity_main, menu); 

     return super.onCreateOptionsMenu(menu); 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item){ 

     page ++; 
     refresh(page); 
     adapter = new ImageAdapter(); 
     grid.setAdapter(adapter); 

     return super.onOptionsItemSelected(item); 
    } 



    @Override 
    public void onScroll(AbsListView view, int firstVisibleItem, 
      int visibleItemCount, int totalItemCount) { 
     // TODO Auto-generated method stub 
     if (mLoading) { 
      if (totalItemCount > mPreviousTotal) { 

       mLoading = false; 
       mPreviousTotal = totalItemCount; 
       mCurrentPage++; 

       // Find your own condition in order to know when you 
       // have finished displaying all items 
       if (mCurrentPage + 1 > 50) { 
        mLastPage = true; 
       } 
      } 
     } 
     if (!mLastPage && !mLoading && 
       (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) { 
      page++; 
      refresh(page); 
      adapter = new ImageAdapter(); 
      grid.setAdapter(adapter); 

      mLoading = true; 
     } 
    } 

    @Override 
    public void onScrollStateChanged(AbsListView view, int scrollState) { 
     // TODO Auto-generated method stub 

    } 

} 

其他我的應用程序工作,但當我滾動到結束網格視圖刷新和丟失的位置,我需要再次滾動到我的最後一個位置,如何解決這個問題?

+0

檢查'list'的大小,它是46. –

+0

您在'MainActivity.java:Line No.98'上的哪條代碼行? –

+0

我在代碼 – 033uk

回答

1

嘗試檢查此條件:

if(str.size() > 0 && position < str.size()){ 
     loader.displayImage(str.get(position), image, options); 
} 

而不是

if(str.size() > 0){ 
     loader.displayImage(str.get(position), image, options); 
} 

希望它可以幫助你。

謝謝。

+0

這是工作,但圖像沒有加載,如何解決這個問題? – 033uk

+0

您是否刪除了'else'部分?不要刪除,只是改變'如果'條件而已。 –

+0

YAHOOO謝謝你的大謝意=)) – 033uk