0

如果您决定扫描 QR 码(使用 zxing)并将其存储在私人存储中,我编写了以下代码,但如果您决定取消扫描,它会崩溃并且之前存储的文件内容会消失。

我认为这可能是一个设计错误,不知道为什么。

下面是相关代码

...

/**
 * 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();           
    }  
}
4

1 回答 1

1

您需要检查resultCode. 如果取消扫描,则没有关于条形码值的信息。使用resultCode可以检查操作是否成功。

if(resultCode == RESULT_OK) {
    // scan successful
} else {
    // no result
}
于 2012-11-25T11:00:55.713 回答