问题
i want to create infinie GridView, and when i scroll, if in onScroll method not add
adapter = new ImageAdapter();
grid.setAdapter(adapter);
my app crashes with LogCat:
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.class
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
}
}
else my app work but when i scroll to end grid view refresh and lost position and i need again scroll to my last position, how fix this problem?
回答1:
Try to check this condition :
if(str.size() > 0 && position < str.size()){
loader.displayImage(str.get(position), image, options);
}
Instead of
if(str.size() > 0){
loader.displayImage(str.get(position), image, options);
}
Hope it helps you.
Thanks.
来源:https://stackoverflow.com/questions/13945941/android-dynamic-gridview