onActivityResult没有调用Fragment'

时间:2016-06-29 07:13:47

标签: android android-fragments

您好我是Android的新手,在我的应用程序中我使用Z-bar库扫描条码。

为此,我正在使用如下所示的ZbarScannerActivity类,因此在扫描条形码后,我将使用onActivityResult方法得到那些条形码结果。

这里我的问题是当我扫描条形码时我想在我的片段中得到这个结果,但是这里onActivityResult没有在我的片段中调用。 但它在我的活动中打电话请帮助我。

我该如何解决这个问题?

ZbarScanner活动: -

public class ZBarScannerActivity extends ActionBarActivity {

    private Camera mCamera;
    private CameraPreview mPreview;
    private Handler autoFocusHandler;
    ImageScanner scanner;
    ImageView backButton;
    private boolean barcodeScanned = false;
    private boolean previewing = true;
    CustomTextview navigation_title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scanner_view_layout);
        ActionBar actionBar = getSupportActionBar();
        String header = "<font color=\"#ffffff\">" + "BarCode Scanner"
                + " </font>";
        CommonUtils.actionbarHeader(this, actionBar, header);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        autoFocusHandler = new Handler();
        mCamera = getCameraInstance();

        /* Instance barcode scanner */
        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);

        mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
        FrameLayout preview = (FrameLayout) findViewById(R.id.cameraPreview);
        preview.addView(mPreview);

        navigation_title = (CustomTextview)findViewById(R.id.navigationTitle_id);
        navigation_title.setText("Barcode Scanner");

        backButton = (ImageView)findViewById(R.id.navigationbackbutton_id);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });
    }

    static {

        System.loadLibrary("iconv");
    }

    public void onPause() {
        super.onPause();
        releaseCamera();
    }

    /** A safe way to get an instance of the Camera object. */
    public static Camera getCameraInstance() {
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e) {
        }
        return c;
    }

    private void releaseCamera() {
        if (mCamera != null) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }
    }

    private Runnable doAutoFocus = new Runnable() {
        public void run() {
            if (previewing)
                mCamera.autoFocus(autoFocusCB);
        }
    };

    PreviewCallback previewCb = new PreviewCallback() {

        public void onPreviewFrame(byte[] data, Camera camera) {
            Camera.Parameters parameters = camera.getParameters();
            Size size = parameters.getPreviewSize();

            Image barcode = new Image(size.width, size.height, "Y800");
            barcode.setData(data);

            int result = scanner.scanImage(barcode);

            if (result != 0) {
                previewing = false;
                mCamera.setPreviewCallback(null);
                mCamera.stopPreview();

                SymbolSet syms = scanner.getResults();
                for (Symbol sym : syms) {

                    System.out.println("------->"+sym.getData());
                    barcodeScanned = true;
                    finishActivivtyWithResult(sym.getData());
                }
            }
        }
    };

    // Mimic continuous auto-focusing
    AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
        public void onAutoFocus(boolean success, Camera camera) {
            autoFocusHandler.postDelayed(doAutoFocus, 1000);
        }
    };

    /**
     *
     * @param barCodeResult
     */
    private void finishActivivtyWithResult(String barCodeResult){

        if (barCodeResult.contains("//b")) {

            String replacedString = barCodeResult.replace("//b", "");
            System.out.println("One========>" + replacedString);
            barCodeResult = replacedString;
        }
        if (barCodeResult.contains("/t")) {

            String replacedString = barCodeResult.replace("/t", "-");
            System.out.println("After========>" + replacedString);
            barCodeResult = replacedString;
        }

        Bundle conData = new Bundle();
        conData.putString("barCodeResult", barCodeResult);
        Intent intent = new Intent();
        intent.putExtras(conData);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public boolean onSupportNavigateUp() {

        finish();
        return true;
    }
}

我的片段: -

 //Camera Button Action Event:-

    /**
     * @return
     */
    private View.OnClickListener cameraDetails() {

        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                BAR_CODE_SCANNER_CODE = 100;
                checkCameraPermission();

            }
        };
    }

    //BarCode Scanner Result:-

    private void checkCameraPermission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            checkManifestPermissionSets();
        } else {

            scanProductCode();
        }
    }

    @TargetApi(23)
    private void checkManifestPermissionSets() {

        int cameraPermission = ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.CAMERA);

        List<String> permissions = new ArrayList<String>();

        if (cameraPermission != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.CAMERA);
        }

        if (!permissions.isEmpty()) {
            requestPermissions(
                    permissions.toArray(new String[permissions.size()]),
                    REQUEST_CODE_SOME_FEATURES_PERMISSIONS);

        } else {

            scanProductCode();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {

            case REQUEST_CODE_SOME_FEATURES_PERMISSIONS: {

                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        //Log.d("Permissions", "Permission Granted: "+ permissions[i]);
                        scanProductCode();
                        break;
                    } else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {

                        //Log.d("Permissions", "Permission Denied: " + permissions[i]);
                        //CommonUtils.showToastMessage(StockTransfer.this, "You've disabled the App required Permissions");
                        break;
                    }
                }
            }

            break;
            default: {
                super.onRequestPermissionsResult(requestCode, permissions,
                        grantResults);
            }
        }
    }


    private void scanProductCode() {

        if (isCameraAvailable()) {

            CommonUtils.showToastMessage(getActivity(),
                    "Please Scan Your Product BarCode");

            callThreadScannerActivity();

        } else {
            Toast.makeText(getActivity(), "Rear Facing Camera Unavailable",
                    Toast.LENGTH_SHORT).show();
        }
    }

    private void callThreadScannerActivity() {

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // dialog.dismiss();
                callScannerActivity();
            }
        }, 700);
    }


    // Call Scanner Activity:-

    private void callScannerActivity() {

        Intent intent = new Intent(getActivity(), ZBarScannerActivity.class);
        startActivityForResult(intent, BAR_CODE_SCANNER_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        System.out.println("result code------>" + requestCode);
    }

    private boolean isCameraAvailable() {

        PackageManager pm = getActivity().getPackageManager();
        return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
    }
}

2 个答案:

答案 0 :(得分:2)

与一般生活相关的简单逻辑

  

活动:父亲(父母)

     

片段:孩子

如果child想要钱而不是他要求他/她的父亲。

技术方式如果片段(子)想要来自onActivityResult it always VIA Activity(father)的数据。

ohk ..让我们看看代码方面

的东西
  

yourActivity(Parent)

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {

        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments != null) {
            for (Fragment fragment : fragments) {
                fragment.onActivityResult(requestCode, resultCode, data);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

这个活动的片段(孩子)名单对他说活动(父亲)数据

当活动收到数据时,它会以片段(孩子)的要求提供。

答案 1 :(得分:0)

在片段中,每当我们为任何结果开始活动然后在活动的onActivityResult中收到该结果时,我们必须将此结果传递给片段的onActivityResult 将此内容写入您的活动的onActivityResult

  @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Logg.e("RESULT ", " " + resultCode);
    if (resultCode != RESULT_OK)
        return;
    switch (requestCode) {
        case 100:
            Fragment YourRfargment= getFragmentManager().findFragmentByTag("Your Fragment TAG");
            updateproFragment.onActivityResult(requestCode, resultCode, data);
            break;
          }    
     }

通过这个你将得到你的结果片段的onActivityresult。