0

Hi I'm having a problem while making an app on Android Studio. I want the user to input some text and then click the save button, which should save the text file on my phone. I have the following code running without any errors, however it is not doing anything. I cant find the file that it is supposed to save in.

public class TakeNotes extends Activity implements View.OnClickListener {

String content = "";
File file;
FileOutputStream outputStream;
TextView tv;
Button btnSave;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.take_notes);
    tv = (TextView) findViewById(R.id.txtInput);
    btnSave = (Button) findViewById(R.id.btnSave);
    btnSave.setOnClickListener(this);

}

public void onClick(View v) {
    if (v == findViewById(R.id.btnSave)) {
        try {
            file = new File(Environment.getExternalStorageDirectory(), "test.txt");


            outputStream = new FileOutputStream(file);
            outputStream.write(content.getBytes());
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  }
}
JamesD
  • 13
  • 5
  • also have this permission in my manifest: – JamesD Apr 13 '17 at 12:41
  • https://stackoverflow.com/questions/32789157/how-to-write-files-to-external-public-storage-in-android-so-that-they-are-visibl https://stackoverflow.com/questions/32635704/android-permission-doesnt-work-even-if-i-have-declared-it – CommonsWare Apr 13 '17 at 12:44

2 Answers2

0

You should include permissions in your AndroidManifest :

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Johny
  • 625
  • 2
  • 6
  • 26
0

You need to add runtime permission in Android 6.0 (API Level 23) and up

This is the code for WRITE_EXTERNAL_STORAGE

if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
    Log.d(TAG,"Permission is granted");

    return true;
}

Ask for permission else like this

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);

Here is the official docs

Burhanuddin Rashid
  • 5,260
  • 6
  • 34
  • 51