I am using zxing in a fragment of viewpager tab. I can call zxing with Intent and read the QR code but I can't get result to a edittext.
This is where i create tab in FragmentPagerAdapter:
@Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new Tab1();
case 1:
return new Tab2();
default:
return new EmptyTab();
}
}
And my Tab1 class:
public class Tab1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab_1, container, false);
IDEditText = (EditText) rootView.findViewById(R.id.fttx_id_editText);
Button scanBarcode = (Button) rootView.findViewById(R.id.scan_barcode);
scanBarcode.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity);
scanIntegrator.initiateScan();
}
});
return rootView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(
requestCode, resultCode, intent);
if (scanningResult != null) {
// we have a result
String scanContent = scanningResult.getContents();
IDEditText .setText("CONTENT: " + scanContent);
} else {
Toast.makeText(getActivity(),
"No scan data received!", Toast.LENGTH_SHORT).show();
}
}
zxing starts; then reads; then ends; but with no scan data: I think 'onActivityResult' never starts :(
How can i use zxing in this fragment?
IntentIntegrator
has another constructor, taking the Fragment. Instead of:
scanBarcode.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
scanIntegrator.initiateScan();
}
});
you can use:
scanBarcode.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
IntentIntegrator scanIntegrator = new IntentIntegrator(Tab1.this);
scanIntegrator.initiateScan();
}
});
and it should invoke onActivityResult
for the Fragment directly.
An example showing working usage of both starting the intent from an Activity and from a Fragment, with the barcode scanner installed, is demonstrated in this GitHub repo.
If you are using the v4 support library Fragments, the IntentIntegratorSupportV4
class provides compatibility:
IntentIntegrator scanIntegrator = new IntentIntegratorSupportV4(Tab1.this);