I continually get an error.
Each time that I run the code in the emulator, it shows the 'Toast' that the directory was created, but there must be an error shortly after that line of code. The error that comes up is:
"/storage/sdcard/Pictures/screenshot.png: open failed: ENOENT (No such file or directory)"
I have place the relevant code below.
<manifest
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19"
/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18"
/>
</manifest>
public class myActivity {
private void openScreenPrint() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)){
View v1 = findViewById(R.id.myRelativeLayout).getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap myBM = Bitmap.createBitmap(v1.getDrawingCache());
saveBitmap(myBM);
v1.setDrawingCacheEnabled(false);
}
else{
Toast.makeText(this, "No Permission to Write", Toast.LENGTH_SHORT).show();
}
}
public void saveBitmap(Bitmap bitmap) {
FileOutputStream fos = null;
String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File dir = new File(filePath);
if (!dir.exists()){
dir.mkdirs();
Toast.makeText(this, "created", Toast.LENGTH_LONG).show(); //This line shown every time
}
String fileName = "screenshot" + ".png";
File imagePath = new File(filePath, fileName);
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
//Log.e("Err", e.getMessage(), e);
} catch (IOException e) {
//Log.e("Err", e.getMessage(), e);
}
}
}
Have you created an SD Card in your AVD? If not, here's the entry that you'll want to use when creating/editing your simulated device:
You do not actually know that the directory is actually being created. You are making the Toast whether the directory create succeeds or not. You should change this section:
if (!dir.exists()){
dir.mkdirs();
Toast.makeText(this, "created", Toast.LENGTH_LONG).show();
}
to test if the directory was actually created successfully. File.mkdirs() returns a boolean.
if (!dir.exists()) {
Toast.makeText(this, "dir not exists. attempting to create...", Toast.LENGTH_SHORT).show();
if (dir.mkdirs()) {
Toast.makeText(this, "dir created", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "dir creation failed", Toast.LENGTH_SHORT).show();
}
}
Related
This question already has answers here:
Unable to save image file in android oreo update. How to do it?
(2 answers)
Closed 4 years ago.
I'm saving image from glide to device. I'm asking for permission in first App run cause that's what my app do.
final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DesiJewellery/");
public void saveImage(Bitmap bitmap, String img_title) {
fname = img_title;
myDir.mkdirs();
File image = new File(myDir, fname);
FileOutputStream outStream;
if (image.exists()) {
image.delete();
}
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getActivity(), "Design saved - " + img_title, Toast.LENGTH_SHORT).show();
} else {
// Toast.makeText(getActivity(), "Something went wrong.", Toast.LENGTH_LONG).show();
}
// this one to show in gallery:
}
It's working fine in emulator, but in real device it shows
java.io.FileNotFoundException: /storage/emulated/0/DesiJewellery/m_aad14.jpg (Permission denied)
Permission Check. I run it on MainActivity.
public void isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED && checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
} else {
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
} else {
}
}
P.S.- I have 2 Real devices. It's working in Mashmallow and Nougat Emulator but Problem is in Only Oreo.
You can try the following:
AsyncTask fileTask = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
File directory = new File(Environment.getExternalStorageDirectory() + File.separator + "MyApplication");
if (!directory.exists()) {
directory.mkdirs();
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String name = " "+n+".jpg";
File pictureFile = new File(directory, name);
pictureFile.createNewFile();
try {
FileOutputStream out = new FileOutputStream(pictureFile);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
};
fileTask.execute();
Refer this for help
You should add WRITE_EXTERNAL_PERMISSION in Android Mainifest like below :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
tools:node="replace"/>
My android app on Android-M have the permission declared in Manifest.
android.permission.WRITE_EXTERNAL_STORAGE
My app starts media player which sends control to Jni layer and then to MediaPlayerService and finally to NuPlayer. I understand that my app and NuPlayer are running in two seperate process (http://rxwen.blogspot.in/2010/01/understanding-android-media-framework.html).
Now if i try to create a file in sdcard from native process, suppose from (NuPlayer.cpp) :
FILE *file = fopen("/storage/emulated/0/Test/test.txt", "w+");
file is coming as null and errno is 13 (No permission). So need to know how to give permission to native process to create file on sdcard on Android M.
Thanks in advance for the help.
In Marshmallow you need to ask for permission to user to achieve this try,
1.in your manifest add,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
2.Create function for write into external storage.
private void createFileExternalStorage() {
MarshMallowPermission marshMallowPermission = new MarshMallowPermission(this);
if (!marshMallowPermission.checkPermissionForExternalStorage())
marshMallowPermission.requestPermissionForExternalStorage();
File backupFile;
File appFolder;
// if SDCard available
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
appFolder = new File(Environment.getExternalStorageDirectory(), getResources().getString(R.string.app_name));
if (!appFolder.exists())
appFolder.mkdir();
Log.d(TAG,"In External");
}else { // if not SDCard available
ContextWrapper cw = new ContextWrapper(this);
appFolder = cw.getDir(getResources().getString(R.string.app_name), Context.MODE_PRIVATE);
if (!appFolder.exists())
appFolder.mkdir();
Log.d(TAG,"In internal");
}
//create a new file, to save the downloaded file
backupFile = new File(appFolder, "backup.txt");
Log.d(TAG, "file #" + backupFile.getAbsolutePath());
try {
FileOutputStream f = new FileOutputStream(backupFile);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
}
3.Create class MarshMallowPermission to get & ask for permission.
public class MarshMallowPermission {
public static final int EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2;
Activity activity;
public MarshMallowPermission(Activity activity) {
this.activity = activity;
}
public boolean checkPermissionForExternalStorage(){
int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
public void requestPermissionForExternalStorage(){
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();
} else {
ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
}
}
}
I am using the below code to create a folder in pictures folder and toasting the path.
but folder is not created i have mentioned write to external storage in android manifest.
java.io.File file = new java.io.File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"College");
if(!file.exists())
{
if(file.mkdir())
{
String f =file.getAbsolutePath();
Toast.makeText(getApplicationContext(),f,Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(),"File Not Created",Toast.LENGTH_LONG).show();
}
}
please help me with the problem
This did it for me:
import java.io.File;
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/College");
try
{
if (!file.exists()) {
file.mkdir();
Toast.makeText(this, "Folder created at " + file.toString(), Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
ex.printStackTrace();
}
I used this code and it worked
File file;
String CAMERA_DIR = "/dcim/";
// Check that the SDCard is mounted
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
// Get the absolute path
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "College");
}
else {
file = new File( Environment.getExternalStorageDirectory() + CAMERA_DIR + "College");
}
// Create the storage directory if it does not exist
if (! file.exists()) {
if (! file.mkdirs()) {
Toast.makeText(getApplicationContext(),"File Not Created",Toast.LENGTH_LONG).show();
return;
}
}
String f =file.getAbsolutePath();
Toast.makeText(getApplicationContext(),f,Toast.LENGTH_LONG).show();
}
else {
throw new IOException();
}
}
i m trying to create directory in sd card through this card.but it is not worked.i put write external storage permission in manifest though it is not working.need urgent help.i had put this code in try catch.but it doesn't enter in catch block.here is my code..
try
{
File songDirectory = new File(Environment.getExternalStorageDirectory().toString()+"/iAC2013");
if(!songDirectory.exists())
{
songDirectory.mkdirs();
Toast.makeText(getApplicationContext(),"Directory created", Toast.LENGTH_LONG).show();
// ShowlistView();
}
else
{
//ShowlistView();
Toast.makeText(getApplicationContext(),"Directory AlreadyExists", Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("","Error While creating file is:::::"+e+"");
}
Try out the Below Code :
File sdDir = Environment.getExternalStorageDirectory();
File wwwjdicDir = new File(sdDir.getAbsolutePath() + "/your_folder_name");
if (!wwwjdicDir.exists()) {
wwwjdicDir.mkdir();
}
if (!wwwjdicDir.canWrite()) {
return;
}
try like
File dir = new File(DEFAULT_STORAGE_LOCATION);
// test dir for existence and writeability
if (!dir.exists()) {
try {
dir.mkdirs();
} catch (Exception e) {
return null;
}
} else {
if (!dir.canWrite()) {
return null;
// do your work here
}
}
If this is your code
File songDirectory = new `File(Environment.getExternalStorageDirectory().toString()+"/iAC2013");
you need to chagne it to this
File songDirectory = new File(Environment.getExternalStorageDirectory().toString()+"/iAC2013");
I have a test class that extends ProviderTestCase2<>.
I would like to populate this test class database with data from some .db files.
Is there some particular method to push some .db file into the Mock Context of a ProviderTestCase2?
Otherwise which way is the easier to populate the database from the .db file?!
Thank you very much!!
How about copying in a pre-existing .db file from the SD Card or something similar? This is a quick piece of code that will accomplish this for you:
private void importDBFile(File importDB) {
String dataDir = Environment.getDataDirectory().getPath();
String packageName = getPackageName();
File importDir = new File(dataDir + "/data/" + packageName + "/databases/");
if (!importDir.exists()) {
Toast.makeText(this, "There was a problem importing the Database", Toast.LENGTH_SHORT).show();
return;
}
File importFile = new File(importDir.getPath() + "/" + importDB.getName());
try {
importFile.createNewFile();
copyDB(importDB, importFile);
Toast.makeText(this, "Import Successful", Toast.LENGTH_SHORT).show();
} catch (IOException ex) {
Toast.makeText(this, "There was a problem importing the Database", Toast.LENGTH_SHORT).show();
}
}
private void copyDB(File from, File to) throws IOException {
FileChannel inChannel = new FileInputStream(from).getChannel();
FileChannel outChannel = new FileOutputStream(to).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
Hopefully this will work for your scenario