如何从共享首选项的onActivityResult方法获取结果

时间:2016-02-12 08:55:17

标签: java android sharedpreferences onactivityresult

在qr扫描仪阅读器中,单击一个按钮后,它将打开相机并扫描结果。然后它将使用onactivityresult方法显示结果。 如何从onActivityResult方法获取结果,并在共享偏好中使用它?以下是我的代码:

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if (result != null) {
        String scanContent = result.getContents();
        customerSno.setText(" " + scanContent);
    } else {
        Toast.makeText(getApplicationContext(),"Cancelled", Toast.LENGTH_LONG).show();

2 个答案:

答案 0 :(得分:0)

将结果保存在SharedPreference

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("result", scanContent);
editor.commit();

SharedPreference

中检索
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String result = prefs.getString("result", "No saved result");

context是您的活动背景。如果此代码在任何活动中,请使用this

答案 1 :(得分:0)

     @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==IntentIntegrator.REQUEST_CODE){
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (result != null) {
                String scanContent = result.getContents();
                customerSno.setText(" " + scanContent);

                SharedPreferences prefs =  PreferenceManager.getDefaultSharedPreferences(this);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("result", scanContent);
                editor.commit();

            } else {
                Toast.makeText(getApplicationContext(),"Cancelled", Toast.LENGTH_LONG).show();
            }
        }
      }