Reputation: 121
I'm trying to write an app for Android and I need to save the resposne from a server, I managed to do it by saving it in a txt file in this path:
String path= "/storage/emulated/0/Android/data/com.example.simone.pizzino/files/response.txt";
final File file = new File(path);
Testing it on my friend's phone he can't see the folder at that path, his path is something like data/data/"packageName"
, it doesnt work on the emulator in Android Studio either.
My phone is a Nexus 5X running 7.1 stock rom.
My friend is rooted using 6.1.
Is there some way to get a dynamic path to the application folder without having to state it as a constant?
Sorry if this question was already asked but I counldn't find a solution for my problem.
Upvotes: 2
Views: 18799
Reputation: 143
First thing you have to do is to add permission to access external storage in your manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Save a File on Internal Storage
File file = new File(context.getFilesDir(), filename);
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
public File getTempFile(Context context, String url) {
File file;
try {
String fileName = Uri.parse(url).getLastPathSegment();
file = File.createTempFile(fileName, null, context.getCacheDir());
} catch (IOException e) {
// Error while creating file
}
return file;
}
Save a File on External Storage
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
Upvotes: 5