简体   繁体   中英

get all image from gallery and store in array

I Have code which is defined for image (drawable ) Means Image is are already defined but I want user to select Image from Gallery . SO first I want to get all Images from gallery and then it is show in view and from their user can select Image .

So it means all Images must be saved in array like below . Any Help for this.

public class StickerSelectActivity extends AppCompatActivity {

    public static final String EXTRA_STICKER_ID = "extra_sticker_id";

    private final int[] stickerIds = {
            R.drawable.abra,
            R.drawable.bellsprout,
            R.drawable.bracelet,
            R.drawable.bullbasaur,
            R.drawable.camera,
            R.drawable.candy,
            R.drawable.caterpie,
            R.drawable.charmander,
            R.drawable.mankey,
            R.drawable.map,
            R.drawable.mega_ball,
            R.drawable.meowth,
            R.drawable.pawprints,
            R.drawable.pidgey,
            R.drawable.pikachu,
            R.drawable.pikachu_1,
            R.drawable.pikachu_2,
            R.drawable.player,
            R.drawable.pointer,
            R.drawable.pokebag,
            R.drawable.pokeball,
            R.drawable.pokeballs,
            R.drawable.pokecoin,
            R.drawable.pokedex,
            R.drawable.potion,
            R.drawable.psyduck,
            R.drawable.rattata,
            R.drawable.revive,
            R.drawable.squirtle,
            R.drawable.star,
            R.drawable.star_1,
            R.drawable.superball,
            R.drawable.tornado,
            R.drawable.venonat,
            R.drawable.weedle,
            R.drawable.zubat
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_sticker_activity);

        //noinspection ConstantConditions
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.stickers_recycler_view);
        GridLayoutManager glm = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(glm);

        List<Integer> stickers = new ArrayList<>(stickerIds.length);
        for (Integer id : stickerIds) {
            stickers.add(id);
        }

        recyclerView.setAdapter(new StickersAdapter(stickers, this));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void onStickerSelected(int stickerId) {
        Intent intent = new Intent();
        intent.putExtra(EXTRA_STICKER_ID, stickerId);
        setResult(RESULT_OK, intent);
        finish();
    }

    class StickersAdapter extends RecyclerView.Adapter<StickersAdapter.StickerViewHolder> {

        private final List<Integer> stickerIds;
        private final Context context;
        private final LayoutInflater layoutInflater;

        StickersAdapter(@NonNull List<Integer> stickerIds, @NonNull Context context) {
            this.stickerIds = stickerIds;
            this.context = context;
            this.layoutInflater = LayoutInflater.from(context);
        }

        @Override
        public StickerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new StickerViewHolder(layoutInflater.inflate(R.layout.sticker_item, parent, false));
        }

        @Override
        public void onBindViewHolder(StickerViewHolder holder, int position) {
            holder.image.setImageDrawable(ContextCompat.getDrawable(context, getItem(position)));
        }

        @Override
        public int getItemCount() {
            return stickerIds.size();
        }

        private int getItem(int position) {
            return stickerIds.get(position);
        }

        class StickerViewHolder extends RecyclerView.ViewHolder {

            ImageView image;

            StickerViewHolder(View itemView) {
                super(itemView);
                image = (ImageView) itemView.findViewById(R.id.sticker_image);
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int pos = getAdapterPosition();
                        if (pos >= 0) { // might be NO_POSITION
                            onStickerSelected(getItem(pos));
                        }
                    }
                });
            }
        }
    }
}

Its not required If you want to show all available images in gallery in your application. You can use

private Cursor cc = null;
cc = this.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null,
                null)

This will give you a connection with files available in gallery. More detailed answer is here

How to implement Image Gallery in Gridview in android?

If In case in your application you have an image view and you want your user to click on the image and then Android should ask if they want to select an image from gallery/camera you can follow this, You can call selectImage method on setOnClickListener on ImageView.

 private void selectImage() {
        final CharSequence[] items = { "Take Photo", "Choose from Library" };
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Update Profile Photograph");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                boolean result = Utility.checkPermission(getActivity());
                if (items[item].equals("Take Photo")) {
                    if(result)
                        cameraIntent();
                } else if (items[item].equals("Choose from Library")) {
                    if(result)
                        galleryIntent();
                }
            }
        });
        builder.show();
    }
private void cameraIntent() {
        Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        File out = Environment.getExternalStorageDirectory();
        out = new File(out, familyMemberId + ".png");
        Uri photoURI = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".app.provider", out);
        takePicture.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
        startActivityForResult(takePicture, 0);
    }

    private void galleryIntent() {
        Intent pickPhoto = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(pickPhoto , 1);//one can be replaced with any action code
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
        switch(requestCode) {
            case 0:
                if(resultCode == Activity.RESULT_OK){
                    File out = Environment.getExternalStorageDirectory();
                    out = new File(out, familyMemberId + ".png");
                    Uri photoURI = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".app.provider", out);
                    Toast.makeText(getContext(), photoURI.toString(), Toast.LENGTH_LONG).show();
                    imageUri =  photoURI.toString();
                    Glide.with(this).load(imageUri).into(familyMemberProfilePick);
                }

                break;
            case 1:
                if(resultCode == Activity.RESULT_OK){
                    Uri selectedImage = imageReturnedIntent.getData();
                    imageUri =  selectedImage.toString();
                    Glide.with(this).load(imageUri).into(familyMemberProfilePick);
                }
                break;
        }
    }

Please don't forget add these in

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application ...

 <provider
            android:name=".utility.GenericFileProvider"
            android:authorities="${applicationId}.app.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
....
</application>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM