Alex Hakman
Alex Hakman

Reputation: 62

Android studio - start QR code scanner from fragment

I have been looking for an answer all over the internet.

The thing is, i found many ways to implement a QR code scanner in my app, in an activity.

This is one of the ways:

        scan_btn = (Button) view.findViewById(R.id.scan_btn);
    scan_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            IntentIntegrator integrator = new IntentIntegrator(getActivity());
            integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
            integrator.setPrompt("Scan!!");
            integrator.setCameraId(0);
            integrator.setBeepEnabled(false);
            integrator.setBarcodeImageEnabled(false);
            integrator.initiateScan();
        }
    });    

Now i want to get it to work in a Fragment. The problem is, it starts a new activity (the QR code reader) Scans the QR code But i dont get a response in my onActivityResult:

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

    if (result != null) {
        if (result.getContents() == null) {
            System.out.println("Cancelled");
            Toast.makeText(getActivity(), "You cancelled the scanning!", Toast.LENGTH_LONG).show();
        } else {
            System.out.println("Worked: " + result.getContents());
            Toast.makeText(getActivity(), "scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

But what is going wrong?

I guess it has to do with this part:

  IntentIntegrator integrator = new IntentIntegrator(getActivity());       

It gets the activity, but it is a fragment, instead of an activity. How can i solve this problem?

Communicating first to my Activity which holds the fragment and then get the result ? Please help, Thanks :)

Upvotes: 1

Views: 4462

Answers (2)

Rahul Shinde
Rahul Shinde

Reputation: 29

IntentIntegrator intentIntegrator=
IntentIntegrator.forSupportFragment(FragmentNme.this);

It worked for me to solve my problem...rest all code is same.

Upvotes: 0

I will presume that the implementation of the onActivityResult is on your Fragment, right?

The IntentIntegrator implementation on your Fragment is right. So, just remove your onActivityResult code from the Fragment and put it on the Activity.

I had a similar problem and this was my solution.

Upvotes: 2

Related Questions