How to create folder in android - 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.

Related

How to create a simple text file in SD card(/storage/emulated/0/Test/test.txt) from Native android code

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

Error in Folder Creation

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

How to set directory for sending files using Android Beam

I am working on an app that allows user to select a file from external storage and send it using Android Beam.
Here is the FileBrowser Activity to select a file from a directory and return the file name and directory path back to main activity:
public class FileBrowser extends Activity {
private String root;
private String currentPath;
private ArrayList<String> targets;
private ArrayList<String> paths;
private File targetFile;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_browser);
getActionBar().setDisplayHomeAsUpEnabled(true);
root = "/";
currentPath = root;
targets = null;
paths = null;
targetFile = null;
showDir(currentPath);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_file_browser, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void selectDirectory(View view) {
File f = new File(currentPath);
targetFile = f;
//Return target File to activity
returnTarget();
}
public void setCurrentPathText(String message)
{
TextView fileTransferStatusText = (TextView) findViewById(R.id.current_path);
fileTransferStatusText.setText(message);
}
private void showDir(String targetDirectory){
setCurrentPathText("Current Directory: " + currentPath);
targets = new ArrayList<String>();
paths = new ArrayList<String>();
File f = new File(targetDirectory);
File[] directoryContents = f.listFiles();
if (!targetDirectory.equals(root))
{
targets.add(root);
paths.add(root);
targets.add("../");
paths.add(f.getParent());
}
for(File target: directoryContents)
{
paths.add(target.getPath());
if(target.isDirectory())
{
targets.add(target.getName() + "/");
}
else
{
targets.add(target.getName());
}
}
ListView fileBrowserListView = (ListView) findViewById(R.id.file_browser_listview);
ArrayAdapter<String> directoryData = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, targets);
fileBrowserListView.setAdapter(directoryData);
fileBrowserListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int pos,long id) {
File f = new File(paths.get(pos));
if(f.isFile())
{
targetFile = f;
returnTarget();
//Return target File to activity
}
else
{
//f must be a dir
if(f.canRead())
{
currentPath = paths.get(pos);
showDir(paths.get(pos));
}
}
}
});
}
public void returnTarget()
{
Intent returnIntent = new Intent();
returnIntent.putExtra("file", targetFile);
returnIntent.putExtra("path", currentPath);
setResult(RESULT_OK, returnIntent);
finish();
}
}
Here is the code for MainActivity where the file returned by FileBrowser Activity is send using android beam:
public class MainActivity extends Activity {
private NfcAdapter nfcAdapter;
public final int fileRequestID = 98;
String name;
String[] extension={".png",".docx",".jpeg",".pdf",".doc"};
ArrayList <String>supportedExtension=new ArrayList<String>(Arrays.asList(extension));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PackageManager pm = this.getPackageManager();
// Check whether NFC is available on device
if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC)) {
// NFC is not available on the device.
Toast.makeText(this, "The device does not has NFC hardware.",
Toast.LENGTH_SHORT).show();
}
// Check whether device is running Android 4.1 or higher
else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
// Android Beam feature is not supported.
Toast.makeText(this, "Android Beam is not supported.",
Toast.LENGTH_SHORT).show();
}
else {
// NFC and Android Beam file transfer is supported.
Toast.makeText(this, "Android Beam is supported on your device.",
Toast.LENGTH_SHORT).show();
}
}
public void browseForFile(View view) {
Intent clientStartIntent = new Intent(this, FileBrowser.class);
startActivityForResult(clientStartIntent, fileRequestID);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//fileToSend
boolean filePathProvided;
File fileToSend;
if (resultCode == Activity.RESULT_OK && requestCode == fileRequestID) {
//Fetch result
File targetDir = (File) data.getExtras().get("file");
String path = (String)data.getExtras().get("path");
Log.i("Path=",path);
if(targetDir.isFile())
{
if(targetDir.canRead()) {
try{
String ext=targetDir.getName().substring(targetDir.getName().lastIndexOf("."));
if (supportedExtension.contains(ext)) {
fileToSend = targetDir;
filePathProvided = true;
setTargetFileStatus(targetDir.getName() + " selected for file transfer");
Button btn = (Button) findViewById(R.id.send);
btn.setVisibility(View.VISIBLE);
name = targetDir.getName();
}
else{
Toast.makeText(getApplicationContext(), "File with this extension cannot be printed",
Toast.LENGTH_LONG).show();
}
}catch (Exception e){e.printStackTrace();}
}
else
{
filePathProvided = false;
setTargetFileStatus("You do not have permission to read the file " + targetDir.getName());
}
}
else
{
filePathProvided = false;
setTargetFileStatus("You may not transfer a directory, please select a single file");
}
}
}
public void setTargetFileStatus(String message)
{
TextView targetFileStatus = (TextView) findViewById(R.id.selected_filename);
targetFileStatus.setText(message);
}
public void sendFile(View view) {
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
// Check whether NFC is enabled on device
if(!nfcAdapter.isEnabled()){
Toast.makeText(this, "Please enable NFC.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
}
else if(!nfcAdapter.isNdefPushEnabled()) {
Toast.makeText(this, "Please enable Android Beam.",
Toast.LENGTH_SHORT).show();
startActivity(new Intent(Settings.ACTION_NFCSHARING_SETTINGS));
}
else {
Uri[] mFileUris = new Uri[1];
String fileName=name;
// Retrieve the path to the user's public pictures directory
File fileDirectory = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File fileToTransfer;
fileToTransfer = new File(fileDirectory, fileName);
fileToTransfer.setReadable(true, false);
mFileUris[0] = Uri.fromFile(fileToTransfer);
nfcAdapter.setBeamPushUris(mFileUris, this);
}
}
}
Now, as you can see in my MainActivity, I am setting my directory as Pictures.
File fileDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
My question is How can I dynamically change my directory every time based on the actual directory value obtained from FileBrowser Activity?
I have already went through the android documentation of How to send files using Android Beam, but didn't find it much useful for my problem. I also went through the android documentation of Environment, but couldn't understand much.
Any help regarding this will really be appreciated. Thanks in advance!
You already have the file selected in OnActivityResult method. Just change
mFileUris[0] = Uri.fromFile(fileToTransfer);
to
mFileUris[0] = Uri.fromFile(targetDir);

How open choose directory dialog on Android java?

My app downloads files from the internet and I need the user to select where to save them. How to make a choice directory on the Android Java? Please give example code
You just need to override onCreateDialog in an activity like this:
//In an Activity
private String[] mFileList;
private File mPath = new File(Environment.getExternalStorageDirectory() + "//yourdir//");
private String mChosenFile;
private static final String FTYPE = ".txt";
private static final int DIALOG_LOAD_FILE = 1000;
private void loadFileList() {
try {
mPath.mkdirs();
}
catch(SecurityException e) {
Log.e(TAG, "unable to write on the sd card " + e.toString());
}
if(mPath.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
return filename.contains(FTYPE) || sel.isDirectory();
}
};
mFileList = mPath.list(filter);
}
else {
mFileList= new String[0];
}
}
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
switch(id) {
case DIALOG_LOAD_FILE:
builder.setTitle("Choose your file");
if(mFileList == null) {
Log.e(TAG, "Showing file picker before loading the file list");
dialog = builder.create();
return dialog;
}
builder.setItems(mFileList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mChosenFile = mFileList[which];
//you can do stuff with the file here too
}
});
break;
}
dialog = builder.show();
return dialog;
}
Check this out :
small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: https://github.com/iPaulPro/aFileChooser
For More Details:
Android file chooser

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

Categories

Resources