I'm having a problem loading an image from the gallery in my Android app. I have some code that picks an image in emulator. When I make a selection, an exception is thrown and caught, meaning the image doesn't load, but I'm not sure how to diagnose what's happening.
Here is my java code file:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
galleryImage = (ImageView) findViewById(R.id.imageView);
pick_btn = (Button)findViewById(R.id.button);
pick_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i,RESULT_LOAD_IMG);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
Log.i("Image Column Index..", "hoiiii");
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
galleryImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}catch (Exception e)
{
Toast.makeText(getApplicationContext(),"You haven't picked any image",Toast.LENGTH_LONG).show();
}
}
}
You need to ask runtime permission for WRITE_EXTERNAL_STORAGE before
you pick image from gallary.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
declare permissions and request code
private static final String[] REQUEST_PERMISSIONS = new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private static final int REQUEST_PERMISSION_CODE = 007;
//check if permissions are needed
if (!checkPermission()) {
requestPermission();
} else {
//open gallary and pick image
}
private boolean checkPermission () {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
for (String permission : REQUEST_PERMISSIONS) {
if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
private void requestPermission () {
ActivityCompat.requestPermissions(this, REQUEST_PERMISSIONS, REQUEST_PERMISSION_CODE);
}
#Override
public void onRequestPermissionsResult ( int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults){
if (requestCode == REQUEST_PERMISSION_CODE) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//open gallary and pick image
}
}
}
please check user-permission in your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is my edited code:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (!Settings.System.canWrite(this) && (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data))
{
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, 2909);
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
} catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_LONG).show();
}
}
Related
In my app I want to pick an image from gallery. But this app runs perfectly in emulator but in My android device an exception is thrown. The code is given below.`
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;
ImageView imgView;
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
}
I have also added in the manifest
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
My device api is 19, and emulator's api is 23.
The following code is to import images. How can I modify it to import videos? Is there anything similar to bitmap for importing/storing videos?
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1 && resultCode==RESULT_OK && data!=null){
Uri selectedImage=data.getData();
try{
Bitmap bitmap=MediaStore.Images.Media.getBitmap((this.getContentResolver()),selectedImage);
ImageView imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
} catch (Exception e){
e.printStackTrace();
}
}
}
To import the video you can do it like this
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECT_VIDEO);
Then to access it use something like :
# Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_VIDEO) {
selectedVideoPath = getPath(data.getData());
try {
if(selectedVideoPath == null) {
Log.e("selected video path = null!");
finish();
} else {
/**
* try to do something there
* selectedVideoPath is path to the selected video
*/
}
} catch (IOException e) {
//#debug
e.printStackTrace();
}
}
}
finish();
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if(cursor!=null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
else return null;
}
Or Else you can use some library :
https://github.com/coomar2841/image-chooser-library
For importing video you will modify you intent like this
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Video"), PICK_VIDEO_REQUEST);
and accessing that video like this
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == PICK_VIDEO_REQUEST) {
Uri selectedVideoUri = data.getData();
String videopath = getPath(selectedVideoUri);
if (videopath != null) {
Log("Video Path : ",videopath);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Video.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
I want to open gallery with multiple image selection functionality and i am using following code.
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);
It opens gallery app but doesn't let me choose multiple images.
This worked for me from api22 to api29.
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 105);
then in activity result overmethod add this code.
if (resultCode == RESULT_OK && requestCode == 105) {
ClipData clipData = data.getClipData();
if (clipData != null) {
for (int i = 0; i < clipData.getItemCount(); i++) {
Uri imageUri = clipData.getItemAt(i).getUri();
// your code for multiple image selection
}
} else {
Uri uri = data.getData();
// your codefor single image selection
}
Note: after you got the gallery screen hold the image little longer. then in top right click "open". it will allow you to select multiple images.
To select multiple images I use this :
Declare a variable
ActivityResultLauncher activityResultLauncher;
2.Call Register Method in OnCreate Method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload_ad_images);
RegisterOpenImageDialog();
}
3.this is the register method
private void RegisterOpenImageDialog() {
activityResultLauncher = registerForActivityResult(new ActivityResultContracts.GetMultipleContents(), new ActivityResultCallback<List<Uri>>() {
#Override
public void onActivityResult(List<Uri> result) {
if (result != null) {
int x = result.size();
//Do What you Want Here ................
}
}
});
}
4.when the user click select image button
private void btnSelectImage() {
activityResultLauncher.launch("image/*");
}
Click and hold to select multiple image. Don't just click on image. Also you can receive those image using this.
int PICK_IMAGE_MULTIPLE = 1;
String imageEncoded;
List<String> imagesEncodedList;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
// When an Image is picked
if (requestCode == 1 && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
String[] filePathColumn = { MediaStore.Images.Media.DATA };
imagesEncodedList = new ArrayList<String>();
if(data.getData()!=null){
Uri mImageUri=data.getData();
// Get the cursor
Cursor cursor = getContentResolver().query(mImageUri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
cursor.close();
}else {
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
mArrayUri.add(uri);
// Get the cursor
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
imagesEncodedList.add(imageEncoded);
cursor.close();
}
Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
}
}
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
super.onActivityResult(requestCode, resultCode, data);
}
try this:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int SELECT_PICTURE = 100;
private static final String TAG = "MainActivity";
CoordinatorLayout coordinatorLayout;
FloatingActionButton btnSelectImage;
AppCompatImageView imgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find the views...
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
btnSelectImage = (FloatingActionButton) findViewById(R.id.btnSelectImage);
imgView = (AppCompatImageView) findViewById(R.id.imgView);
btnSelectImage.setOnClickListener(this);
}
/* Choose an image from Gallery */
void openImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
// Get the url from data
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getPathFromURI(selectedImageUri);
Log.i(TAG, "Image Path : " + path);
// Set the image in ImageView
imgView.setImageURI(selectedImageUri);
}
}
}
}
public String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
#Override
public void onClick(View v) {
openImageChooser();
}
}
Add Permission in manifest file.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
So I implemented code to let me pick images from my filesystem using the default image picker in Android, but for some reason every image is greyed out. It's not letting me choose an image at all. I tested it on Marshmallow 6.0.1 (from where screenshot is taken) and on Lollipop 5.1.1.
Here's my implementation:
Manifest:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.company.app.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Note that all of this has been done on the same activity, LaunchActivity.java
Variables as used:
private ImageView picturebutton;
private Bitmap imageBitmap;
final private int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE=1;
private int PICK_IMAGE_REQUEST = 1;
ImageView acting as button:
picturebutton = (ImageView) findViewById(R.id.chose_picture);
View.OnClickListener picturebuttonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
checkStorageReadPermission(LaunchActivity.this);
}
};
picturebutton.setOnClickListener(picturebuttonClickListener);
The method checkStorageReadPermission() which requests for storage access permission:
public void checkStorageReadPermission(final Context context){
if(ContextCompat.checkSelfPermission(LaunchActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(LaunchActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)){
}
else {
ActivityCompat.requestPermissions(LaunchActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
}
else{
Log.d("Permissions","Permission was already granted");
startActivity(openGallery());
}
}
The override code for onRequestPermissionsResult():
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startActivity(openGallery());
Log.d("Permissions","Can read storage");
} else {
//code for deny
Log.e("Permissions","Can't read storage");
}
break;
}
}
The intent openGallery() which calls the image picker:
public Intent openGallery() {
Intent og = new Intent();
og.setType("image*/");
og.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(og,"Pick a picture"),PICK_IMAGE_REQUEST);
return og;
}
The code to override onActivityResult() when the Intent is called:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(resultCode,requestCode,data);
if(requestCode==PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
Uri imageUri = data.getData();
try{
imageBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUri);
x.uploadImage(imageBitmap,LaunchActivity.this);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There is no problem with the permission requesting process, the system permission dialog for external storage access comes up, gets granted and the picker opens up, but I can't select any image. Help will be appreciated!
Instead of startActivity(openGallery());,just call openGallery(); method. You are already launching the image picker in that method using startActivityForResilt, so you do not need startActivity() again. Also, remove the return statement from openGallery().
Also, you are setting the MIME type wrong. It should be image/*.
So, the updated one should be:
public void openGallery() {
Intent og = new Intent();
og.setType("image/*");
og.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(og,"Pick a picture"),PICK_IMAGE_REQUEST);
}
OnChoose Code
chooseimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= 23){
boolean result= Utility.checkPermission(getActivity());
if(result) {
galleryIntent();
}
}
else {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
startActivityForResult(i,LOAD_IMAGE_RESULTS); //LOAD_IMAGE_RESULTS
}
}
});
Also Code added For Permission and Set Image
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= 23) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == LOAD_IMAGE_RESULTS) {
onSelectFromGalleryResult(data);
}
}
}
else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) {
Bitmap bitmap = null;
Uri selectedImage = data.getData();
String wholeID = DocumentsContract.getDocumentId(selectedImage);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
//filePath = cursor.getString(columnIndex);
mPath = cursor.getString(columnIndex);
}
cursor.close();
}
else {
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == getActivity().RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
mPath = cursor.getString(cursor.getColumnIndex(filePath[0]));
//edAttach.setText(mPath.toString()); path set anywhere
cursor.close();
}
}
}
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
ivprofile.setImageBitmap(bm);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) {
Uri selectedImage = data.getData();
String wholeID = DocumentsContract.getDocumentId(selectedImage);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
//filePath = cursor.getString(columnIndex);
mPath = cursor.getString(columnIndex);
//edAttach.setText(mPath); path set anywhere
}
cursor.close();
}
else {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mPath = cursor.getString(columnIndex).toString();
System.out.println("picturePath" + mPath);
if (!mPath.equalsIgnoreCase(null)) {
edAttach.setText(mPath);
}
cursor.close();
}
}
public boolean hasPermissionInManifest(Context context, String permissionName) {
final String packageName = context.getPackageName();
try {
final PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
final String[] declaredPermisisons = packageInfo.requestedPermissions;
if (declaredPermisisons != null && declaredPermisisons.length > 0) {
for (String p : declaredPermisisons) {
if (p.equals(permissionName)) {
return true;
}
}
}
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
public static boolean isMediaDocument(Uri uri)
{
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private void galleryIntent()
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),LOAD_IMAGE_RESULTS);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
galleryIntent();
} else {
//code for deny
}
break;
}
}
Or Permission In your mainfiest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Utility.java
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
public class Utility {
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
}
If you cannot select one of the image in the list I think the problem is on the intent.
The intent openGallery() which calls the image picker:
public Intent openGallery() {
Intent og = new Intent();
og.setType("image*/");
og.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(og,"Pick a picture"),PICK_IMAGE_REQUEST);
return og;
}
actually I see that you made a mistake here
og.setType("image*/");
you should write ("image/*") or specify an extension like ("image/jpg") for example!
and actually you don't need for this operation of
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
as the ACTION_GET_CONTENT pick only the image Uri don't need for this permission
I am a beginner of android development. I am trying to develop my own gallery. But I am facing a problem. When I go to SD card on my memory and choose a photo then I am trying to open image using my Image Viewer app. But when I select Image Viewer then another intent is called for choosing my image. But I directly want show the selected image on Imageview. Please anyone help me.
My code:
public class MainActivity extends Activity {
private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
private ImageView imageView;
private String selectedImagePath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.result);
pickImage();
}
public void pickImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
InputStream stream = null;
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
// recyle unused bitmaps
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
Log.v("roni", filePath);
cursor.close();
if(bitmap != null && !bitmap.isRecycled())
{
bitmap = null;
}
bitmap = BitmapFactory.decodeFile(filePath);
imageView.setBackgroundResource(0);
imageView.setImageBitmap(bitmap);
// imageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getPath(Uri uri)
{
String[] projection={MediaStore.Images.Media.DATA};
Cursor cursor=managedQuery(uri,projection,null,null,null);
int column_index=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
/////After changing the code
public class MainActivity extends Activity {
private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
private ImageView imageView;
private String selectedImagePath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.result);
Intent i = new Intent(
Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
InputStream stream = null;
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
// recyle unused bitmaps
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
Log.v("roni", filePath);
cursor.close();
if(bitmap != null && !bitmap.isRecycled())
{
bitmap = null;
}
bitmap = BitmapFactory.decodeFile(filePath);
//imageView.setBackgroundResource(0);
imageView.setImageBitmap(bitmap);
// imageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getPath(Uri uri)
{
String[] projection={MediaStore.Images.Media.DATA};
Cursor cursor=managedQuery(uri,projection,null,null,null);
int column_index=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index); } }
Let's assume you have an activity called ViewActivity that shows selected Image.
in your AndroidManifest.xml set your activity as a Image Viewer Activity by adding this :
<activity android:name=".ViewActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="image/*"/>
</intent-filter>
</activity>
in onCreate() method of ViewActivity catch passed Image by doing this :
Intent intent = getIntent();
Uri data = intent.getData();
//Check If data type is Image
if (intent.getType().indexOf("image/") != -1)
{
myImageView.setImageURI(data);
}
try this Code replace whole class plz if success then i will explain to you
public class ImageGalleryDemoActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}