Reputation: 89
I'm trying to write a program that will need tot save to external storage. Right now I cant seem to save to the external storage.
I included the necessary permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
My code is a simple test for writing to external storage.
final Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String path = Environment.getExternalStorageDirectory() + "/Pictures/" + "test.jpg";
File file = new File(path);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
I have run this code on an emulator and a physical device. In neither case do I see a file saved to the Pictures Folder. Really need help with this.
Upvotes: 0
Views: 51
Reputation: 11090
Since Android M+ you need to request permission not only in Manifest but at runtime also
private void requestPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat
.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
//your permission was already granted then write to storage
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
// here you write to the storage for the first time
} else {
// Permission Denied
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Upvotes: 1