I know how to Write and Read data from External Storage, I don't know How to encrypt and decrypt this data to my external storage, so that whoever is trying to access that file using file explorer, It should be encrypted.
Here I have written the for storing and reading the data, for which I am using the buttons.
public class SOSActivity extends AppCompatActivity {
public EditText contact1;
Button saveButton, readButton;
private Context context;
public SharedPreferences.Editor editorcache;
private String filename = "SampleFile.txt";
private String filepath = "MyFileStorage";
File myExternalFile;
String myData = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sos);
context = this.getApplicationContext();
saveButton = (Button) findViewById(R.id.save);
contact1 = ((EditText) findViewById(R.id.contact1));
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(contact1.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
// response.setText("SampleFile.txt saved to External
// Storage...");
finish();
}
});
readButton = (Button) findViewById(R.id.read);
readButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
contact1.setText("");
try {
FileInputStream fis = new FileInputStream(myExternalFile);
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();
}
contact1.setText(myData);
// response.setText("SampleFile.txt data retrieved from Internal
// Storage...");
}
});
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
saveButton.setEnabled(false);
} else {
myExternalFile = new File(getExternalFilesDir(filepath), filename);
}
}
private static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
private static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
}