Hi i am working in app were user can select image when he is registering an account. I am able to get image on lollipop but when i am testing it in marshmallow then i am not getting file and its name, I am able to ask permission from user and when i am selecting image from gallery i am not getting any file or its name
This is my Code
select_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >=23) {
if (checkPermission()){
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}else{
requestPermission();
}
}else{
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
}
});
My Permissions
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(Register.this, Manifest.permission.READ_EXTERNAL_STORAGE );
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(Register.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(Register.this, "Write External Storage permission allows us to access images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(Register.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
if(requestCode == PERMISSION_REQUEST_CODE){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Accepted", Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
}
}
After Selecting Image
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
filePath = data.getData();
if (null != filePath) {
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
// img.setImageBitmap(bitmap);
if (filePath.getScheme().equals("content")) {
try (Cursor cursor = getContentResolver().query(filePath, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
file_name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
img_name.setText(file_name);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I am not getting why its not working in marshmallow even i have given permissions
I solved it.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
filePath = data.getData();
if (null != filePath) {
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
// img.setImageBitmap(bitmap);
if (filePath.getScheme().equals("content")) {
try (Cursor cursor = getContentResolver().query(filePath, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
file_name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
img_name.setText(file_name);
}
}
}else {
String path= data.getData().getPath();
file_name=path.substring(path.lastIndexOf("/")+1);
img_name.setText(file_name);
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
When i was selecting file , then i was not going to this condition
if (filePath.getScheme().equals("content"))
so in else condition i have given this
String path= data.getData().getPath();
file_name=path.substring(path.lastIndexOf("/")+1);
img_name.setText(file_name);
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
To get image from gallery on any api level then follow this :
Copy and paste all 4 function to your activity
And call this to open gallery galleryPermissionDialog();
Variable used
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
protected static final int REQUEST_CODE_MANUAL = 5;
Permission need to add for lower than marshmallow
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Function 1:
void openGallry() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
Function 2 :
void galleryPermissionDialog() {
int hasWriteContactsPermission = ContextCompat.checkSelfPermission(ActivityProfile.this,
android.Manifest.permission.READ_EXTERNAL_STORAGE);
if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(ActivityProfile.this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
return;
} else {
openGallry();
}
}
Function 3 :
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(android.Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for READ_EXTERNAL_STORAGE
boolean showRationale = false;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (perms.get(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
galleryPermissionDialog();
} else {
showRationale = ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE);
if (showRationale) {
showMessageOKCancel("Read Storage Permission required for this app ",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
galleryPermissionDialog();
}
});
} else {
showMessageOKCancel("Read Storage Permission required for this app ",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(ActivityProfile.this, "Please Enable the Read Storage permission in permission", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_CODE_MANUAL);
}
});
//proceed with logic by disabling the related features or quit the app.
}
}
} else {
galleryPermissionDialog();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Function 4 :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = imageReturnedIntent.getData();
/* final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
img_profile.setImageBitmap(selectedImage);*/
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
pictureFile = saveBitmapToFile(new File(picturePath));
Picasso.with(getApplicationContext()).load(new File(picturePath)).transform(new CircleTransform()).into(imgProfile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Function 5 :
public void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(ActivityProfile.this)
.setTitle(R.string.app_name)
.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
file/* is not a valid MIME type. You should use / if you want to support any type of file. The files you see are unselectable because they are not of the correct MIME type.
With the introduction of virtual files in Android 7.0 (files that don't have a bytestream and therefore cannot be directly uploaded), you should most definitely add CATEGORY_OPENABLE to your Intent:
https://developer.android.com/about/versions/nougat/android-7.0.html#virtual_files
https://developer.android.com/reference/android/content/Intent.html#CATEGORY_OPENABLE
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//sets the select file to all types of files
intent.setType("*/*");
// Only get openable files
intent.addCategory(Intent.CATEGORY_OPENABLE);
//starts new activity to select file and return data
startActivityForResult(Intent.createChooser(intent,
"Choose File to Upload.."), PICK_FILE_REQUEST);
}
public String getFileName(Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
String filename =getFileName(yourfileuri);
Related
Instead of the hard coded storage location in the code below, I would like to get the [name & path] of any Excelsheet that user selects, for data import operation. Found that getExternalStorageDirectory is deprecated, not sure how to achieve the requirement for accessing Excelfile from both Internal / External storage of Android.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case imrequestcode:
// Need help at this LOC where filepath could be user selected one.
String FilePath = "/mnt/sdcard/" + "sampleinput.xls";
try {
if (resultCode == RESULT_OK) {
//// Import function goes here
}
} catch (Exception ex) {
lbl.setText("Error " + e);
}
break;
}
}
Intent : Pick an excel sheet which has inputdata
bimport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fileintent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
fileintent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_LOCATION_ACCESS);
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_READ_EXTERNAL_STORAGE);
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
}
fileintent.setType("application/vnd.ms-excel");
try {
startActivityForResult(fileintent, importrequestcode);
fileintent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);
if (Build.VERSION.SDK_INT > 22) {
requestPermissions(new String[]{"FLAG_GRANT_READ_URI_PERMISSION"}, 11);
}
} catch (ActivityNotFoundException e) {
lbl.setText("No file picker activity.");
}
}
});
}
To get the Filename:
private String getFileName(Uri uri) {
Cursor mCursor =
getApplicationContext().getContentResolver().query(uri, null, null, null, null);
int indexedname = mCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
mCursor.moveToFirst();
String filename = mCursor.getString(indexedname);
mCursor.close();
return filename;
}
To get the FilePath:
[Checkthislink](https://stackoverflow.com/questions/13209494/how-to-get-the-full-file-path-from-uri/55469368#55469368)
Call the method and class in onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case imrequestcode:
Uri fileuri = data.getData();
String Nameoffile_selected = getFileName(fileuri);
String Pathoffile_selected = FileUtils.getPath(this, fileuri);
try {
if (resultCode == RESULT_OK) {
//// Import function goes here
}
} catch (Exception ex) {
lbl.setText("Error " + e);
}
break;
}
}
What I want to accomplish is to select a sperate image whenever I click on a separate Imageview. For example, If a click on ImageView_1 I can select one image from the gallery and if I click on Imagview_2 I can select a separate image from the gallery. I have seen there are already many answers to this question but they are all different from what is I want to do. In the previous answers, they get all the images as a list in OnActivity Results and all the images are selected at once from the gallery.
My code
Dependency Used
implementation 'com.theartofdev.edmodo:android-image-cropper:2.8.+'
private void ImageOnclick(){
image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(Upload_New_Product.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
openFileChooser();
} else {
requestStoragePermission();
}
}
});
image_profile2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(Upload_New_Product.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
openFileChooser2();
} else {
requestStoragePermission();
}
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
private void openFileChooser2() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PICK_IMAGE_REQUEST2);
}
#RequiresApi(api = Build.VERSION_CODES.P)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
ImageUri = data.getData();
CropImage.activity(ImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
// .setAspectRatio(1, 1)
.start(this);
} else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
resultUri = result.getUri();
if (Build.VERSION.SDK_INT >= 29) {
try {
bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(getContentResolver(), resultUri));
} catch (IOException e) {
e.printStackTrace();
}
} else {
// Use older version
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
}
//setImage_profile();
resized = Bitmap.createScaledBitmap(bitmap, 600, 600, true);
image_profile.setImageBitmap(resized);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
// UploadingImage();
// UploadingThumbnailImage();
if (requestCode == PICK_IMAGE_REQUEST2 && resultCode == RESULT_OK && data != null) {
ImageUri2 = data.getData();
CropImage.activity(ImageUri2)
.setGuidelines(CropImageView.Guidelines.ON)
// .setAspectRatio(1, 1)
.start(this);
} else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
resultUri2 = result.getUri();
if (Build.VERSION.SDK_INT >= 29) {
try {
bitmap2 = ImageDecoder.decodeBitmap(ImageDecoder.createSource(getContentResolver(), resultUri2));
} catch (IOException e) {
e.printStackTrace();
}
} else {
// Use older version
try {
bitmap2 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), resultUri2);
} catch (IOException e) {
e.printStackTrace();
}
}
resized2 = Bitmap.createScaledBitmap(bitmap2, 600, 600, true);
image_profile2.setImageBitmap(resized2);
//setImage_profile2();
// UploadingImage();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
You missed this line:
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
And activity result should be like this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST) {
if(resultCode == Activity.RESULT_OK) {
if(data.getClipData() != null) {
int count = data.getClipData().getItemCount();
for(int i = 0; i < count; i++)
Uri imageUri = data.getClipData().getItemAt(i).getUri();
//TODO: do something; here is your selected images
}
} else if(data.getData() != null) {
String imagePath = data.getData().getPath();
//TODO: do something
}
}
}
Intent:
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 images"), PICK_IMAGE_REQUEST);
I have created two functionality for photo uploading in my app. The first one is for capture image and the second one is for pick image from gallery. Now I have a photo API as URL. By using this API I have to upload the image at first to server and from server it will be available throught the app. Now I can successfully uploaded the picture in server and in the server side shows the picture. But in the imageview of app does not show that image. Whenever I go to another activity and then come back to image activity the imageview is empty. I have used shared preference to keep the image at image view, but that does not work.
Here is my code for photo activity
public class ViewProfileFragment extends Fragment implements
View.OnClickListener{
private static final int CODE_GALLERY_REQUEST =999 ;
private static final int MY_CAMERA_REQUEST_CODE = 100;
private ImageView image;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private String userChoosenTask;
Bitmap bm;
private String UPLOAD_URL = Constants.HTTP.PHOTO_URL;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_view_profile,
container, false);
.........
image=(ImageView)rootView.findViewById(R.id.profile_pic);
saveData();
return rootView;
}
public void saveData(){
Log.d( "----ViewProfile-Email", "mEmail" );
GlobalClass globalClass = new GlobalClass();
String mEmail = globalClass.getEmail_info();
Realm profileRealm;
profileRealm = Realm.getDefaultInstance();
RealmResults<MyColleagueModel> results =
profileRealm.where(MyColleagueModel.class).equalTo("mail",
mEmail).findAll();
//fetching the data
results.load();
if (results.size() > 0) {
......
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getActivity());
String mImageUri = preferences.getString("image", null);
if (mImageUri != null) {
image.setImageURI(Uri.parse(mImageUri));
} else {
Glide.with( this )
.load(Constants.HTTP.PHOTO_URL+mail)
.thumbnail(0.5f)
.override(200,200)
.diskCacheStrategy( DiskCacheStrategy.ALL)
.into( image);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[]
permissions, int[] grantResults) {
if(requestCode==CODE_GALLERY_REQUEST){
if(grantResults.length>0 && grantResults[0]==
PackageManager.PERMISSION_GRANTED){
galleryIntent();
}
else {
Toast.makeText( getActivity().getApplicationContext(),"You
don't have permission to access gallery",Toast.LENGTH_LONG ).show();
}
return;
}
if(requestCode==MY_CAMERA_REQUEST_CODE){
if(grantResults.length>0 && grantResults[0]==
PackageManager.PERMISSION_GRANTED){
cameraIntent();
}
else {
Toast.makeText( getActivity().getApplicationContext(),"You
don't have permission to access gallery",Toast.LENGTH_LONG ).show();
}
return;
}
super.onRequestPermissionsResult( requestCode, permissions,grantResults );
}
public void showDialog(){
//Create a new builder and get the layout.
final AlertDialog.Builder builder = new
AlertDialog.Builder(this.getActivity());
.....
}
});
alertListView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListViekw Clicked item index
if (position == 0) {
userChoosenTask ="Take Photo";
alert.dismiss();
if(isPermissionGrantedCamera()) {
cameraIntent();
}
}
else if (position == 1){
userChoosenTask ="Choose from Library";
alert.dismiss();
if(isPermissionGrantedGallery()) {
galleryIntent();
}
}
}
});
}
public boolean isPermissionGrantedGallery() {
if (Build.VERSION.SDK_INT >= 23) {
if
(getActivity().checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG","Permission is granted");
return true;
} else {
Log.v("TAG","Permission is revoked");
ActivityCompat.requestPermissions(this.getActivity(), new
String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon
installation
Log.v("TAG","Permission is granted");
return true;
}
}
public boolean isPermissionGrantedCamera() {
if (Build.VERSION.SDK_INT >= 23) {
if
(getActivity().checkSelfPermission(android.Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG","Permission is granted");
return true;
} else {
Log.v("TAG","Permission is revoked");
ActivityCompat.requestPermissions(this.getActivity(), new
String[]{Manifest.permission.CAMERA}, 0);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon
installation
Log.v("TAG","Permission is granted");
return true;
}
}
private void galleryIntent()
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select
File"),SELECT_FILE);
}
public void cameraIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if
(takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null)
{
File cameraFolder;
if
(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
cameraFolder = new
File(Environment.getExternalStorageDirectory(), "image/");
} else {
cameraFolder = getActivity().getCacheDir();
}
if (!cameraFolder.exists()) {
cameraFolder.mkdirs();
}
String imageFileName = System.currentTimeMillis() + ".jpg";File photoFile = new File(cameraFolder + imageFileName);
currentPhotoPath = photoFile.getAbsolutePath();
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_CAMERA);
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_FILE && data!=null){
onSelectFromGalleryResult(data);
}
else if (requestCode == REQUEST_CAMERA ) {
if(!TextUtils.isEmpty(currentPhotoPath)) {
try {
galleryAddPic();
onCaptureImageResult();
}
catch (Exception e){
}
}
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new
Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.getActivity().sendBroadcast(mediaScanIntent);
}
private void onCaptureImageResult() {
Bitmap bitmap = getBitmapFromPath(currentPhotoPath, 200, 200);
image.setImageBitmap(bitmap);
compressBitMap(bitmap);
}
private void onSelectFromGalleryResult(Intent data) {
Uri uri = data.getData();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContext().getContentResolver().query(uri,
projection, null, null, null);
if (cursor != null) {
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
currentPhotoPath = cursor.getString(column_index);
cursor.close();
} else {
currentPhotoPath = uri.getPath();
}// Saves image URI as string to Default Shared Preferences
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("image", String.valueOf(uri));
editor.commit();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
bm = BitmapFactory.decodeFile(currentPhotoPath);
compressBitMap(bm);
}
private void compressBitMap(Bitmap bitmap) {
ImageConversion imageConversion = new ImageConversion();
byte[] bytesArray;
int maxSize = 10 * 1024;
int imageMaxQuality = 50;
int imageMinQuality = 5;
bytesArray = imageConversion.convertBitmapToByteArray(bitmap,
imageMaxQuality, imageMinQuality, maxSize);
File destination = new
File(getContext().getApplicationContext().getFilesDir(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytesArray);
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
currentPhotoPath = destination.getPath();
uploadImage(bytesArray);
}
private void uploadImage(final byte[] bytesArray){
.....
}
}
Please don't use
image.setImageURI(uri);
image.invalidate();
Please use this code below instead of that :
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
I am developing an android app, which has a profile fragment where users can upload profile picture via taking picture or selecting from gallery. For now, everything is working fine via Activity.RESULT_OK. But the problem is the onActivityResult data.getData() that is returning nothing. I have made researches on this issue to no avail.
These are the two methods contained in my editprofile fragment.
private void setGalleryBtn() {
if (PermissionHandler.checkPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
AppHelper.LogCat("Read data permission already granted.");
new PickerBuilder(getActivity(), PickerBuilder.SELECT_FROM_GALLERY)
.setOnImageReceivedListener(imageUri -> {
Intent data = new Intent();
data.setData(imageUri);
AppHelper.LogCat("new image SELECT_FROM_GALLERY" + imageUri);
mEditProfilePresenter.onActivityResult(this, AppConst.SELECT_PROFILE_PICTURE, RESULT_OK, data);
})
.setImageName(getActivity().getString(R.string.app_name))
.setImageFolderName(getActivity().getString(R.string.app_name))
.setCropScreenColor(R.color.colorPrimary)
.withTimeStamp(false)
.setOnPermissionRefusedListener(() -> {
PermissionHandler.requestPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
})
.start();
} else {
AppHelper.LogCat("Please request Read data permission.");
PermissionHandler.requestPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
}
}
private void setCameraBtn() {
if (PermissionHandler.checkPermission(getActivity(), Manifest.permission.CAMERA)) {
AppHelper.LogCat("camera permission already granted.");
new PickerBuilder(getActivity(), PickerBuilder.SELECT_FROM_CAMERA)
.setOnImageReceivedListener(imageUri -> {
AppHelper.LogCat("new image SELECT_FROM_CAMERA " + imageUri);
Intent data = new Intent();
data.setData(imageUri);
mEditProfilePresenter.onActivityResult(this, AppConst.SELECT_PROFILE_CAMERA, RESULT_OK, data);
})
.setImageName(getActivity().getString(R.string.app_name))
.setImageFolderName(getActivity().getString(R.string.app_name))
.setCropScreenColor(R.color.colorPrimary)
.withTimeStamp(false)
.setOnPermissionRefusedListener(() -> {
PermissionHandler.requestPermission(getActivity(), Manifest.permission.CAMERA);
})
.start();
} else {
AppHelper.LogCat("Please request camera permission.");
PermissionHandler.requestPermission(getActivity(), Manifest.permission.CAMERA);
}
}
This is my EditProfilePresenter.onActivityResult method.
public void onActivityResult(Edit_profile_fragment myEdit_profile_fragment, int requestCode, int resultCode, Intent data) {
String imagePath = null;
if (resultCode == Activity.RESULT_OK) {
if (PermissionHandler.checkPermission(myEdit_profile_fragment.getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
AppHelper.LogCat("Read contact data permission already granted.");
switch (requestCode) {
case AppConst.SELECT_PROFILE_PICTURE:
imagePath = FilesManager.getPath(myEdit_profile_fragment.getActivity(), data.getData());
break;
case AppConst.SELECT_PROFILE_CAMERA:
if (data.getData() != null) {
imagePath = FilesManager.getPath(myEdit_profile_fragment.getActivity(), data.getData());
} else {
try {
String[] projection = new String[]{MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA, MediaStore
.Images.ImageColumns.BUCKET_DISPLAY_NAME, MediaStore.Images.ImageColumns.DATE_TAKEN, MediaStore.Images
.ImageColumns.MIME_TYPE};
final Cursor cursor = myEdit_profile_fragment.getActivity().getContentResolver()
.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, MediaStore.Images.ImageColumns
.DATE_TAKEN + " DESC");
if (cursor != null && cursor.moveToFirst()) {
String imageLocation = cursor.getString(1);
cursor.close();
File imageFile = new File(imageLocation);
if (imageFile.exists()) {
imagePath = imageFile.getPath();
}
}
} catch (Exception e) {
AppHelper.LogCat("error" + e);
}
}
break;
}
if (imagePath != null) {
EventBus.getDefault().post(new Pusher(AppConst.EVENT_BUS_IMAGE_PROFILE_PATH, imagePath));
} else {
AppHelper.LogCat("imagePath is null");
}
} else {
AppHelper.LogCat("Please request Read contact data permission.");
PermissionHandler.requestPermission(myEdit_profile_fragment.getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
}
}
}
Please what am I getting wrong?
You can Try this
if (requestCode == REQUEST_FROM_CAMERA && resultCode == RESULT_OK)
{
Bundle extras2 = data.getExtras();
if (extras2 != null) {
// do your stuff here
}
else {
// handle this case as well if data.getExtras() is null
Uri selectedImage = data.getData();
}
}
Hope it helps you
Right Now I am getting my files using a particular piece of code which is working fine but in some of cell phones where there is no software like google drive I am getting message like no application installed for request. So I have searched and found that We can get files using Media.Files but not enough documentation is present to carry out the task.
Code:
warantyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/pdf,application/msword");
Intent i = Intent.createChooser(intent, "File");
getActivity().startActivityForResult(i, FILE_REQ_CODE);
//Toast.makeText(getContext(),"Files",Toast.LENGTH_SHORT).show();
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_REQ_CODE) {
if (resultCode == RESULT_OK) {
String path="";
Uri uri = data.getData();
if (uri != null) {
try {
file = new File(getPath(getContext(),uri));
if(file!=null){
ext = getMimeType(uri);
sendFileToServer(file,ext);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}