1

code:

public class gallerygrid extends Activity {

private GridView grdImages;
private Button btnSelect;

private ImageAdapter imageAdapter;
private String[] arrPath;
private boolean[] thumbnailsselection;
private int ids[];
private int count;


/**
 * Overrides methods
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gallerypickergrid);
    grdImages= (GridView) findViewById(R.id.grdImages);
    btnSelect= (Button) findViewById(R.id.btnSelect);

    final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
    final String orderBy = MediaStore.Images.Media._ID;
    @SuppressWarnings("deprecation")
    Cursor imagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
    int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
    this.count = imagecursor.getCount();
    this.arrPath = new String[this.count];
    ids = new int[count];
    this.thumbnailsselection = new boolean[this.count];
    for (int i = 0; i < this.count; i++) {
        imagecursor.moveToPosition(i);
        ids[i] = imagecursor.getInt(image_column_index);
        int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
        arrPath[i] = imagecursor.getString(dataColumnIndex);
    }

    imageAdapter = new ImageAdapter();
    grdImages.setAdapter(imageAdapter);
    imagecursor.close();


    btnSelect.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            final int len = thumbnailsselection.length;
            int cnt = 0;
            String selectImages = "";
            for (int i = 0; i < len; i++) {
                if (thumbnailsselection[i]) {
                    cnt++;
                    selectImages = selectImages + arrPath[i] + "|";
                }
            }
            if (cnt == 0) {
                Toast.makeText(getApplicationContext(), "Selecione pelo menos uma imagem", Toast.LENGTH_LONG).show();
            } else {

                Log.d("Imagens Selecionadas", selectImages);
                Intent i = new Intent();
                i.putExtra("data", selectImages);
                setResult(Activity.RESULT_OK, i);
                finish();
            }
        }
    });
}
@Override
public void onBackPressed() {
    setResult(Activity.RESULT_CANCELED);
    super.onBackPressed();

}

/**
 * Class method
 */

/**
 * This method used to set bitmap.
 * @param iv represented ImageView
 * @param id represented id
 */

private void setBitmap(final ImageView iv, final int id) {

    new AsyncTask<Void, Void, Bitmap>() {

        @Override
        protected Bitmap doInBackground(Void... params) {
            return MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            iv.setImageBitmap(result);
        }
    }.execute();
}


/**
 * List adapter
 * @author tasol
 */

public class ImageAdapter extends BaseAdapter {
    private LayoutInflater mInflater;

    public ImageAdapter() {
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return count;
    }

    public Object getItem(int position) {
        return position;
    }

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

    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.galleryitem, null);
            holder.imgThumb = (ImageView) convertView.findViewById(R.id.imgThumb);
            holder.chkImage = (CheckBox) convertView.findViewById(R.id.chkImage);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.chkImage.setId(position);
        holder.imgThumb.setId(position);
        holder.chkImage.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                CheckBox cb = (CheckBox) v;
                int id = cb.getId();
                if (thumbnailsselection[id]) {
                    cb.setChecked(false);
                    thumbnailsselection[id] = false;
                } else {
                    cb.setChecked(true);
                    thumbnailsselection[id] = true;
                }
            }
        });
        holder.imgThumb.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                int id = holder.chkImage.getId();
                if (thumbnailsselection[id]) {
                    holder.chkImage.setChecked(false);
                    thumbnailsselection[id] = false;
                } else {
                    holder.chkImage.setChecked(true);
                    thumbnailsselection[id] = true;
                }
            }
        });
        try {
            setBitmap(holder.imgThumb, ids[position]);
        } catch (Throwable e) {
        }
        holder.chkImage.setChecked(thumbnailsselection[position]);
        holder.id = position;
        return convertView;
    }
}


/**
 * Inner class
 * @author tasol
 */
class ViewHolder {
    ImageView imgThumb;
    CheckBox chkImage;
    int id;
}
}

