I spent hours trying to solve this problem and got nowhere! I am trying to save magnetometer data to csv file. I am using FastCSV library. Initially I used getExternalStoragePublicDirectory to save the file to the Downloads directory in my phone.
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "magnetic" + value + ".csv");
But since its been depreciated I used
File file = new File(context.getExternalFilesDir(DIRECTORY_DOWNLOADS), "magnetic" + value + ".csv");
I get a toast message saying that my file is saved in the memory but I cannot find them when I look for them in my phone's Download location. Instead they are stored in my phone's Android directory.
Here's the code:
private int REQUEST_CODE = 1;
private View.OnClickListener listenerStopButton = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(recording == true)
{
recording = false;
counter = 0;
String value = fileIDEdit.getText().toString();
stateText.setText("Recording Stopped");
stateText.setTextColor(Color.parseColor("#0000FF"));
if (storagePermitted((Activity) context)){
csvWriter = new CsvWriter();
File file = new File(context.getExternalFilesDir(DIRECTORY_DOWNLOADS), "magnetic" + value + ".csv");
//File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "magnetic" + value + ".csv");
try {
csvWriter.write(file, StandardCharsets.UTF_8, magneticData);
Toast.makeText(MainActivity.this, "File is recorded in memory.", Toast.LENGTH_LONG).show();
} catch (IOException io) {
Log.d("Error", io.getLocalizedMessage());
}
}
}
else{
Toast.makeText(MainActivity.this, "Nothing to save. Recording was not started.", Toast.LENGTH_LONG).show();
}
}
};
@Override
protected void onResume(){
super.onResume();
sensorManager.registerListener(this, magnetic, SensorManager.SENSOR_DELAY_FASTEST);
}
This code checks for permission:
private static boolean storagePermitted(Activity activity){
// Check read write permission
Boolean readPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
Boolean writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
if (readPermission && writePermission){
return true;
}
ActivityCompat.requestPermissions(activity, new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUESTCODE_STORAGE_PERMISSION);
return false;
}
Please let me know how can I use getExternalFilesDir() to save the file to Downloads directory!