i seem to be having problems creating folders in LOLLIPOP and up although code works just fine for previous versions
there is no error in the log-cast it simply does not crate the folder can someone help
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES), "reelyChat/vids");
if(!mediaStorageDir.exists()){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
mediaStorageDir.mkdirs();
try {
mediaStorageDir.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}else{
if(!mediaStorageDir.mkdirs()){
Log.d("reelyChat", "failed to create directory");
return null;
}
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if(type == MEDIA_TYPE_VIDEO){
vid_name = "RC_"+my_user_id+"_profile.mp4";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + vid_name);
}else{
return null;
}
return mediaFile;
}
You need write permission at run time.
//Just call this function
getWirtePermissionAndCreateDir();
private void getWirtePermissionAndCreateDir() {
if (Build.VERSION.SDK_INT < 23) {
createDir();
} else {
final String[] PERMISSIONS_STORAGE = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
//Asking request Permissions
ActivityCompat.requestPermissions(mActivity, PERMISSIONS_STORAGE, 9);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
boolean writeAccepted = false;
switch (requestCode) {
case 9:
writeAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
break;
}
if (writeAccepted) {
createDir();
} else {
Toast.makeText(mActivity, "You don't assign permission.", Toast.LENGTH_LONG).show();
}
}
private void createDir(){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES), "reelyChat/vids");
mediaStorageDir.mkdirs();
}
It looks like you have took permissions but not at run time. Device running on Marshmallow or above needs to take permissions at run time.
For more information visit Developer Site
Related
After following a few tutorials i've got a code to save an created bitmap into the SD Card. However nothing is being saved or created.
I have a method to check if i can write into the External Storage, and it returns true (files \ folders can be created). However when i try to create something it just won't.
I also tried an method just to write an string to the sd card (simple file), didn't worked as well.
Is there any config i should set on Android Studio to save files on the SD Card ?
Important: Using emulated device, no physical device.
I've saw posts on SO\Google about writing to the SD card. They all look like what i'm already doing.
Any input is highly appreciated
Thanks
android-manifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saveview">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
MainActivity.Java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ViewParaSalvar myCustomView = new ViewParaSalvar(this);
Boolean CanWrite = isStoragePermissionGranted();
myCustomView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){
#Override
public void onGlobalLayout() {
Bitmap BmpFromView = loadBitmapFromView(myCustomView);
saveImageToExternalStorage(BmpFromView);
}
});
setContentView(R.layout.activity_main);
}
private File GetFinalFileName()
{
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/saved_images");
//boolean created = myDir.mkdirs();
//ExibirMensagemAlerta(Boolean.toString(created));
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
return file;
}
private void saveImageToExternalStorage(Bitmap finalBitmap) {
try
{
File file = GetFinalFileName();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
// ExibirMensagemAlerta(file.toString());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static Bitmap loadBitmapFromView(View view)
{
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.layout(0, 0, view.getWidth(), view.getHeight());
Log.d("", "combineImages: width: " + view.getWidth());
Log.d("", "combineImages: height: " + view.getHeight());
view.draw(canvas);
return bitmap;
}
public void ExibirMensagemAlerta(String msg)
{
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
public boolean isStoragePermissionGranted() {
Boolean finalPerm;
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
//ExibirMensagemAlerta("Permission is granted");
finalPerm = true;
return true;
} else {
// ExibirMensagemAlerta("Permission revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
finalPerm = false;
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
//ExibirMensagemAlerta("Permission is granted");
finalPerm = true;
return true;
}
}
}
I use system permission.And I announced permission to read and write in sdcard. According to the past, the following writing methods were made. But in Android 8.0+ devices. I always get permission denied at logFile.createNewFile(). But if my file path replace to internal storage is pass.
Looking for the network data, only find a SAF mechanism may provide assistance, but this mechanism is the file manager of the intent machine itself, after returning a URI to perform the function of reading and writing files, the same URI is given to the same funtion Unable to create a new file successfully.(https://github.com/termux/termux-app/issues/812)
I try to use execute function Runtime.getRuntime().exec("push '/storage/emulated/0/eee.txt' '/storage/3630-6236/'"). But it doesn't work,either.
Is there any solutions to write on Android 8.0+ sdcard?Currently trying to use DocumentFile to do.(https://github.com/TeamAmaze/AmazeFileManager/blob/master/app/src/main/java/com/amaze/filemanager/filesystem/HybridFile.java)
private final static String localFullPath = PATH_SDCARD + File.separator + nowFormat + "_log.txt";
public static void logWriter(String logText) {
try {
File logFile = new File(localFullPath);
if (!logFile.exists()) {
if (logFile.createNewFile()) {
Log.d("mkdir", "Create new file: " + localFullPath);
}
}
Date date = new Date(System.currentTimeMillis());
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault());
String nowFormat = simpleDateFormat.format(date);
FileWriter fileWriter = new FileWriter(localFullPath, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.append("[").append(nowFormat).append("] ").append(logText);
bufferedWriter.newLine();
bufferedWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void CheckPermission() {
// CheckStoragePermission();
String PERMISSION_WRITE_STORAGE = "android.permission.WRITE_EXTERNAL_STORAGE";
String PERMISSION_READ_PHONE_STATE = "android.permission.READ_PHONE_STATE";
String PERMISSION_ACCESS_FINE_LOCATION = "android.permission.ACCESS_FINE_LOCATION";
String PERMISSION_ACCESS_COARSE_LOCATION = "android.permission.ACCESS_COARSE_LOCATION";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if ((ContextCompat.checkSelfPermission(this, PERMISSION_WRITE_STORAGE) != PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(this, PERMISSION_ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(this, PERMISSION_ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(this, PERMISSION_READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)) {
String[] perms = {PERMISSION_WRITE_STORAGE, PERMISSION_READ_PHONE_STATE, PERMISSION_ACCESS_FINE_LOCATION, PERMISSION_ACCESS_COARSE_LOCATION};
int permsRequestCode = 1;
requestPermissions(perms, permsRequestCode);
}
}
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
public static String[] getExtSdCardPathsForActivity(Context context) {
List <String> paths = new ArrayList <>();
for (File file : context.getExternalFilesDirs("external")) {
if (file != null) {
int index = file.getAbsolutePath().lastIndexOf("/Android/data");
if (index < 0) {
Log.w(LOG, "Unexpected external file dir: " + file.getAbsolutePath());
} else {
String path = file.getAbsolutePath().substring(0, index);
try {
path = new File(path).getCanonicalPath();
} catch (IOException e) {
// Keep non-canonical path.
}
paths.add(path);
}
}
}
if (paths.isEmpty()) paths.add("/storage/sdcard1");
return paths.toArray(new String[0]);
}
1 Only define permissions in AndroidManifest.xml is not enough, you have to requestPermissions in onCreate #MainActivity.
2 Another way to solve it is to target the sdk version to lower than M, for ex targetSdkVersion 15.
At Android 8+ you have to add also the READ_EXTRERNAL_STORAGE permission
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if ((checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) ||
(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
Log.e(getClass().getSimpleName(), "missing permission: external storage");
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom));
builder.setTitle(getResources().getString(R.string.assign_permissions));
builder.setMessage(getResources().getString(R.string.permissions_prompt));
builder.setPositiveButton(getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
requestPermissions(new String[]
{android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE);
}
dialog.dismiss();
}
});
builder.show();
return;
}
}
I am trying to create a text document with user inputted information but nothing is being created... Here is the code I have used for the button click:
runnerTestResultBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (capitanPasswordValidate()& permissionGranted) {
if (capitanPasswordET.getText().toString().equals(capitanPassword)) {
createFile();
} else {
capitanPasswordError.setText("Wrong Password!");
capitanPasswordError.requestFocus();
}
}
}
});
Also, here is the code I am using to create the file:
private void createFile() {
String familiaName = familiaNamesSpinner.getSelectedItem().toString();
String FILE_NAME = familiaName + "_Runner_Test_Results.txt";
String cafeteroTestResultString = runnerTestResult1.getText().toString();
FileOutputStream fos = null;
File file = new File(FILE_NAME);
try {
capitanPasswordError.setText("");
fos = new FileOutputStream(file);
fos.write(cafeteroTestResultString.getBytes());
fos.close();
Toast.makeText(this, "worked", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "did not work", Toast.LENGTH_SHORT).show();
} finally {
if (fos != null) try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Just a side note, I am making it so the user selects a choice from a spinner View in order to track down which file belongs to which person. it is under familiaName and will be part of the name of the file created. any feedback would be amazing, thank you!!
You must check for permissions before reading or writing a file, Please add permission requests to manifests and request permissions for READ, WRITE operations at runtime,
Here i have a simple solution, - (Multiple permission checking)
String[] permissions = new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE}; // Here i used multiple permission check
Then call it in Oncreate
if (checkPermissions()) {
// permissions granted.
getCallDetails();
}
Finally, copy the below code
private boolean checkPermissions() {
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;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MULTIPLE_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permissions granted.
getCallDetails(); // Now you call here what ever you want :)
} else {
String perStr = "";
for (String per : permissions) {
perStr += "\n" + per;
}
// permissions list of don't granted permission
}
return;
}
}
}
Been stuck on this for a while now and have no clue. I'm trying to write some objects to file for an app I'm making but keep getting the file not found exception. Here are the methods for write & read that I'm using.
I get the log to say read is starting, but after that I get the error and get no more logs.
private void loadData() throws IOException, ClassNotFoundException {
// Will run and load all data from the config file into the app's memory
Log.d("READ:", "reading starting");
FileInputStream fileInputStream = new FileInputStream("config");
ObjectInputStream oIS = new ObjectInputStream(fileInputStream);
Object[] output = new Object[4];
for (int i=0; i<4; i++) {
output[i] = oIS.readObject();
Log.d("READ:", output[i].toString());
}
oIS.close();
fileInputStream.close();
return;
}
public void writeData() throws IOException {
FileOutputStream fOut = openFileOutput("config", Context.MODE_PRIVATE);
ObjectOutputStream oOut = new ObjectOutputStream(fOut);
Log.d("writeData:", "streamsOpened");
oOut.writeInt(this.targetINR);
oOut.writeObject(this.inrReadings);
oOut.writeObject(this.weeklyDoses);
oOut.writeObject(this.alarmTime);
Log.d("writeData:", "objectsWritten");
oOut.close();
fOut.close();
Log.d("writeData:", "Streams closed, write finished");
return;
}
Heres the code that calls these methods.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
inrReadings = new HashMap<Calendar, Integer>();
weeklyDoses = new HashMap<Calendar, Integer>();
TextView debug = (TextView) findViewById(R.id.textView) ;
debug.setText("Vars init");
targetINR = 2;
inrReadings.put(Calendar.getInstance(), 2);
weeklyDoses.put(Calendar.getInstance(), 2);
alarmTime = Calendar.getInstance();;
isStoragePermissionGranted();
/* try {
writeData();
} catch (IOException e) {
e.printStackTrace();
debug.setText(debug.getText() + " errorWrite");
Log.d("writeData:", "ioException");
}
try {
loadData();
} catch (IOException e) {
e.printStackTrace();
Log.d("readData:", "ioException");
debug.setText(debug.getText() + " errorRead");
} catch (ClassNotFoundException e) {
e.printStackTrace();
Log.d("readData:", "ioException");
debug.setText(debug.getText() + " errorClassNotFound");
}
*/
}
Here are the two permision check methods:
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("Perms:","Permission is granted now");
return true;
} else {
Log.v("Perms:","Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v("Perms:","Permission is granted already");
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v("Perms:","Permission: "+permissions[0]+ "was "+grantResults[0]);
// User has granted the access. Now you can initiate the file writing.
try {
writeData();
} catch (IOException e) {
e.printStackTrace();
Log.v("Write:", "ioError");
}
MediaScannerConnection.scanFile(this,
new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
}
});
try {
loadData();
} catch (IOException e) {
e.printStackTrace();
Log.v("Read:", "ioError");
} catch (ClassNotFoundException e) {
e.printStackTrace();
Log.v("Read:", "ClassNotFound");
}
}
}
Full error log here: https://pastebin.com/dhxnXyUg
New error log: https://pastebin.com/Nq0Kh1Au
**Edit:
Fixed it with a work around, see answers.**
I think you have not added the following permission in your AndroidManifest.xml file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
If you are using the latest version of Android SDK in your device, then you have to request for permission from the user as well. Here's how you can request the permission to write external storage from user.
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
return true;
} else {
Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
// User has granted the access. Now you can initiate the file writing.
writeData();
}
}
Update
I can see that you are trying to access the file immediately after the file is created. In case of doing that, you need to scan the file before you access the newly created file.
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,
new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
}
});
I think you need to modify your writeData function like the following.
public void writeData() throws IOException {
FileOutputStream fOut = openFileOutput("config", Context.MODE_PRIVATE);
ObjectOutputStream oOut = new ObjectOutputStream(fOut);
Log.d("writeData:", "streamsOpened");
oOut.writeInt(this.targetINR);
oOut.writeObject(this.inrReadings);
oOut.writeObject(this.weeklyDoses);
oOut.writeObject(this.alarmTime);
Log.d("writeData:", "objectsWritten");
oOut.close();
fOut.close();
Log.d("writeData:", "Streams closed, write finished");
MediaScannerConnection.scanFile(this,
new String[]{"/data/data/" + "com.example.yourpackage" + "/config" }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
}
});
return;
}
And the loadData function should be.
private void loadData() throws IOException, ClassNotFoundException {
// Will run and load all data from the config file into the app's memory
Log.d("READ:", "reading starting");
FileInputStream fileInputStream = new FileInputStream("/data/data/" + "com.example.yourpackage" + "/config");
ObjectInputStream oIS = new ObjectInputStream(fileInputStream);
Object[] output = new Object[4];
for (int i=0; i<4; i++) {
output[i] = oIS.readObject();
Log.d("READ:", output[i].toString());
}
oIS.close();
fileInputStream.close();
return;
}
Replace com.example.yourpackage with the package name that you have for your project.
I fixed it in the end, without implementing the onRequestPermision() etc. I just simplified the object write by getting it only write one object (an array of objects). That array has all the values needed stored inside it. Bit of a workaround but it simplifies the writing process!
I could not save Image in external directory in my android app. I practices myself and searched for the same problem but nothing could help me.
All i want to do is display a dialog with that image, and give user a option to save it and if saved view it.
But it always catches a null pointer exception at out.flush(); in Marshmallow and upper.
Works fine in lollipop.
permissions added:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Code seems fine to me. Any help would be highly appreciated.
private void display_image(String url, String title) {
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog_display_images);
dialog.setTitle(title);
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.copyFrom(dialog.getWindow().getAttributes());
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialog.show();
dialog.getWindow().setAttributes(layoutParams);
ImageView iv = (ImageView)dialog.findViewById(R.id.image_here);
final InputStream in;
Bitmap img=null;
final Bitmap imgcpy;
try {
in = getAssets().open(url);
img = BitmapFactory.decodeStream(in);
iv.setImageBitmap(img);
} catch (IOException e) {
e.printStackTrace();
}
imgcpy = img;
final FloatingActionButton save = (FloatingActionButton)dialog.findViewById(R.id.fab_save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String filePath = Environment.getExternalStorageDirectory().toString();
File dir = new File(filePath + "/app_images");
dir.mkdirs();
Random generate = new Random();
int n = 10000;
n = generate.nextInt(n);
String fName = "Image-" + n + ".jpg";
final File file = new File(dir, fName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imgcpy.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
new AlertDialog.Builder(MainActivity.this)
.setTitle("Image Saved Successfully")
.setIcon(R.drawable.ic_save)
.setMessage("Image saved at: " + file.getAbsolutePath())
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setPositiveButton("Open", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Opening...", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + file.getAbsolutePath()), "image/*");
startActivity(intent);
}
})
.create().show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Could not save image", Toast.LENGTH_SHORT).show();
} catch (NullPointerException e) {
Toast.makeText(MainActivity.this, "Could not save image", Toast.LENGTH_SHORT).show();
}
}
});
}
Use this method to create directory and image file:
private File createImageFile() throws IOException {
// Create an image file name
Random generate = new Random();
int n = 10000;
n = generate.nextInt(n);
String nValue = String.valueOf(n);
String fName = "Image-" + n;
String filePath = Environment.getExternalStorageDirectory().toString();
File dir = new File(filePath + "/app_images");
if (!dir.exists()) {
dir.mkdirs();
}
File image = File.createTempFile(
fName, /* prefix */
".jpg", /* suffix */
dir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Log.e("mCurrentPhotoPath", mCurrentPhotoPath + " ++++"); //Prints you the image file path
return image;
}
And call the above method like this wherever you want:
try {
//photoFile = createImageFile();
File photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
Log.e("IO_EX", ex + "");
}
And in the manifest give these permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
All the best!
API level 6.0 or above you need runtime permission:
if (ContextCompat.checkSelfPermission(context,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_EXT_STORAGE);
}
And override this method in your activity:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case Constant.REQUEST_CODE_ASK_PERMISSIONS:
if (grantResults!=null) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Call ur save method here
} else {
Toast.makeText(this, "Please enable write permission from ,Toast.LENGTH_SHORT).show();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}