I've written the following code that works fine if you decide to scan a QR code (using zxing) and store it in private storage but in case you decide to cancel scanning, it crashes and the file previously stored content disappears.
I think it might be a design error, not sure why.
Below is relevant code
...
/**
* menu generation
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
/**
* menu handling
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "", Toast.LENGTH_LONG);
toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0);
switch (item.getItemId()) {
case R.id.qrScan:
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.initiateScan();
return true;
case R.id.qrReset:
File dir = getFilesDir();
File file = new File(dir, qrCodeFile);
boolean deleted = file.delete();
return true;
case R.id.appClose:
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
...
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
if (scanResult != null) {
FileOutputStream fos = null;
CharSequence text = scanResult.getContents();
try {
fos = openFileOutput(qrCodeFile, Context.MODE_PRIVATE);
try {
fos.write(text.toString().getBytes());
fos.close();
toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0);
toast.setText("Code saved");
toast.show();
} catch (IOException ex) {
toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0);
toast.setText("Invalid code");
toast.show();
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0);
toast.setText("Error while saving");
toast.show();
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0);
toast.setText("Invalid code");
toast.show();
}
}