Image Save to SdCard for 6.0.1 Android Version - android

This code works correctly under 6.0.1 android version but if i run this application on 6.0.1 android devices , it will not save images to sd card.
What i need to update for 6.0.1 devices ?
public void SaveImages(int a ,String b)
{
Bitmap bitmap = null;
OutputStream output;
if(a==0)
{
bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.image_0);
}
File filepath = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath()
+ "/Wallpapers/");
dir.mkdirs();
// Create a name for the saved image
File file = new File(dir,b);
// Show a toast message on successful save
Toast.makeText(FullImageActivity.this, "Loading...",
Toast.LENGTH_SHORT).show();
Toast.makeText(FullImageActivity.this, "Image Saved to SD Card",
Toast.LENGTH_SHORT).show();
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
output.flush();
output.close();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

On Android 6.0+, you need to request runtime permission to write to external storage.
In order to request runtime permission to write to external storage:
public class MarshmallowPermission {
public static final int EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2;
public MarshmallowPermission() {
}
public boolean checkPermissionForExternalStorage(Activity activity) {
if(Build.VERSION.SDK_INT >= 23) {
int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
} else {
return true;
}
}
public void requestPermissionForExternalStorage(Activity activity) {
if(ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(activity,
"External Storage permission needed. Please allow in App Settings for additional functionality.",
Toast.LENGTH_LONG).show();
// user has previously denied runtime permission to external storage
} else {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
}
}
}
Then you can do
if(!marshmallowPermission.checkPermissionForExternalStorage(this)) {
marshmallowPermission.requestPermissionForExternalStorage(this);
} else {
// can write to external
}
And
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == MarshmallowPermission.EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE) {
if(marshmallowPermission.checkPermissionForExternalStorage(this)) {
// can write to external
} else {
// runtime permission denied, user must enable permission manually
}
}
}

Refer the following link,
How to save the image to SD card on button Click android. and
Saving image from image view to sd card : Android.
For detailed tutorial,
http://www.android-examples.com/save-store-image-to-external-storage-android-example-tutorial/

Related

Cannot save pdf files after updating my phone to Android 11

