I'm new in android developing. I want create a File in my external SD Card. I searched a lot and tried different codes. But it created in device storage or it doesn't create at all. I get my SD Card path, it was in /mnt/extSdCard. I even tried several code, but non of them doesn't work. this code found my SD Card location:
public static String getExternalSdCardPath() {
String path = null;
File sdCardFile = null;
List<String> sdCardPossiblePath = Arrays.asList("external_sd", "ext_sd", "external", "extSdCard");
for (String sdPath : sdCardPossiblePath) {
File file = new File("/mnt/", sdPath);
if (file.isDirectory() && file.canWrite()) {
path = file.getAbsolutePath();
Log.i("LOG", "path is: " + path);
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
File testWritable = new File(path, "test_" + timeStamp);
if (testWritable.mkdirs()) {
testWritable.delete();
} else {
path = null;
}
}
}
if (path != null) {
sdCardFile = new File(path);
} else {
sdCardFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
}
return sdCardFile.getAbsolutePath();
}
path is my location.
You can use context.getApplicationContext().getExternalFilesDirs()
to get array of available string paths, including one which you want. But, it only available in Android 4.4+.
Here is how you use the code to set your path to the SD CARD if you do not have a SD CARD Android will just store data in INTERNAL STORAGE First declare this variable on the launch Activity
public static String THE_PATH;
Then in the same Activity in the onCreate Bundle call this method onAvail()
// Is External Storage Available if so use it and desi the path for DBHelper
public void onAvail() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED) &&
(!state.equals(Environment.MEDIA_MOUNTED_READ_ONLY))) {
File removable = ContextCompat.getExternalFilesDirs(this, null)[1];
THE_PATH = String.valueOf(removable);
//System.out.println("EXTERNAL PATH ====> " + THE_PATH);
THE_PATH = THE_PATH + "/Documents/";
//System.out.println("new path ====> "+THE_PATH);
}
}
I hope you have a DBHelper Class here is what happens in that Class
import static <app name here>.MainActivity.THE_PATH;
// Variable str is set in MainActivity as Public static
// to be accessible in the DBHelper Class
// which is called from MainAvtivity
public class DBHelper extends SQLiteOpenHelper {
public static final String DB_NAME = THE_PATH +"PassWord";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.