public class gallerygridselect extends BaseNavegationActivity implements View.OnClickListener{

private LinearLayout lnrImages;
private Button btnAddPhots;
private Button btnSaveImages;
private ArrayList<String> imagesPathList;
private Bitmap yourbitmap;
private Bitmap resized;
private final int PICK_IMAGE_MULTIPLE =1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gallery_picker);
    lnrImages = (LinearLayout)findViewById(R.id.lnrImages);
    btnAddPhots = (Button)findViewById(R.id.btnAddPhots);
    btnSaveImages = (Button)findViewById(R.id.btnSaveImages);
    btnAddPhots.setOnClickListener(this);
    btnSaveImages.setOnClickListener(this);
}
@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.btnAddPhots:
            Intent intent = new Intent(gallerygridselect.this,gallerygrid.class);
            startActivityForResult(intent,PICK_IMAGE_MULTIPLE);
            break;
        case R.id.btnSaveImages:
            if(imagesPathList !=null){
                if(imagesPathList.size()>1) {
                    Toast.makeText(gallerygridselect.this, imagesPathList.size() + " no of images are selected", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(gallerygridselect.this, imagesPathList.size() + " no of image are selected", Toast.LENGTH_SHORT).show();
                }
            }else{
                Toast.makeText(gallerygridselect.this," no images are selected", Toast.LENGTH_SHORT).show();
            }
            break;
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if(requestCode == PICK_IMAGE_MULTIPLE){
            imagesPathList = new ArrayList<String>();
            String[] imagesPath = data.getStringExtra("data").split("\\|");
            try{
                lnrImages.removeAllViews();
            }catch (Throwable e){
                e.printStackTrace();
            }
            for (int i=0;i<imagesPath.length;i++){
                imagesPathList.add(imagesPath[i]);
                yourbitmap = BitmapFactory.decodeFile(imagesPath[i]);
                ImageView imageView = new ImageView(this);
                imageView.setImageBitmap(yourbitmap);
                imageView.setAdjustViewBounds(true);
                lnrImages.addView(imageView);
            }
        }
    }

}
}

xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<GridView
    android:id="@+id/grdImages"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"/>

<Button
    android:id="@+id/btnSelect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Selecionar"
    android:layout_marginTop="5dp"/>
</LinearLayout>
//xml that call the gridactivity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingTop="75dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/linearLayout">
    <Button
        android:id="@+id/btnAddPhots"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Escolher Fotos"/>

    <Button
        android:id="@+id/btnSaveImages"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Enviar"/>
</LinearLayout>
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content" android:id="@+id/scroll1"
    >

    <LinearLayout
        android:id="@+id/lnrImages"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    </LinearLayout>
</ScrollView>
</LinearLayout>

My code doesnt give error but in my custom gallery it replicates the image preview of 1 image to all of the others so when i select one picture is other i will post a print too

I got the code from this question:How to select multiple images from gallery in android?

the code is from Haresh Chhelana

print:https://i.stack.imgur.com/6IjOJ.jpg

And if i select 1 image it isnt even that picture. And sometimes the app breaks even if i dont do anything.

Errors that i get:

FATAL EXCEPTION: main
Process: com.example.andrmarques.costumerbook_v2, PID: 23308
                                                                                     java.lang.OutOfMemoryError: Failed to allocate a 79629324 byte allocation with 16777216 free bytes and 37MB until OOM
                                                                                         at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                                                         at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
                                                                                         at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:635)
                                                                                         at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:611)
                                                                                         at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:391)
                                                                                         at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:417)
                                                                                         at com.example.andrmarques.costumerbook_v2.gallerygridselect.onActivityResult(gallerygridselect.java:72)
                                                                                         at android.app.Activity.dispatchActivityResult(Activity.java:6235)
                                                                                         at android.app.ActivityThread.deliverResults(ActivityThread.java:3570)
                                                                                         at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
                                                                                         at android.app.ActivityThread.access$1300(ActivityThread.java:151)
                                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
                                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                         at android.os.Looper.loop(Looper.java:135)
                                                                                         at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                                         at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964)
                                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)
Community
  • 1
  • 1
André Marques
  • 180
  • 1
  • 15
  • if your app "breaks" then there must be error stacktrace – Opiatefuchs May 17 '16 at 09:48
  • i will try to force the "break" to see the error – André Marques May 17 '16 at 10:00
  • 'imageAdapter = new ImageAdapter()' has no connection with 'arrPath' in your code. And check the logic inside 'getView' method of 'ImageAdapter'. – 1'hafs May 17 '16 at 10:01
  • @TheHunter what u mean sry didnt get it – André Marques May 17 '16 at 10:08
  • i think the exception is related to memory issue (as OOM outOfMemory) in the exception, it's related to this line `yourbitmap = BitmapFactory.decodeFile(imagesPath[i]);` when you decode paths into image views, this might be due to too many images or some large images. you may want to look into some techniques to handle this process efficiently – Yazan May 17 '16 at 13:03

0 Answers0