While learning I try to build a simple app which shows some images from a folder in a scrollview.
However my app crashes on the second click of this item in a row. removeAllViews() in the onOptionsItemSelected() did help to prevent the crash if another item is clicked in between.
I did read and try alot, without any success. Can someone point me in the right direction?
Here is the Code.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
LinearLayout myLinearLayout = (LinearLayout) findViewById(R.id.myLinearLayout);
myLinearLayout.removeAllViews(); //Does help if whatever item is clicked in between.
switch (id) {
case R.id.action_whatever:
...
return true;
case R.id.action_showScrollview:
File tumbDir = new File(Environment.getExternalStorageDirectory() + "/tumbs");
File[] allTumbs = tumbDir.listFiles();
for(File tumb : allTumbs){
ImageView myImageView = new ImageView(getApplicationContext());
Bitmap tumbToShow = BitmapFactory.decodeFile(tumb.getAbsolutePath());
myImageView.setImageBitmap(tumbToShow);
myLinearLayout.addView(myImageView); //This line causes crash on second click of the showScrollview item in a row
}
return true;
default:
return super.onOptionsItemSelected(item);
}
edit:
I did now use a workaround to ensure removeAllViews()is performed before the method to add images is called a second time in a row.
These lines remain in onOptionsImtemSelected() of my options menu:
LinearLayout myLinearLayout = (LinearLayout) findViewById(R.id.myLinearLayout);
myLinearLayout.removeAllViews();
These lines in the menu item:
if (clickedTwice) clickedTwice=false;
else clickedTwice = showMyScrollView();
The method with return value true:
private boolean showMyScrollView() {
File tumbDir = new File(Environment.getExternalStorageDirectory() + "/tumbs");
File[] allTumbs = tumbDir.listFiles();
for (File tumb : allTumbs){
ImageView myImageView = new ImageView(this);
Bitmap tumbToShow = BitmapFactory.decodeFile(tumb.getAbsolutePath());
myImageView.setImageBitmap(tumbToShow);
myLinearLayout.addView(myImageView);
}
return true;
}
Now of course every second click of the menu item results in a blank screen, cause the views are removed. On the third click images are added again without trouble.
So i would assume the problem is removeAllViews() is not performed reliably before the following code is processed. Maybe something similar as described her: Calling removeAllViews(); still results in IllegalStateException:You must call removeView() on the child's parent first