Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent activity to reload when acessing contextual action menu by clicking on a image in async gridview

I have a bunch of images from sdcard that are load asynchronously on a gridview. Everything works fine, but when accessing a multi select contextual action menu by long clicking in any image the entire activity reloads and all images are loaded again. How to prevent it?

Myadapter

public class PhotosGridViewImageAdapter extends BaseAdapter {

AsyncTaskLoadFiles myAsyncTaskLoadFiles;

public class AsyncTaskLoadFiles extends AsyncTask<Void, String, Void> {

    File targetDirector;
    PhotosGridViewImageAdapter myTaskAdapter;

    public AsyncTaskLoadFiles(PhotosGridViewImageAdapter adapter) {
        myTaskAdapter = adapter;
    }

    @Override
    protected void onPreExecute() {
        String ExternalStorageDirectoryPath = Environment
                .getExternalStorageDirectory().getAbsolutePath();
        String targetPath = ExternalStorageDirectoryPath + File.separator + AppConstant.PHOTO_ALBUM + File.separator;
        targetDirector = new File(targetPath);
        myTaskAdapter.clear();

        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {
        File[] files = targetDirector.listFiles();
        Arrays.sort(files);
        for (File file : files) {
            publishProgress(file.getAbsolutePath());
            if (isCancelled()) break;
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        myTaskAdapter.add(values[0]);
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(Void result) {
        myTaskAdapter.notifyDataSetChanged();
        super.onPostExecute(result);
    }

}

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

void add(String path) {
    itemList.add(path);
}

void clear() {
    itemList.clear();
}

void remove(int index){
    itemList.remove(index);
}

private Activity _activity;
private ArrayList<String> _filePaths = new ArrayList<String>();
private int imageWidth;

public PhotosGridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
        int imageWidth) {
    this._activity = activity;
    this._filePaths = filePaths;
    this.imageWidth = imageWidth;
}

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

@Override
public Object getItem(int position) {
    return this._filePaths.get(position);
}

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

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    final ImageView imageView;
    if (convertView == null) {
        imageView = new ImageView(_activity);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
                imageWidth));

        convertView = imageView;

        holder = new ViewHolder();
        holder.image = imageView;
        holder.position = position;
        convertView.setTag(holder);
    } else {
        //imageView = (ImageView) convertView;
        holder = (ViewHolder) convertView.getTag();
        ((ImageView)convertView).setImageBitmap(null);
    }

    new AsyncTask<ViewHolder, Void, Bitmap>() {
        private ViewHolder v;

        // get screen dimensions
        @Override
        protected Bitmap doInBackground(ViewHolder... params) {
            v = params[0];
            Bitmap image = decodeFile(_filePaths.get(position), imageWidth,
                    imageWidth);
            //imageView.setImageBitmap(image);
            return image;
        }
        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            v.image.setImageBitmap(result);

        }
    }.execute(holder);

    return convertView;
}

/*
 * Resizing image size
 */
public Bitmap decodeFile(String filePath, int WIDTH, int HEIGHT) {
    try {
        File f = new File(filePath);
        if(filePath.contains(".jpg")) {
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            final int REQUIRED_WIDTH = WIDTH;
            final int REQUIRED_HEIGHT = HEIGHT;
            int scale = 1;
            while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
                    && o.outHeight / scale / 2 >= REQUIRED_HEIGHT)
                scale *= 2;

            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        }else  if(filePath.contains(".mp4")){
            return ThumbnailUtils.createVideoThumbnail(filePath, 0);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}
class ViewHolder {
    ImageView image;
    int position;
}
}

Contextual action menu code

public class MultiChoiceModeListener implements
        GridView.MultiChoiceModeListener {
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        MenuInflater inflater = mode.getMenuInflater();
        inflater.inflate(R.menu.contextual_action_menu, menu);
        //mode.setTitle("Select Items");
        mode.setTitle("1 item selected");
        return true;
    }

    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return true;
    }
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        // Respond to clicks on the actions in the CAB
        switch (item.getItemId()) {
            case R.id.delete:
                SparseBooleanArray checked = gridView.getCheckedItemPositions();
                try {
                    int len = checked.size();
                    for (int i = 0; i < len; i++) {
                        if (checked.valueAt(i)) {
                            Integer position = checked.keyAt(i);
                            //deleteToMessageHistory(position);
                        }
                    }
                }catch (Exception i){
                    Toast.makeText(PhotosGridViewActivity.this, "Message was not deleted. Try again.", Toast.LENGTH_SHORT).show();
                }
                mode.finish(); // Action picked, so close the CAB
                return true;
            default:
                return false;
        }
    }
    public void onDestroyActionMode(ActionMode mode) {
    }
    public void onItemCheckedStateChanged(ActionMode mode, int position,
                                          long id, boolean checked) {
        int selectCount = gridView.getCheckedItemCount();
        switch (selectCount) {
            case 1:
                mode.setTitle("1 item selected");
                break;
            default:
                mode.setTitle("" + selectCount + " items selected");
                break;
        }
    }
}

I appreciate any help!

==UPDATE==

Here is the MainActivity code:

public class PhotosGridViewActivity extends Activity {

private PhotosUtils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private PhotosGridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initilizing Grid View
    InitilizeGridLayout();

}

