0

I wrote this to store a file in SD card, but it's not working.

public class TestarFilesActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        File root = Environment.getExternalStorageDirectory();

        try {
            if (root.canWrite()) {
                File file = new File(root, "agora.txt");
                FileWriter fwriter = new FileWriter(file);
                BufferedWriter out = new BufferedWriter(fwriter);
                out.write("Hello world");
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }TestarFilesActivity.this.finish();
    }
}

How is this problem caused and how can I solve it? I think it's everything right and I have write the permission in the manifest too.

Blizzer
  • 260
  • 4
  • 22
Ricardo
  • 121
  • 1
  • 2
  • 11

2 Answers2

2

if you run this application in android emulator you have to prepare sdcard through DevTools Terminal Emulator and check sdcard directory using linux command as $ls and allow to sdcard if not available prepare it and try the following

File file = new File(root, "/sdcard/agora.txt");
FileWriter fwriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fwriter);
out.write("Hello world");
out.close();

//Use this in manifest.xml  
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Blizzer
  • 260
  • 4
  • 22
prasad.gai
  • 2,977
  • 10
  • 58
  • 93
0

Have you given write permission on sdcard in your AndroidManifest.xml?

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Aneeq Anwar
  • 1,282
  • 7
  • 20