Reputation: 147
I'm trying to write/read the external storage, after reading some questions here and on internet, exmeple etc.
But i have problem in creating file in the SD, and it doesn't creates and loads, and the mkdirs
give me the error that it will be ignored:
public EditText et;
public Button buttonSave,buttonLoad;
public TextView tv;
public String myData = "";
public File root = android.os.Environment.getExternalStorageDirectory();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
et = findViewById(R.id.inserimento);
buttonSave = findViewById(R.id.save);
buttonLoad = findViewById(R.id.load);
tv = findViewById(R.id.tv);
File dir = new File(root.getAbsolutePath() + "/eliminaCoda");
dir.mkdirs();
final File file = new File(dir, "Lista.txt");
buttonSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
FileOutputStream fos = new FileOutputStream(file,true);
fos.write(et.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
et.setText("");
}
});
buttonLoad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
FileInputStream fis = new FileInputStream(file);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
tv.setText(myData);
}
});
}
Upvotes: 0
Views: 298
Reputation: 205
You have to add write uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" in AndroidManifest.xml file. Also, you have to request for runtime permission.
Please check this demo for runtime permission Runtime Permissions in Marshmallow
Upvotes: 1