private void InitilizeGridLayout() {
    setContentView(R.layout.photos_grid_view);
    utils = new PhotosUtils(PhotosGridViewActivity.this);
    gridView = (GridView) findViewById(R.id.grid_view);
    // loading all image paths from SD card
    imagePaths = utils.getFilePaths();
    Resources r = getResources();
    float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            AppConstant.GRID_PADDING, r.getDisplayMetrics());

    columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);

    gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
    gridView.setColumnWidth(columnWidth);
    gridView.setStretchMode(GridView.NO_STRETCH);
    gridView.setPadding((int) padding, (int) padding, (int) padding,
            (int) padding);
    gridView.setHorizontalSpacing((int) padding);
    gridView.setVerticalSpacing((int) padding);

    gridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
    gridView.setMultiChoiceModeListener(new MultiChoiceModeListener());

    // Gridview adapter
    adapter = new PhotosGridViewImageAdapter(PhotosGridViewActivity.this, imagePaths,
            columnWidth);
    // setting grid view adapter
    gridView.setAdapter(adapter);

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            gridView.getItemAtPosition(position);
            Intent i = new Intent(PhotosGridViewActivity.this, PhotosScreenViewActivity.class);
            i.putExtra("position", position);
            PhotosGridViewActivity.this.startActivity(i);
        }
    });
}

public class MultiChoiceModeListener implements
        GridView.MultiChoiceModeListener {
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        MenuInflater inflater = mode.getMenuInflater();
        inflater.inflate(R.menu.contextual_action_menu, menu);
        //mode.setTitle("Select Items");
        mode.setTitle("1 item selected");
        return true;
    }

    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return true;
    }
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        // Respond to clicks on the actions in the CAB
        switch (item.getItemId()) {
            case R.id.delete:
                SparseBooleanArray checked = gridView.getCheckedItemPositions();
                try {
                    int len = checked.size();
                    for (int i = 0; i < len; i++) {
                        if (checked.valueAt(i)) {
                            Integer position = checked.keyAt(i);
                            //deleteToMessageHistory(position);
                        }
                    }
                }catch (Exception i){
                    Toast.makeText(PhotosGridViewActivity.this, "Message was not deleted. Try again.", Toast.LENGTH_SHORT).show();
                }
                mode.finish(); // Action picked, so close the CAB
                return true;
            default:
                return false;
        }
    }
    public void onDestroyActionMode(ActionMode mode) {
    }
    public void onItemCheckedStateChanged(ActionMode mode, int position,
                                          long id, boolean checked) {
        int selectCount = gridView.getCheckedItemCount();
        switch (selectCount) {
            case 1:
                mode.setTitle("1 item selected");
                break;
            default:
                mode.setTitle("" + selectCount + " items selected");
                break;
        }
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(co.glurl.appoid.R.menu.photo_gallery, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.add:
            /** Go to the user's add photos. */
            startActivity(new Intent(this, PhotoIntentActivity.class));
            break;
        //case R.id.settings:
            /** Go to the user's settings photos. */
        //    startActivity(new Intent(this, PhotoGridSettings.class));
        //    break;
        default:
            return super.onContextItemSelected(item);
    }
    return true;
}

}
like image 899
afazolo Avatar asked May 02 '15 01:05

afazolo


1 Answers

My soluction. Thanks to @pushbit for guiding me through it.

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ImageView imageView = (ImageView) convertView;
    if (imageView == null) {
        imageView = new ImageView(_activity);
    }

    // Trigger the download of the URL asynchronously into the image view.
    if(_filePaths.get(position).contains(".jpg")) {
        Picasso.with(_activity)
                .load(new File(_filePaths.get(position)))
                .resize(imageWidth, imageWidth)
                .centerCrop()
                .tag(_activity)
                .into(imageView);
    }else  if(_filePaths.get(position).contains(".mp4")){
        VideoRequestHandler videoRequestHandler;
        Picasso picassoInstance;
        videoRequestHandler=new VideoRequestHandler();
        picassoInstance = new Picasso.Builder(_activity.getApplicationContext())
                .addRequestHandler(videoRequestHandler)
                .build();
        picassoInstance
                .load(videoRequestHandler.SCHEME_VIDEO+":"+_filePaths.get(position))
                .resize(imageWidth, imageWidth)
                .centerCrop()
                .tag(_activity)
                .into(imageView);
    }
    return imageView;
}

public static boolean deleteToPhotoAlbum(Integer position) {
    File file = new File(_filePaths.get(position));
    boolean deleted = file.delete();
    return deleted;
}

public class VideoRequestHandler extends RequestHandler {
    public String SCHEME_VIDEO  = "video";
    @Override
    public boolean canHandleRequest(Request data)
    {
        String scheme = data.uri.getScheme();
        return (SCHEME_VIDEO.equals(scheme));
    }

    @Override
    public Result load(Request data, int arg1) throws IOException
    {
        Bitmap bm = ThumbnailUtils.createVideoThumbnail(data.uri.getPath(), MediaStore.Images.Thumbnails.MINI_KIND);
        return new Result(bm, Picasso.LoadedFrom.DISK);
    }
}
like image 137
afazolo Avatar answered Sep 20 '22 04:09

afazolo