2012-11-25 44 views
0

我寫了下面的代碼,如果您決定掃描QR碼(使用zxing)並將其存儲在私人存儲空間中,但是如果您決定取消掃描,它會崩潰並且先前存儲的文件內容消失。android zxing intentintegrator

我認爲這可能是一個設計錯誤,不知道爲什麼。

下面是相關的代碼

... 

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

回答

1

您需要檢查resultCode。如果掃描被取消,則沒有關於條形碼值的信息。用resultCode你可以檢查操作是否成功。

if(resultCode == RESULT_OK) { 
    // scan successful 
} else { 
    // no result 
} 
+0

謝謝你,我現在意識到,我應該多看些書上的意圖,我看着intentintegrator.java和intentresult.java它搖鈴......再次感謝 –