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");
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 am trying to create a mp3 player as an android app and I want to have it that it will automatically find any .mp3 file in my My Files folder. I don't want to have a direct path to a Music folder as I will include a link to Dropbox, where I can download a .mp3 file that is already on it. This will go to a Download folder and I want my MP3 player to pick it up for me.
How could I do this? Any help would be much appreciated.
This method should work
private void searchMusic() {
int count = 0;
ArrayList<String> musicFiles;
LinkedList<File> stack = new LinkedList<File>();
File directory = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath());
stack.add(directory);
while (!stack.isEmpty()) {
File fmusic = stack.removeLast();
File[] files = null;
try {
files = fmusic.listFiles();
} catch (Exception e) {
}
musicFiles = new ArrayList<String>();
if (files != null) {
for (File folder : files) {
if (folder.getName().endsWith(".mp3")
|| folder.getName().endsWith(".ogg")
|| folder.getName().endsWith(".wav")
&& folder.isFile() && folder.canRead()
&& !folder.getName().startsWith("._")) {
count++;
musicFiles.add(folder.getPath());
}
try {
if (folder.isDirectory()
&& !FileUtils.isSymlink(folder)) {
stack.addFirst(folder);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return;
}
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