val filePath = getString(R.string.file_path)
val file = File(filePath)
var lines: List<String?> = ArrayList()
if(!file.exists()) {
try {
if (Environment.getExternalStorageState()==Environment.MEDIA_MOUNTED) {
file.createNewFile()
}
} catch (e: IOException) {
AlertDialog.Builder(this)
.setTitle(getString(R.string.No_records_file))
.setMessage(getString(R.string.cant_create_file))
.setNeutralButton(
R.string.Exit
) { dialog, id -> finish() }.show()
}
}
It works on Android 8.0.0, 9.0 . I am not sure about android, but this problem appeared on Mi9T pro
With Android Q, you can no longer directly access to the file system. Use the SAF (Storage Access Framework) instead.
First add this rules;
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Ask permissions from activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//ASK HERE...
if (shouldAskPermissions()) {
askPermissions();
}
}
-
//// ASK METHODS
protected boolean shouldAskPermissions() {
return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}
protected void askPermissions() {
String[] permissions = {
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE"
};
int requestCode = 200;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissions, requestCode);
}
}
then for create file use this code;
File directory = new File(Environment.getExternalStorageDirectory()+java.io.File.separator +"AppName");
try{
if(!directory.exists()) {
System.out.println("Directory created");
directory.mkdirs();
} else {
System.out.println("Directory is not created");
}
File f = new File(directory.getPath()+"/"+ "ENTER_FILE_NAME" + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
System.out.println("FILE PATH:" + f.getPath());
}catch(Exception e){
e.printStackTrace();
}
on Android API 29, getExternalStorageDirectory is deprecated, you should use getExternalFilesDir instead.
Related
I try to make 'File Control' app.
I found how to read file, but I can't find how to write file.
I set permission like this.
AndroidManifast.xml
<application
...
android:requestLegacyExternalStorage="true"
...
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<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"/>
and i call this code in MainActivity.onCreate.
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MODE_PRIVATE);
verifyStoragePermissions(this);
I want read and write file, at /storage/3066-3133/title.txt . /storage/3066-3133 is my sdcard path.
read file is work perfectly.
public void readFile() {
String fileTitle = "title.txt";
File file = new File("/storage/3066-3133", fileTitle);
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String result = "";
String line;
while ((line = reader.readLine()) != null) {
result += line;
}
popupToast("read : " + result);
reader.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
popupToast("no file found");
} catch (IOException e2) {
e2.printStackTrace();
popupToast("read fail");
}
}
but write code occur exception.
write Exception: /storage/3066-3133/title.txt: open failed: EACCES (Permission denied)
public void writeFile() {
String fileTitle = "title.txt";
File file = new File("/storage/3066-3133", fileTitle);
try {
if (!file.exists()) {
file.createNewFile(); // error!!!!
}
FileWriter writer = new FileWriter(file, false);
String str = " write text ";
writer.write(str);
writer.close();
} catch (IOException e) {
e.printStackTrace();
popupToast("write fail");
}
}
Plus, I can write file at /storage/emulated/0/title.txt. /storage/emulated/0 is bullt-in external storage path.
I need more permission for sdcard?
or this is problem? First, i create project for target sdk:31. and i change 29 in build.gradle. changing target sdk is not work? Someone tell sdk 30 little changed. but, if this is problem, i can't understand then why 'read' work...
USE
uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
in your manifest along with
android:requestLegacyExternalStorage="true" in your <application/>
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"/>
I want to download file from google drive for which I am using dependency that is compile 'com.google.android.gms:play-services:8.4.0' and using this I am able to get link from meta data from below example.
mFileId = (DriveId) data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
final DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, mFileId);
new Thread(new Runnable() {
#Override
public void run() {
// DO your work here
DriveResource.MetadataResult mdRslt = file.getMetadata(mGoogleApiClient).await();
if (mdRslt != null && mdRslt.getStatus().isSuccess()) {
String link = mdRslt.getMetadata().getWebContentLink();
String name=mdRslt.getMetadata().getTitle();
Log.d("LINK", link);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && getApplication().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
else
{
new get_download_data(link,name).execute();
}
}
}
}).start();
}
After getting the link from Google Drive, I am calling async task to download that file from link. So my problem is when I am downloading file, it's not opening. After checking and debugging, I found that my files was not downloading properly.
For example, I have file name abc.pdf and the size is 400kb. I downloaded on my sdcard but abc.pdf is 56 kb only. I am using below code for downloading. I don't know where I was doing wrong. Please help. Thanks.
public class get_download_data extends AsyncTask<Void,Void,String>
{
File apkStorage = null;
File outputFile = null;
String link1="";
String name1="";
public get_database_data(String link, String name) {
this.link1=link;
this.name1=name;
}
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(link1);//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.setDoInput(true);
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());
}else{
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.getExternalStorageDirectory() + "/"
+ "checkdb");
} else
Toast.makeText(getApplication(), "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, name1);//Create Output file in Main File
//Create New File if not present
if (!outputFile.exists()) {
outputFile.createNewFile();
Log.e(TAG, "File Created");
}
OutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
InputStream is = c.getInputStream();//Get InputStream for connection
BufferedInputStream inStream = new BufferedInputStream(is, 1024);
byte[] buffer = new byte[1024];//Set buffer type
int len1 = 0;//init length
while ((len1 = inStream.read(buffer)) != -1) {
fos.write(buffer, 0, len1);//Write new file
}
//Close all connection after doing task
fos.flush();
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;
}
#Override
protected void onPostExecute(String result_1) {
super.onPostExecute(result_1);
String downlodepath = Environment.getExternalStorageState()+"/"+name1;
Log.e("Sdpath",""+imagePath);
Toast.makeText(getApplication(), "download"+downlodepath, Toast.LENGTH_SHORT).show();
}
}
I found this link here but some how I don't have idea how to implement this. Please let me know where I was wrong. Thanks.
After some work around and trying so many examples, I found the answer for this.
Here are the dependencies which I have added in my project:
compile 'com.google.android.gms:play-services-auth:11.8.0'
compile 'com.google.android.gms:play-services-drive:11.8.0'
Here is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_api_key" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
Here is my MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ActivityMainBinding binding;
private static final String TAG = "Google drive";
private static final String SIGN_IN = "Sign In";
private static final String DOWNLOAD_FILE = "Download file";
private static final int REQUEST_CODE_SIGN_IN = 0;
private static final int REQUEST_CODE_OPEN_ITEM = 1;
private static final int REQUEST_WRITE_STORAGE = 112;
private GoogleSignInAccount signInAccount;
private Set<Scope> requiredScopes;
private DriveClient mDriveClient;
private DriveResourceClient mDriveResourceClient;
private OpenFileActivityOptions openOptions;
private TaskCompletionSource<DriveId> mOpenItemTaskSource;
private File storageDir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
initialize();
requestPermission();
signInAccount = GoogleSignIn.getLastSignedInAccount(this);
binding.btnSubmit.setOnClickListener(this);
if (signInAccount != null && signInAccount.getGrantedScopes().containsAll(requiredScopes)) {
initializeDriveClient(signInAccount);
binding.btnSubmit.setText(DOWNLOAD_FILE);
} else {
binding.btnSubmit.setText(SIGN_IN);
}
}
private void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SIGN_IN:
if (resultCode == RESULT_OK) {
Task<GoogleSignInAccount> getAccountTask = GoogleSignIn.getSignedInAccountFromIntent(data);
if (getAccountTask.isSuccessful()) {
initializeDriveClient(getAccountTask.getResult());
showMessage("Sign in successfully.");
binding.btnSubmit.setText(DOWNLOAD_FILE);
} else {
showMessage("Sign in failed.");
}
} else {
showMessage("Sign in failed.");
}
break;
case REQUEST_CODE_OPEN_ITEM:
if (resultCode == RESULT_OK) {
DriveId driveId = data.getParcelableExtra(OpenFileActivityOptions.EXTRA_RESPONSE_DRIVE_ID);
mOpenItemTaskSource.setResult(driveId);
} else {
mOpenItemTaskSource.setException(new RuntimeException("Unable to open file"));
}
break;
}
}
private void initialize() {
requiredScopes = new HashSet<>(2);
requiredScopes.add(Drive.SCOPE_FILE);
requiredScopes.add(Drive.SCOPE_APPFOLDER);
openOptions = new OpenFileActivityOptions.Builder()
.setSelectionFilter(Filters.eq(SearchableField.MIME_TYPE, "application/pdf"))
.setActivityTitle("Select file")
.build();
}
private void initializeDriveClient(GoogleSignInAccount signInAccount) {
mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);
mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.btnSubmit) {
String text = (String) ((Button) view).getText();
if (text.equals(SIGN_IN)) {
signIn();
} else {
onDriveClientReady();
}
}
}
private void signIn() {
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.requestScopes(Drive.SCOPE_APPFOLDER)
.build();
GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
private void onDriveClientReady() {
mOpenItemTaskSource = new TaskCompletionSource<>();
mDriveClient.newOpenFileActivityIntentSender(openOptions)
.continueWith(new Continuation<IntentSender, Void>() {
#Override
public Void then(#NonNull Task<IntentSender> task) throws Exception {
startIntentSenderForResult(
task.getResult(), REQUEST_CODE_OPEN_ITEM, null, 0, 0, 0);
return null;
}
});
Task<DriveId> tasks = mOpenItemTaskSource.getTask();
tasks.addOnSuccessListener(this,
new OnSuccessListener<DriveId>() {
#Override
public void onSuccess(DriveId driveId) {
retrieveContents(driveId.asDriveFile());
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showMessage("File not selected.");
}
});
}
private void retrieveContents(final DriveFile file) {
// [START open_file]
final Task<DriveContents> openFileTask = mDriveResourceClient.openFile(file, DriveFile.MODE_READ_ONLY);
// [END open_file]
// [START read_contents]
openFileTask.continueWithTask(new Continuation<DriveContents, Task<Void>>() {
#Override
public Task<Void> then(#NonNull Task<DriveContents> task) throws Exception {
DriveContents contents = task.getResult();
Log.v(TAG, "File name : " + contents.toString());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
InputStream input = contents.getInputStream();
try {
File file = new File(getExternalFilesDir(null), "umesh.pdf");
Log.v(TAG, storageDir + "");
OutputStream output = new FileOutputStream(file);
try {
try {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
showMessage("Download file successfully.");
return mDriveResourceClient.discardContents(contents);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showMessage("Unable to download file.");
}
});
// [END read_contents]
}
private void requestPermission() {
String dirPath = getFilesDir().getAbsolutePath() + File.separator + "PDF";
storageDir = new File(dirPath);
if (!storageDir.exists())
storageDir.mkdirs();}}
And here is the string file for the API key:
<resources>
<string name="app_name">GoogleDriveDemo</string>
<string name="google_api_key">"your-key"</string>
</resources>
The way I use webContentLink when downloading a file in Drive API is to open a new browser window in Javascript.
var webcontentlink = 'https://docs.google.com/a/google.com/uc?id='+fileId+'&export=download'
window.open( webcontentlink);
I'd suggest you do that in Android like the one mentioned in this post:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(webcontentlink));
startActivity(browserIntent);
For someone who still stuck in this problem.
Somehow the download URL cannot be returned right after driveResourceClient.createFile()
driveResourceClient?.createFile(appFolder, metadataChangeSet, contents)
}?.addOnSuccessListener(this
) { driverFile -> //we cannot get webContentLink here }
At this time we can only get the file name (this one may already defined)
In my case, I don't really need the URL right after upload but when user click a copy URL button
driveResourceClient?.query(Query.Builder()
.addFilter(Filters.eq(SearchableField.TITLE, sharedFileName))
.build())
?.addOnSuccessListener {
url = it.first().webContentLink
}
?.{
}
I've just success with this.
You can easily do that using chrome custom tabs just paste the url in the custom tabs and it will show the drive website and one can download the file
Refer this official documentation for chrome custom tabs https://developer.chrome.com/multidevice/android/customtabs it's an really superb feature and a best alternative for webview
Simplest way to download a file through Google Drive URL in Android is by navigating to browser. In this way we can download any data like .apk, .mp4, .txt..
In kotlin
val driveIntent = Intent(Intent.ACTION_VIEW, Uri.parse(DRIVE_URL))//Link can have any data link .apk, .mp4 ..
val browserChooserIntent = Intent.createChooser(driveIntent, "Choose browser")
startActivity(browserChooserIntent)
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 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.