I have been experimenting with writing to sdcard storage in my Android application (Target API 11)
I have been successful in creating the Directory in the following code called “BPAExp_data” but it does not create a new file at all. I’m stumped as to why since it does not show up in the logcat!!.
Here is my onCreate() method
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_logger);
String data = "asdfghjkl.."
//The filename of the log file
filename = getIntent().getExtras().getString("Filename");
//Save Test data button
Button saveData = (Button)findViewById(R.id.saveDataButton);
saveData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Save Data in file and go back to home screen
addtoKeyLogFile(data);
//Make intent for the Main Activity screen
Intent main_intent = new Intent(TextLogger.this, MainActivity.class);
startActivity(main_intent);
}
});
This is my method called addKeyLogFile()
public void addtoKeyLogFile(String data){
FileOutputStream f = null;
File data_file;
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/BPAExp_data");
dir.mkdirs();
data_file = new File(dir, filename);
f = new FileOutputStream(data_file);
// if file doesn't exists, then create it
if (!data_file.exists()) {
data_file.createNewFile();
Toast.makeText(TextLogger.this, "File GOT CREATED!", Toast.LENGTH_SHORT).show();
}
// get the content in bytes
byte[] dataInBytes = data.getBytes();
f.write(dataInBytes);
f.flush();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("TextLogger onCreate: ", e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.d("TextLogger onCreate: ", e.getMessage());
} finally {
try {
if (f != null) {
f.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have Located that the problem lies in or near the
f = new FileOutputStream(data_file);
because when I put a toast message after that it is never executed BUT if I put a toast before it, it is executed! Also the intent after that works perfectly fine!
But I do NOT understand, why is it not working?
Thanks for any help anyone can provide!
File has multiple constructors. One take as parameters a File and String:
What’s the value of filename ?
remove those lines:
File will be created when you stop writing the file.
you call it twice. Leave it only inside the finally block
All in all, are you sure that you have something to write?
is the length of
dataInBytes > 0?