Search code examples
javaandroidandroid-studioimageviewlag

How to prevent lag when loading more than one picture in Android Studio


I need to get 4 pictures from gallery...

When I touch one of the 4 ImageView in my Activity it calls the following piece of code:

public void imagePicker(View view)
{
    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, view.getId());
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    ImageView image1=(ImageView)findViewById(R.id.image1);
    ImageView image2=(ImageView)findViewById(R.id.image2);
    ImageView image3=(ImageView)findViewById(R.id.image3);
    ImageView image4=(ImageView)findViewById(R.id.image4);

    if ((requestCode == R.id.image1 || requestCode == R.id.image2 || requestCode == R.id.image3 || requestCode == R.id.image4) && resultCode == RESULT_OK && data != null)
    {
        Uri pickedImage = data.getData();
        String[] filePath = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
        cursor.moveToFirst();
        String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
        switch(requestCode)
        {
            case R.id.image1:
                image1.setImageBitmap(bitmap);
                break;
            case R.id.image2:
                image2.setImageBitmap(bitmap);
                break;
            case R.id.image3:
                image3.setImageBitmap(bitmap);
                break;
            case R.id.image4:
                image4.setImageBitmap(bitmap);
                break;
        }
        cursor.close();
    }

But when it loads the second image the Activity start lagging. So, how can I avoid this? I tought I could reduce the ImageView's resolution and store the original images elsewhere. If this works, how can I do it?


Solution

  • Try scale your bitmap to lower its actual resolution, I've used the following codes to reduce bitmap's size.

    int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
    Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);