Error in Folder Creation - android

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();
}
}

Related

Saving file shows Permission Denied though permission granted [duplicate]

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"/>

How to create folder in android

I have stuck up with creation of folder in my mobile which is (Micromax Canvas 2).I cant able to create folder.please tel me where i made mistake.
File folder = new File(Environment.getExternalStorageDirectory() + "/Example");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_LONG).show();
}
permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
File f1 = new File(getApplicationContext().getFilesDir()+"");
fol = new File(f1, "Images");
if(!fol.exists())
{
fol.mkdir();
}
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Example");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_LONG).show();
}
Use getExternalStorageDirectory().getAbsolutePath() instead of just getExternalStorageDirectory().
I implement like this. Instead of "plus(+)" write with a "comma(,)"
File imageFileFolder = new File(Environment.getExternalStorageDirectory(),
"folder name");
imageFileFolder.mkdir();
At first add permission in AndroidMenifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
then add FolderInfo.Class
package com.xxx.cg;
import java.io.File;
import android.os.Environment;
public class FolderInfo {
public static final String SDCARD;
static {
SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath();
}
public static final String CG_FOLDER = SDCARD + "/CG";
public static String ASSET_FOLDER = CG_FOLDER + "/assets";
public static boolean createFolderForCG() {
boolean exist = false;
File dir = new File(CG_FOLDER);
if (dir.exists()) {
exist = true;
} else {
if (dir.mkdirs()) {
exist = true;
}
}
return exist;
}
public static boolean createAssetsFolderForCG() {
boolean exist = false;
File dir = new File(ASSET_FOLDER);
if (dir.exists()) {
exist = true;
} else {
if (dir.mkdirs()) {
exist = true;
}
}
return exist;
}
public static boolean createFolder(String folder) {
boolean exist = false;
File dir = new File(ASSET_FOLDER + "/" + folder);
if (dir.exists()) {
exist = true;
} else {
if (dir.mkdirs()) {
exist = true;
}
}
return exist;
}
}
then call from your activity. such as MainActivity.Class.
FolderInfo.createFolderForCG();
FolderInfo.createAssetsFolderForCG();
FolderInfo.createFolder(subFolderName);
then run. You can show CG/assets your SD Card.
and also sub folders show CG/assets/.................
Best of Luck!
String downloadDirectory = "/folderName";
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File newDownloadDirectory = new File(extStorageDirectory
+ downloadDirectory);
newDownloadDirectory.mkdir();
I have solved the problem.. I have declared <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> after the application tag.So it didnt works. I declared permission before application tag.Now folder had been created.

Cannot print screenshot to sdcard on emulator (eclipse)

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();
}
}

Making a directory in android sdcard

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");

How to populate a test database in Android?

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

Categories

Resources