I am trying to attach a pdf file with my Gmail. But the problem is, it always shows a toast message which says "PERMISSION DENIED FOR THE ATTACHMENT". I tried on some different emails like Yahoo, but the file is still not being attached.
This is my Code for the Attachment:
case R.id.emailPdf:
try {
String filename = "SampleFile1.pdf";
File filelocation = new File(Environment.getDataDirectory() + "/data/" + getPackageName() + "/files/", filename);
filelocation.setReadable(true, false);
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("vnd.android.cursor.dir/email");
String to[] = {""};
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(Intent.createChooser(emailIntent, "Send email..."), 12);
break;
}catch (Exception e){
e.printStackTrace();
}
These are the permissions in the AndroidManifest.xml file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I used the debugger, and I observed that the file is being read from the file location but dont know why its not getting attached.
Any help would be appreciated.
Thanks in advance.
Try like below:
Create method to check runtime permission.
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public boolean checkExternalPermission() {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("Write external storage permission is necessary to read gallery pictures!!!");
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) getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
Now on attach button click:
boolean result = checkExternalPermission();
if (result) {
activeGallery();
}
Create method to open gallery like below:
/**
* to gallery
*/
private void activeGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
Now handle permission result like below:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
activeGallery();
} else {
Toast.makeText(getActivity(), "Permission not granted", Toast.LENGTH_LONG).show();
//code for deny
}
break;
}
}
Now handle activity result like below for your selected attachment:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (resultCode == RESULT_OK && null != data) {
try {
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]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
// MyImage image = new MyImage();
// image.setTitle("Test");
// image.setDescription(
// "test choose a photo from gallery and add it to " +
// "list view");
// image.setDatetime(System.currentTimeMillis());
File file = new File(picturePath);
Uri imageUri = Uri.fromFile(file);
Product product = new Product(catID, "custom", "#1111", imageUri.toString(), "15000", "30%", 0);
dBhelper.createPRODUCT(product);
imageList.add(0, product);
// imageList.add(0, imageUri);
setimage(imageUri.toString(), imgview, true);
// imageList.add(0, picturePath);
adapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
// images.add(image);
}
break;
}
}
And finally declare below global variable:
private static final int RESULT_LOAD_IMAGE = 1;
public static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 3;
Make sure below permission you have define in manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Related
My Topic,
i am trying to take storage permission in android, my permission code works in below andoid 11 ,
but problem is when i try to take storage permission in android 11 then code not works , so please help me..
This is my code:-
This is my AndroidManifest.xml Code
android:requestLegacyExternalStorage="true"
This is my JavaCode Code
#Override
protected void onActivityResult(int _requestCode, int _resultCode, Intent _data) {
super.onActivityResult(_requestCode, _resultCode, _data);
if (_resultCode == RESULT_OK){
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R){
if (Environment.isExternalStorageManager()){
Toast.makeText(this,"Permission Granted",Toast.LENGTH_SHORT).show();
i.setClass(getApplicationContext(), Main2Activity.class);
startActivity(i);
} else {
_takePermission();
}
}
}
switch (_requestCode) {
default:
break;
}
}
public boolean _isPermissionGranted() {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R){
return Environment.isExternalStorageManager();
} else {
int readexternalStoragePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
return readexternalStoragePermission == PackageManager.PERMISSION_GRANTED;
}
}
public void _takePermission() {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R) {
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse(String.format("package:%s",getApplicationContext().getPackageName())));
startActivityForResult(intent,100);
} catch (Exception exception){
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivityForResult(intent,100);
}
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},101);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0){
if (requestCode == 101){
boolean readExternalStorage = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (readExternalStorage){
Toast.makeText(this,"Permission Granted",Toast.LENGTH_SHORT).show();
i.setClass(getApplicationContext(), Main2Activity.class);
startActivity(i);
} else {
_takePermission();
}
}
}
Above is the complete code, please check and tell me what my mistake is, and what is the correct bridge.
Thanks for watching..
android:requestLegacyExternalStorage="true" will not affect if your app targetSdk > 30 (Android 11 and above).
Must add this to manifest:
Request to permission:
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.MANAGE_EXTERNAL_STORAGE}, 1);
Check whether app can access storage:
if (!Environment.isExternalStorageManager())
Request to access "All files and media" access:
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
Uri uri = Uri.fromParts("package", this.getPackageName(), null);
intent.setData(uri);
startActivity(intent);
want to open up text documents as text in an android app. I am working in Android Studio using Java. I have permissions set to allowed an I request user permissions, I researched a lot and could not find anything more than what I have. An error comes up that permission is not granted. I am using an android 7 or higher. Please help!
My code in MainActivity is:
public class MainActivity extends AppCompatActivity {
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
//for asking permission
private final static int REQUEST_CODE_ASK_PERMISSIONS = 1;
private static final String[] REQUIRED_SDK_PERMISSIONS = new String[] {
Manifest.permission.WRITE_EXTERNAL_STORAGE};
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_note_menu, menu);
return super.onCreateOptionsMenu (menu);
}
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.open_note){
//get txt from file and send as text to textEditor action
//pick the file
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(
Intent.createChooser(intent, "Choose a file"),
8778
);
}
if (item.getItemId() == R.id.new_note){
//New Note
Intent intent = new Intent (getApplicationContext(), NoteEditorActivity.class);
startActivity(intent);
return true;
}
return false;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
//get the file path as string
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 8778 && resultCode == Activity.RESULT_OK){
checkPermissions();
if (ContextCompat.checkSelfPermission(
MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED) {
//build the uri
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
verifyStoragePermissions(MainActivity.this);
String baseDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
StringBuilder text = new StringBuilder();
//request permission
final int REQUEST_CODE_ASK_PERMISSIONS = 1;
final String[] REQUIRED_SDK_PERMISSIONS = new String[] {
Manifest.permission.WRITE_EXTERNAL_STORAGE};
try {
BufferedReader br = new BufferedReader(new
FileReader(("/storage/emulated/0/download/paperclip.txt")));
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert).setTitle("File
Name").setMessage("YAY").show();
String line=br.readLine();
while (!((line).equals(null))) {
text.append(line);
text.append('\n');
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert).setTitle("File
Name").setMessage(line + "great").show();
}
br.close();
} catch (IOException e) {
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert).setTitle("File
Name").setMessage("In the catch!" + e).show();
}
String result = text.toString();
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("File Info")
.setMessage(result + "result")
.show();
// You can use the API that requires the permission.
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert) .setTitle("File
Name").setMessage("GRANTED").show();
//performAction(...);
}
}
}
protected void checkPermissions() {
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert) .setTitle("File Name").setMessage("In
Check Permissions").show();
final List<String> missingPermissions = new ArrayList<String>();
// check all required dynamic permissions
for (final String permission : REQUIRED_SDK_PERMISSIONS) {
final int result = ContextCompat.checkSelfPermission(this, permission);
if (result != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(permission);
}
}
if (!missingPermissions.isEmpty()) {
// request all missing permissions
final String[] permissions = missingPermissions
.toArray(new String[missingPermissions.size()]);
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_ASK_PERMISSIONS);
} else {
final int[] grantResults = new int[REQUIRED_SDK_PERMISSIONS.length];
Arrays.fill(grantResults, PackageManager.PERMISSION_GRANTED);
onRequestPermissionsResult(REQUEST_CODE_ASK_PERMISSIONS, REQUIRED_SDK_PERMISSIONS,
grantResults);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[],
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
for (int index = permissions.length - 1; index >= 0; --index) {
if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {
// exit the app if one permission is not granted
Toast.makeText(this, "Required permission '" + permissions[index]
+ "' not granted, exiting", Toast.LENGTH_LONG).show();
finish();
return;
}
}
// all permissions were granted
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listVeiw);
SharedPreferences sharedPreferences =
getApplicationContext().getSharedPreferences("com.example.notepadr", Context.MODE_PRIVATE);
//Dealing with saving and stuff!!!!!
HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null);
if (set==null){
notes.add("Example note");
}else{
notes = new ArrayList(set);
}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
intent.putExtra("noteId", i);
startActivity(intent);
}
});
My xml in activity_main.xml is:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="-16dp"
tools:layout_editor_absoluteY="-69dp">
<Button
android:id="#+id/storage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Storage"
android:layout_marginTop="16dp"
android:padding="8dp"
android:layout_centerHorizontal="true"/>
<ListView
android:id="#+id/listVeiw"
android:layout_width="400dp"
android:layout_height="732dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="false"
android:layout_marginTop="3dp"
android:layout_marginEnd="7dp"
android:layout_marginBottom="-3dp"
android:scrollbarSize="5dp"
android:scrollbarStyle="outsideInset" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Code in AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.notepadr">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/>
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:requestLegacyExternalStorage="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.NotePadR">
<activity android:name=".NoteEditorActivity"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
enter code here <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
When I try to create a directory in storage/emulator/0/ directory, it becomes invisible and inaccessible. I use mkdir() to create, and when I check its existence, dir.exists() returns true, even though I cannot access it.
My device runs in API 23, so I get the permissions in runtime, like this:
boolean hasPermission = (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_READ_STORAGE);
}
I also create onRequestPermissionsResult function:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case REQUEST_READ_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//reload my activity with permission granted or use the features what required the permission
} else
{
Toast.makeText(this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
In this function, I try to access my directory
public void makeOutSide(String song, InputStream ins){
// Create the directory
File dir = new File(Environment.getExternalStorageDirectory(),"appMemes");
// If it does not exists, make it.
if (!dir.exists()) {
dir.mkdirs(); // Generating the directory
}
try {
// Open the resource
byte[] buffer = new byte[ins.available()];
ins.read(buffer);
ins.close();
// Burn
String filename = Environment.getExternalStorageDirectory()
+ "/appMemes/"+song+".mp3";
FileOutputStream fos = new FileOutputStream(filename);
fos.write(buffer);
fos.close();
} catch (Exception e) {
System.out.println(e);
}
}
My AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.renan.appmemes">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
...
</application>
first put EnableRuntimePermission Function in Oncreate
private void EnableRuntimePermission() {
if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale
(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(MainActivity.this, "Allow permissions", Toast.LENGTH_LONG).show();
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, RequestPermissionCode);
}
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length > 0) {
boolean writeExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (writeExternalFile) {
} else {
Toast.makeText(MainActivity.this, "Allow permissions to Edit the Image", Toast.LENGTH_LONG).show();
}
}
break;
}
}
then create direcory using this line
File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DSLR CAMERASagar/");
dir.mkdirs();
I have a method that should check if some permission that I need to have are Granted or not :
public boolean checkCamera(){
String[] permissions= new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA};
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(getApplicationContext(),p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),MULTIPLE_PERMISSIONS );
return false;
}
return true;
}
If not, it request these permissions. The problem is, if I denied one of them it pass as valid Permission.
private void requestPermissionCamera(){
if(checkCamera()){
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent,requestCodeCamera);
}
}
In the moment that checks, it's not returning false as it should and on RequestResult the same thing.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case MULTIPLE_PERMISSIONS:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent,requestCodeCamera);
} else {
Toast.makeText(this, "Not All permissions are granted", Toast.LENGTH_SHORT).show();
}
break;
case READ_STORAGE:
I'm open gallery from one of my fragment but after i select image from gallery
the image doesn't show to me in view.
in the onActivityResult I have error in the rootview in this line:
ImageView imgView = (ImageView) rootview.findViewById(R.id.imgView);
and I test with toast to show me the selected image path but
it doesnt show me the path.
here is my fragment code:
public class Share_Page extends Fragment implements View.OnClickListener {
private static final int RESULT_OK = 1;
String path="";
String imgPath, fileName;
private Button home_page,search_page;
private static int RESULT_LOAD_IMG = 1;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.share, container, false);
home_page = (Button) rootview.findViewById(R.id.home_page);
search_page = (Button) rootview.findViewById(R.id.search_page);
rootview.findViewById(R.id.buttonLoadPicture).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadImagefromGallery();
}
});
btn_click();
return rootview;
}
public void loadImagefromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
public 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 = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
//ImageView imgView = (ImageView) findViewById(R.id.imgView);
ImageView imgView = (ImageView) rootview.findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgPath));
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
path=imgPath;
} else {
Toast.makeText(getActivity(), "image not select",
Toast.LENGTH_LONG).show();
imgPath="2";
}
} catch (Exception e) {
Toast.makeText(getActivity(), "error`enter code here`...!", Toast.LENGTH_LONG)
.show();
}
}
This method is for intent to open gallery and pick image:
public void loadImagefromGallery(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityIfNeeded(galleryIntent, RESULT_LOAD_IMG);
}
And here is result after a image picked. As u see i use image to change a background, u can put it into imageView or what ever u wanted
#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);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imgDecodableString = cursor.getString(columnIndex);
cursor.close();
Drawable d = new BitmapDrawable(getResources(), imgDecodableString);
relativeLayout.setBackground(d);
} 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();
}
}
Also please remember to add a permissions in Manifest
Example how to use a permissions runtime, paste it into Activity
private static final int REQUEST_CODE_EXTERNAL_STORAGE = 1;
private static final int REQUEST_CODE_CAMERA = 2;
private static int RESULT_LOAD_IMG = 1;
#TargetApi(23)
public void checkCameraPermission(){
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
return;
}
if (this.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] {Manifest.permission.CAMERA}, REQUEST_CODE_CAMERA);
}
}
#TargetApi(23)
public void checkStoragePermission() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return;
}
if (this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager
.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_EXTERNAL_STORAGE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[]
grantResults) {
switch (requestCode) {
case REQUEST_CODE_EXTERNAL_STORAGE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Thanks for your permission", LENGTH_SHORT).show();
} else {
Toast.makeText(this, "We need your permission to save image",
LENGTH_SHORT).show();
}
break;
case REQUEST_CODE_CAMERA:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "Thanks for your permission", LENGTH_SHORT).show();
} else {
Toast.makeText(this, "We need your permission to start SOS",
LENGTH_SHORT).show();
}
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
break;
}
}
And if u want to check permissions on fragment u should do like this:
((Activity) getContext()).checkAnyPermission();
u should check this after u open a gallery