In one of my activities, I save an image in my App's directory subfolder and in the next activity I read the .png file and include it in a pdf file with some other data and save it in my App's directory, Everything worked fine until I updated my phone from Android 10 to 11. Now I get this error:
E/main: error java.io.FileNotFoundException: /storage/emulated/0/IranianMasonryBuildings/sjdnnd -- Fri Feb 12 11:49:36 GMT+03:30 2021.pdf: open failed: EPERM (Operation not permitted)
I tried many fixes online but none of them seem to work.
My manifest includes theses permissions and also the requestLegacyExternalStorage = true
<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" />
android:requestLegacyExternalStorage="true"
compileSdkVersion and targetSdkVersion are set to 29, I tried to change the API level to 28 as mentioned in some answers to other questions but did not work.
This is how I try to create the pdf file:
private boolean isExternalStorageWritable(){
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
Log.i("State", "Yes, it is writable");
return true;
}else{
return false;
}
}
public boolean checkPermission(String permission){
int check = ContextCompat.checkSelfPermission(this, permission);
return (check == PackageManager.PERMISSION_GRANTED);
}
public void checkPermission(String permission, int requestCode)
{
if (ContextCompat.checkSelfPermission(Results.this, permission)
== PackageManager.PERMISSION_DENIED) {
// Requesting the permission
ActivityCompat.requestPermissions(Results.this,
new String[] { permission },
requestCode);
}
else {
/*Toast.makeText(Results.this,
"Permission already granted",
Toast.LENGTH_SHORT)
.show();*/
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == STORAGE_PERMISSION_CODE){
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
/*Toast.makeText(Results.this,
"Storage Permission Granted",
Toast.LENGTH_SHORT)
.show();*/
}
else {
Toast.makeText(Results.this,
"Please grant access",
Toast.LENGTH_SHORT)
.show();
}
}
}
// 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
);
}
}
public void writeExternalStorage (){
String state;
state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) &&
checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
try {
//File storageDir2 = new File(Environment.getExternalStorageDirectory().toString(),
"/IranianMasonryBuildings/BluePrints");
File storageDir2 = new File(Environment.getExternalStorageDirectory().toString(),
"/IranianMasonryBuildings");
File f = new File(storageDir2, "BluePrint213.png");
Bitmap blueprint2 = BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PdfDocument myPdfDocument = new PdfDocument();
Paint myPaint = new Paint();
// Create a page description
PdfDocument.PageInfo myPageInfo1 = new PdfDocument.PageInfo.Builder(PageWidth,
PageHeight, PageNumber).create();
// start a page
PdfDocument.Page myPage1 = myPdfDocument.startPage(myPageInfo1);
Canvas canvas = myPage1.getCanvas();
myPaint = new Paint();
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(3);
canvas.drawRect(200, 250, 1900, 2600, myPaint);
myPdfDocument.finishPage(myPage1);
File storageDir = new File(Environment.getExternalStorageDirectory().toString(),
"/IranianMasonryBuildings");
storageDir.mkdirs(); // make sure you call mkdirs() and not mkdir()
boolean wasSuccessful = storageDir.mkdirs();
if (!wasSuccessful) {
//Toast.makeText(getApplicationContext(), "mkdirs was not Successful ",
Toast.LENGTH_LONG).show();
}
File file2 = new File(storageDir, ProjectName + " -- " + Today + ".pdf");
try {
myPdfDocument.writeTo(new FileOutputStream(file2));
Toast.makeText(this, "The results are saved in" + "IranianMasonryBuildings",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e("main", "error " + e.toString());
Toast.makeText(this, "Error!" + e.toString(), Toast.LENGTH_LONG).show();
}
// close the document
myPdfDocument.close();
Any ideas what is causing the problem and how to fix?
Android 11 (API level 30) further enhances the platform, giving better protection to app and user data on external storage. This release introduces several enhancements, such as opt-in raw file path access for media, batch edit operations for media, and an updated UI for the Storage Access Framework.
Follow this link
https://developer.android.com/about/versions/11/privacy/storage

put image from sd card to imageview in android

I have to place image from sd card to imageview in android
I tried using getExternalStorageDirectory(). It is showing deprecated method. It is not working.
MainActivity
public class MainActivity extends Activity {
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView1);
try {
Bitmap picture = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath()+"/DCIM/mm.png");
imageView.setImageBitmap(picture);
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
// File imgFile = new File("/sdcard/DCIM/mm.png");
//
// if(imgFile.exists()) {
//
// Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
//
// imageView.setImageBitmap(myBitmap);
// }
}
}
xml file
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<ImageView
android:id = "#+id/imageView1"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
/>
</LinearLayout>
I tried many ways. But it is not working. Kindly suggest me to do this.
Manifest Add this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
declare this on your Activity:
String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE,android.Manifest.permission.READ_EXTERNAL_STORAGE};
private Context mContext=MainActivity.this;
private static final int REQUEST = 112;
static ImageView muyimage;
in Oncreate();
muyimage=(ImageView)findViewById(R.id.myimge);
if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (!hasPermissions(mContext, PERMISSIONS)) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST );
} else {
try {
//here i have mentioned my image path ,you have to set your image path
Bitmap picture = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath()+"/Pictures/Screenshots/mine.png");
muyimage.setImageBitmap(picture);
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
}
} else {
try {
//here i have mentioned my image path ,you have to set your image path
Bitmap picture = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath()+"/Pictures/Screenshots/mine.png");
muyimage.setImageBitmap(picture);
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
}
And this
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//do here
} else {
Toast.makeText(mContext, "The app was not allowed to write in your storage", Toast.LENGTH_LONG).show();
}
}
}
}
private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
try {
//here i have mentioned my image path ,you have to set your image path
Bitmap picture = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath()+"/Pictures/Screenshots/mine.png");
muyimage.setImageBitmap(picture);
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
return false;
}
}
}
return true;
}
Environment.getExternalStorageDirectory() returns the primary storage directory of the phone (/storage/emulated/0/) not SD card. The path of SD card storage varies from phone to phone and it depends on manufactures how to implement it. Sometimes SD card mounts to a folder with different names in /storage directory and sometimes in /mnt directory. Starting from Android KitKat (API 19) you have access to getExternalFilesDirs method to get storages directory but there isn't any official solution to work in all phones and android versions. Most of the time SD card mounts to /storage directory so I wrote a solution that works in the android emulator and most of the Android phones but it doesn't guarantee all possibilities. You could change your code like so:
public class MainActivity extends AppCompatActivity {
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView1);
File storageDir = new File("/storage/");
if(storageDir.exists()){
String[] dirList = storageDir.list();
for (String dir: dirList){
if(!(dir.equals("emulated") || dir.equals("self"))){
File file = new File( "/storage/" + dir + "/DCIM/" + "mm.png");
if(file.exists()) {
Bitmap picture = BitmapFactory.decodeFile(file.getAbsolutePath());
imageView.setImageBitmap(picture);
break;
}
}
}
}
}
}

