<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
//activity A intent
Intent intent = new Intent(Intent.ACTION_PICK,null);
intent.setType("image/*");
intent.putExtra("return-data", true);
startActivityForResult(intent,Constant.ACTION.LOAD_GALLERY_ACTION);
//this is onActicityResult function
case Constant.ACTION.LOAD_GALLERY_ACTION:
Uri uri = data.getData();
if(mImage.size()<maxAddPic) {
mImage.add(copyGalleryPic(uri));
adapter.notifyDataSetChanged();
}
break;
//to copy the gallery photo,return the new file uri.
private Uri copyGalleryPic(Uri uri) {
String filePath = Environment.getExternalStorageDirectory() + "/images/"+"diary"+System.currentTimeMillis()+".jpg";
File outputFile = new File(filePath);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
Bitmap bitmap;
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
bitmap=MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
} catch (IOException e) {
// ... handle IO exception
}
Uri newUri = FileProvider.getUriForFile(CreateDiaryActivity.this,"com.example.diary.cr",outputFile);
return newUri;
}
but there are some errors
the intent returns uri
"content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F29/ORIGINAL/NONE/41130179"
but debug info shows the code
"bitmap=MediaStore.Images.Media.getBitmap(getContentResolver(),
uri);" error : java.io.FileNotFoundException: open failed: ENOENT
(No such file or directory)
please help me ! Love you guys!
My English is not well. please use Simple words. Thank you!
which android version and which sdk-version are you using? I have an android-2.2 app that cannot receive intent permissions under android 7 see: https://github.com/k3b/intent-intercept/issues/4. I assume that recompiling with a more recent android-sdk might help.
Does you program work if you use an InputStream to read the picked image via getContentResolver().openInputStream(data.getData(uri)).
Since android-4.4 ACTION_PICK was replaced by ACTION_OPEN_DOCUMENT. My recent apps that use ACTION_OPEN_DOCUMENT together with openInputStream work as expected
Related
(to make things clearer :) I am using WebView. The idea is that users can visit any page and download any file, the idea is to support as many basic features as i can to get closer feel to built in web browser.
As the title says, i am trying to make my app download files and open them once theyre downloaded. There are some bullet points i want to mention :
user should be able to download any kind of file (i guess its called mimeType), as they would in they default internet browser app
since users download items from webview, it would only make sense if downloads would appear in downloads folder
would be awesome if every users device could decide on itself which app to use to open downloaded file, but, for example, my samsung s9 asks which app to use, thats not a bad option either
i ran across some problems like sucessful download, but the file was empty/corrupted, the downlaoded file was missing in file browser even if app told me that the download is completed
So i have been on not 2nd, not 3rd but even 5th page of google search results, so ive seen a lot, these are couple versions of my code so far, every single one of them are not working as i expected them in my dreams.
Just to be clear, the code you are about to see is under webview setDownloadListener(new DownloadListener() ...
So my latest version, without file opening after download :
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
//used to call a class to in previous code version to make some downloads
//new DownloadTask(webview_base.this, url, mimeType);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)).setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE);
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, url.substring(url.lastIndexOf('/')));
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
});
the problem with ^ this version was that i was able to download files, but it downlaoded pages HTML instead of actual pdf or whatever i was aiming for, thats weird.
previous version was a bit smoother, i was able to download files, and i used a dialog to offer to open a file. Everything worked fine, but documents were empty/corrupted and i got offered to open them with weird apps, for example, once i got asked to open pdf with my smartwatch app, but that mustve gone away since i edited a code time by time. The problem i landed here was that even after couple of ctrl+z i wasnt able to get my app back on feets - i was stuck at download screen and logcat shout at me that it couldnt fine a download directory. at that point i got mad and started the version you can see above. Anyway, here is the whole class :
package com.example.viaapp_v2;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import androidx.core.content.FileProvider;
public class DownloadTask extends FileProvider {
private static final String TAG = "Download Task";
private Context context;
String mimeType;
private String downloadUrl = "", downloadFileName = "";
private ProgressDialog progressDialog;
public DownloadTask() {
//required empty constructor
}
public DownloadTask(Context context, String downloadUrl, String mime) {
this.context = context;
this.downloadUrl = downloadUrl;
this.mimeType = mime;
//Create file name by picking download file name from URL
downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf('/'));
//Start Downloading Task
new DownloadingTask().execute();
}
private class DownloadingTask extends AsyncTask<Void, Void, Void> {
File apkStorage = null;
File outputFile = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Downloading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Void result) {
try {
if (outputFile != null) {
progressDialog.dismiss();
final ContextThemeWrapper ctw = new ContextThemeWrapper( context, R.style.Theme_AppCompat_Light_Dialog);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
alertDialogBuilder.setTitle("Document ");
alertDialogBuilder.setMessage(downloadFileName+" Downloaded Successfully ");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
alertDialogBuilder.setNegativeButton("Open file",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()
+ downloadFileName);//name here is the name of any string you want to pass to the method
if (!file.isDirectory())
file.mkdir();
Intent testIntent = new Intent();
testIntent.setType(mimeType);
testIntent.setAction(Intent.ACTION_VIEW);
Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file);
testIntent.setDataAndType(uri, mimeType);
ctw.startActivity(testIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
alertDialogBuilder.show();
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 3000);
Log.e(TAG, "Download Failed");
}
} catch (Exception e) {
e.printStackTrace();
//Change button text if exception occurs
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 3000);
Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());
}
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL(downloadUrl);//Create Download URl
HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
c.connect();//connect the URL Connection
//If Connection response is not OK then show Logs
if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
+ " " + c.getResponseMessage());
}
//Get File if SD card is present
if (new CheckForSDCard().isSDCardPresent()) {
apkStorage = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
} else
Toast.makeText(context, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();
//If File is not present create directory
if (!apkStorage.exists()) {
apkStorage.mkdir();
Log.e(TAG, "Directory Created.");
}
outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File
//Create New File if not present
if (!outputFile.exists()) {
outputFile.createNewFile();
Log.e(TAG, "File Created");
}
FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
InputStream is = c.getInputStream();//Get InputStream for connection
byte[] buffer = new byte[1024];//Set buffer type
int len1 = 0;//init length
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);//Write new file
}
//Close all connection after doing task
fos.close();
is.close();
} catch (Exception e) {
//Read exception if something went wrong
e.printStackTrace();
outputFile = null;
Log.e(TAG, "Download Error Exception " + e.getMessage());
}
return null;
}
}
private class CheckForSDCard {
//Check If SD Card is present or not method
boolean isSDCardPresent() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
}
}
Looking for my manifest file ? Well here it goes .. ive put in some support for file upload, file download, internet acces, ect
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-feature android:name="android.hardware.camera"/>
<uses-permission android:name="android.permission.CAMERA"/>
i even tried to put some provider stuff in application
<provider
android:name=".DownloadTask"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
But deep inside i had no idea what to put in provider path file
<paths><external-path name="external_files" path="."/></paths>
Sorry that this text is so long. Im just desperate and almost done with my project, but i have to seek for help somewhere to keep going. I hope ive explained my problem enough and provided enough code, would be happy to know which code is better / more possible ( make a class or write everything down right under listener ).
--- EDIT ---
So.. i tried to run my old version of code, which is that long block of code above, class file "DownloadTask.java", which is called by constructor, passing utl, mimetype and context. You can see the line commented in the first block of code in this post, 3rd line. Here is what happened : i visited a page, clicked on a link to download pdf file, but then i got stuck on dialog that shows "downloading.." while logcat said this :
D/ViewRootImpl#19478bd[webview_base]: MSG_RESIZED: frame=Rect(18, 617 - 701, 821) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
D/ViewRootImpl#c47c382[webview_base]: Relayout returned: old=[0,0][720,1480] new=[0,0][720,1480] result=0x1 surface={valid=true 484837122048} changed=false
I/ample.viaapp_v: Compiler allocated 4MB to compile void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Download/Datu%20p%C4%81rraides%20t%C4%ABkli-III_LV.pdf (Is a directory)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:308)
at java.io.FileOutputStream.<init>(FileOutputStream.java:238)
at java.io.FileOutputStream.<init>(FileOutputStream.java:180)
at com.example.viaapp_v2.DownloadTask$DownloadingTask.doInBackground(DownloadTask.java:173)
at com.example.viaapp_v2.DownloadTask$DownloadingTask.doInBackground(DownloadTask.java:54)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
E/Download Task: Download Error Exception /storage/emulated/0/Download/Datu%20p%C4%81rraides%20t%C4%ABkli-III_LV.pdf (Is a directory)
E/Download Task: Download Failed
D/ViewRootImpl#19478bd[webview_base]: MSG_WINDOW_FOCUS_CHANGED 1 1
And yes, as you can see, the file name contais accented letters, thats why its so weird, 99% of users which are willing to use the app, will work around content which uses accented letters so im wondering mayeb i should replace filenames without all these letters like "āēīģčķ" to "aeigck".
I'm trying to let a user export an excel file in my app and have the app automatically open the created excel file. The excel file is created and stored successfully using jxl, but when I try to open it with the Hancom Office Editor nothing happens other than my screen getting a dark overlay. Here's a gif:
I can't figure out what would cause this and can't find anything about it online.
I'm using the accepted answer from here to support my target SDK 28.
my export method:
public void onExport(View view){
try {
//write changes to excel file(changes made outide of function)
workbook.write();
workbook.close();
Toast.makeText(getApplication(),
"Data Exported to Excel Sheet", Toast.LENGTH_SHORT).show();
findViewById(R.id.btn_export).setEnabled(false);
//set file to saved excel file
File file = new File(Environment.getExternalStorageDirectory(),
race.getName()+".xls");
Uri path = FileProvider.getUriForFile(getApplicationContext(), "com.something.racecalculator.fileprovider", file);
Intent intent = new Intent(Intent.ACTION_VIEW);
Log.i("path: ", path.toString());
intent.setDataAndType(path, "image/jpg");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
catch (ActivityNotFoundException e) {
Log.i("oh no:", "No application available to view excel");
}
}
My provider tag in AndroidManifest.xml(set as a child of ):
<provider
android:name=".GenericFileProvider"
android:authorities="com.something.racecalculator.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
I'm not getting any Errors or warnings as far as I can tell. Thanks for any help.
I'm not sure exactly what caused the problem, however, I suspect that I might have had the file path wrong. I changed a couple things (including where the excel files were being saved to. Changed from /storage/emulated/0/ to /storage/emulated/0/Samsung) and here is what worked:
Intent intent = new Intent(Intent.ACTION_VIEW);
File file = new File("/storage/emulated/0/Samsung"+File.separator + race.getName()+".xls");
Uri path = FileProvider.getUriForFile(getApplicationContext(), "com.something.racecalculator.fileprovider", file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(path, "application/vnd.ms-excel");
startActivity(intent);
remember that you need to implement a FileProvider if your target SDK is 24 or above
i have a problem with new FileProvider API:
I have this code to generate a uri from a file:
public Uri generateUri(String authority) {
File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = fileHelper.from(storageDir, PHOTO_NAME);
if (!imageFile.exists() && !imageFile.createNewFile()) {
throw new Exception("Can't create capture file");
}
Uri sharedUri = ExtendedFileProvider.getUriForFile(context, authority, imageFile);
return sharedUri;
}
The URI it's correct, and now i open a camera intent like this>
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, result);
context.grantUriPermission(context.getPackageName(), result,
Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
context.startActivityForResult(takePictureIntent, BaseActivity.SUBACTIVITY_TAKE_PHOTO);
}
Then, camera it's opened, and when photo is taked and confirmed, i have:
01-10 15:37:27.236 W/FastPrintWriter: Write failure
java.io.IOException: write failed: EPIPE (Broken pipe)
at libcore.io.IoBridge.write(IoBridge.java:501)
at java.io.FileOutputStream.write(FileOutputStream.java:316)
at com.android.internal.util.FastPrintWriter.flushBytesLocked(FastPrintWriter.java:336)
at com.android.internal.util.FastPrintWriter.flushLocked(FastPrintWriter.java:359)
at com.android.internal.util.FastPrintWriter.flush(FastPrintWriter.java:394)
at android.view.ThreadedRenderer.dumpGfxInfo(ThreadedRenderer.java:613)
at android.view.WindowManagerGlobal.dumpGfxInfo(WindowManagerGlobal.java:556)
at android.app.ActivityThread$ApplicationThread.dumpGfxInfo(ActivityThread.java:1175)
at android.app.ApplicationThreadNative.onTransact(ApplicationThreadNative.java:577)
at android.os.Binder.execTransact(Binder.java:565)
Caused by: android.system.ErrnoException: write failed: EPIPE (Broken pipe)
at libcore.io.Posix.writeBytes(Native Method)
at libcore.io.Posix.write(Posix.java:273)
at libcore.io.BlockGuardOs.write(BlockGuardOs.java:319)
at libcore.io.IoBridge.write(IoBridge.java:496)
at java.io.FileOutputStream.write(FileOutputStream.java:316)
at com.android.internal.util.FastPrintWriter.flushBytesLocked(FastPrintWriter.java:336)
at com.android.internal.util.FastPrintWriter.flushLocked(FastPrintWriter.java:359)
at com.android.internal.util.FastPrintWriter.flush(FastPrintWriter.java:394)
at android.view.ThreadedRenderer.dumpGfxInfo(ThreadedRenderer.java:613)
at android.view.WindowManagerGlobal.dumpGfxInfo(WindowManagerGlobal.java:556)
at android.app.ActivityThread$ApplicationThread.dumpGfxInfo(ActivityThread.java:1175)
at android.app.ApplicationThreadNative.onTransact(ApplicationThreadNative.java:577)
at android.os.Binder.execTransact(Binder.java:565)
I have done all manifest changes required to use FileProvider and it was working a week ago..
Any idea?
context.grantUriPermission(context.getPackageName(), result,
Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
This code says "grant my own app permission to use my own app's data". This is not what you want. If you want to use grantUriPermission(), the package name needs to be for the app to whom you are granting permission.
Plus, there are simpler options on newer API levels:
i.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) {
i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
else if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN) {
ClipData clip=
ClipData.newUri(getContentResolver(), "A photo", outputUri);
i.setClipData(clip);
i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
else {
List<ResolveInfo> resInfoList=
getPackageManager()
.queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, outputUri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
}
Here, I:
Just use addFlags(), if the app is running on Android 5.0+
Use ClipData, if the app is running on Android 4.1-4.4
Iterate over all possible camera apps and grant the permission to each of them, on Android 4.0 and older
I cover that code snippet more in this blog post.
I am trying to edit an MSWord document from my app.
I decided to use an Intent to do this but MSWord can't seem to locate the document to edit. I'm not sure if I'm not correctly defining the location of the document, or if I'm not passing the uri correctly.
Intent intent = new Intent(Intent.ACTION_EDIT);
file = Environment.getExternalStorageDirectory().getPath()+"/mydoc.doc";
Uri uri = Uri.parse(file);
intent.setDataAndType(uri, "application/msword");
activity.startActivityForResult(intent, MSWORD);
The result I get is that MSWord launches and I get an error message:
"Can't open file"
"Try saving the file on the device and then opening it."
Documentation on MSWord and Intents seems to be very sparse!
At long last have found it - here for other frustrated developers!
File file = new File(Environment.getExternalStorageDirectory(),"Documents/101131new.docx");
Uri path = Uri.fromFile(file);
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
objIntent.setDataAndType(path,"application/msword");
activity.startActivity(objIntent);
This allows you to work on the local file in the /Documents directory.
Please try below:
/**
* #param fileRelativePath should be relative to SDCard
*/
private void launchMSWorldToOpenDoc(String fileRelativePath) {
File file = new File(Environment.getExternalStorageDirectory(), fileRelativePath);
Uri path = Uri.fromFile(file);
Intent msIntent = new Intent(Intent.ACTION_EDIT);
msIntent .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
msIntent .setDataAndType(path,"application/msword");
activity.startActivity(msIntent);
}
I try to create directory on Tablet and want to see it.
I create directory with this code
public void createDirectory(String sDirectoryName) {
File direct = getDir(sDirectoryName, Context.MODE_PRIVATE);
File fileWithinMyDir = new File(direct, "myfile");
if(!direct.exist()) {
System.out.println("Directory created");
}
else {
System.out.println("Directory not created");
}
}
I see everytime Directory created, But when I search Folder in file system, I can not see it. How can I make it visible. Am I making wrong?
EDIT:
I gave all permission on manifest. And I tried this code too
File direct = new File(Environment.getExternalStorageDirectory()+"/"+sDirectoryName);
if(!direct.exists())
{
if(direct.mkdir())
{
System.out.println("Directory created");
Toast.makeText(MainActivity.this, "Directory created", Toast.LENGTH_LONG).show();
}
else
{
System.out.println("Directory not created");
Toast.makeText(MainActivity.this, "Directory not created", Toast.LENGTH_LONG).show();
}
}
But this is not working for me too.
EDIT:
For refreshing I use this code.
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
working.
Note: because Android uses the MTP protocol for USB connections sometimes a file or folder just wont show because everything is cached and may need a refresh.
More info: Nexus 4 not showing files via MTP
File does not create a file if it doesn't exist. It just stores the path to it. Your if statement shows it doesn't exist.
Try this...
public void createDirectory(String sDirectoryName)
{
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), sDirectoryName);
if (!file.exists()) {
file.mkdirs();
}
}
Use below code to create directory.
public void createDirectory(String sDirectoryName) {
File direct = getDir(sDirectoryName, Context.MODE_PRIVATE);
File fileWithinMyDir = new File(direct, "myfile");
if(!direct.exist()) {
direct.mkdirs();
System.out.println("Directory created");
}
else {
System.out.println("Directory not created");
}
}
Add permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Make sure that your manifeist have the following permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And in code
File directory = new File(Environment.getExternalStorageDirectory()+DOC_FOLDER_NAME);
// create directory if not exists
if(!directory.exists())
{
if(directory.mkdirs()) //directory is created;
Log.i(" download ","App dir created");
else
Log.w(" download ","Unable to create app dir!");
}
To create a dir:
if(!direct.exist()) {
if (direct.mkdir())
Log.i(TAG, "Directory created");
else
Log.w(TAG, "Failed to create directory");
}
and don't forget permissions in your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Your print statement is confusing :
if(!direct.exist()) { // If directory does not exist
System.out.println("Directory created"); // Directory created not true
}
As just creating a File object it will not create directory the code should be:
if(!direct.exist()) { // If directory does not exist
direct.mkdir(); // Create directory
System.out.println("Directory created");
}
else {
System.out.println("Directory not created");
}
Also make sure to add android.permission.WRITE_EXTERNAL_STORAGE permission in your application.
Additionally its suggested not to use System.out.println in Android as On the emulator and most devices System.out.println gets redirected to LogCat and printed using Log.i(). This may not be true on very old or custom Android versions.
in manifest add this:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and this for java file:
File myDirectory = new File(Environment.getExternalStorageDirectory(), "dirName");
if(!myDirectory.exists()) {
myDirectory.mkdirs();
}
to delete it:
myDirectory.delete();
and this for File object for the parent directory:
//create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
Is the issue not on the line
File direct = getDir(sDirectoryName, Context.MODE_PRIVATE);
According to the documentation context.MODE_PRIVATE will only be visible within the app itself another program or user ID won't be able to find it.
try:
File direct = getDir(sDirectoryName, Context.MODE_WORLD_READABLE);
or
File direct = getDir(sDirectoryName, Context.MODE_WORLD_WRITEABLE);
http://developer.android.com/reference/android/content/Context.html