Search code examples
androidandroid-fragmentsbarcodezxingandroid-fragmentactivity

Can't access onActivityResult zxing for fragment


I'am trying to read the barcode via Zxing in fragment

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_caddie, container, false);
    etCodigo = v.findViewById(R.id.etCodigo);
    btnLeerCodigo = v.findViewById(R.id.btnLeerCodigo);

    btnLeerCodigo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            escanear();
        }
    });
    text = "";

    return v;
}


public void escanear() {

    IntentIntegrator intent = IntentIntegrator.forSupportFragment(FragmentCaddie.this);
    //IntentIntegrator intent = new IntentIntegrator(getActivity());
    intent.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
    intent.setPrompt("ESCANEAR CODIGO");
    intent.setCameraId(0);
    intent.setBeepEnabled(false);
    intent.setBarcodeImageEnabled(false);
    intent.initiateScan();

}


 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);

    if(result != null) {
        if(result.getContents() == null) {
            Toast.makeText(getContext(), "Cancelaste el escaneo", Toast.LENGTH_SHORT).show();
        } else {
            text = text + " + " +  result.getContents().toString() ;
            etCodigo.setText(text);
            escanear();
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

The issue is it doesn't access the onActivityResult


Solution

  • The solution was quiet simple the onActivityResult that i implemented was Overrided from the parent activity

    The solution is to call the fragment onActivityResult from the parent activity

    private static final int BARECODE_REQUEST = 114910;
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {     
    
        if (requestCode == BARECODE_REQUEST) {
            super.onActivityResult(requestCode,resultCode,data);
        }
    }