Can't modify file in external storage in android

Please help me... I'm getting
java.io.FileNotFoundException : /storage/'my external storage'/Music/'file name' : open failed: EACCES (Permission denied)
when I'm modifying music's id3 tags which are located in my sd card with jaudiotagger.
I already wrote read/write permissions on manifest file, and I wrote requesting method, permission request result callback method, and a part that modify tags when button clicked like this.
private void requestExternalStoragePermissions() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted to write your External storage", Toast.LENGTH_SHORT).show();
start();
}
else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1 : {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0&&grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
start();
}
else {
Toast.makeText(this, "Permission denied to access your External storage", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
savebutton.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View view){
try{
AudioFile f = AudioFileIO.read(file);
Tag tag = f.getTag();
tag.setField(FieldKey.TITLE,editText1.getText().toString());
tag.setField(FieldKey.ALBUM,editText2.getText().toString());
tag.setField(FieldKey.ARTIST,editText3.getText().toString());
tag.setField(FieldKey.ALBUM_ARTIST,editText4.getText().toString());
tag.setField(FieldKey.YEAR,editText5.getText().toString());
tag.setField(FieldKey.DISC_NO,editText6.getText().toString());
tag.setField(FieldKey.TRACK,editText7.getText().toString());
tag.setField(FieldKey.LYRICS,editText8.getText().toString());
f.commit();
Toast.makeText(getApplicationContext(), "Tag Saved", Toast.LENGTH_SHORT).show();
} catch(Exception e){
e.printStackTrace();
}
}
});
How can I fix this?
In Android 4.4 and higher, editing files on the sd card is not possible anymore. I had the same issue..
The only workaround is to copy the file to the internal storage, modify it and move it back.

Why can't I save to the external storage using my code?

I'm trying to write a program that will need tot save to external storage. Right now I cant seem to save to the external storage.
I included the necessary permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
My code is a simple test for writing to external storage.
final Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String path = Environment.getExternalStorageDirectory() + "/Pictures/" + "test.jpg";
File file = new File(path);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
I have run this code on an emulator and a physical device. In neither case do I see a file saved to the Pictures Folder. Really need help with this.
Since Android M+ you need to request permission not only in Manifest but at runtime also
private void requestPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat
.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
//your permission was already granted then write to storage
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
// here you write to the storage for the first time
} else {
// Permission Denied
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}

Permission denied but I have permission access

I already put a permission access on my manifest still not saving. I tried this yesterday and its saving my image and now I cant. I dont know what is the problem here. logcat says java.io.IOException: open failed: EACCES (Permission denied)
below is the code
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout content = (RelativeLayout) findViewById(R.id.dashBoard);
content.setDrawingCacheEnabled(true);
Bitmap bitmap = content.getDrawingCache();
File file = new File(Environment.getExternalStorageDirectory().getPath()+ imagename+ ".png");
try {
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 10, ostream);
ostream.close();
content.invalidate();
Toast.makeText(getApplicationContext(), "SAVED", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
} finally {
content.setDrawingCacheEnabled(false);
}
}
});
here is the full logcat
https://www.dropbox.com/s/dlb6p5i1nd1kxua/Logcat.txt?dl=0
You need use real time permission after SDK API 23 required.
You can ask permission like this code.
if (Build.VERSION.SDK_INT >= 23) {
if (checkWritePermission()) {
// your code
} else {
requestStoragePermission();
}
} else {
// your code
}
You need to check permission and request put this method.
private boolean checkWritePermission() {
int result = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(MainActivity.this, "EXTERNAL STORAGE permission allows us to save image/video. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_STORAGE_REQUEST_CODE);
}
}
Use onRequestPermissionsResult method for handle permission result
Don't forget to put permission on manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Categories

Resources