Good day, I'm trying to get the result of scanning the QR code in the fragment, as activity everything works, but after the transfer the result cannot be obtained. How can this be fixed?
As I understood the problem in the "onActivityResult" method. I need to some information for solution. how can change it for the fragment ?
My Code is below line:
public class Fragment_qr extends Fragment implements View.OnClickListener {
private Button btnScanQRCode;
private TextView txtFruit, txtSize, txtColor;
//QR Code Scanner Object
private IntentIntegrator qrScan;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.qr_code_scan_layout, null);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
btnScanQRCode = (Button) view.findViewById(R.id.btnScanQRCode);
txtFruit = (TextView) view.findViewById(R.id.txtFruitName);
txtSize = (TextView) view.findViewById(R.id.txtFruitSize);
txtColor = (TextView) view.findViewById(R.id.txtFruitColor);
//Initialize the Scan Object
qrScan = new IntentIntegrator(getActivity());
//OnClickListener Attached to the Button
btnScanQRCode.setOnClickListener(this);
}
//Getting the scan results
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
//Check to see if QR Code has nothing in it
if (result.getContents() == null) {
Toast.makeText(getActivity(), "Result Not Found", Toast.LENGTH_LONG).show();
} else {
//QR Code contains some data
try {
//Convert the QR Code Data to JSON
JSONObject obj = new JSONObject(result.getContents());
//Set up the TextView Values using the data from JSON
txtFruit.setText(obj.getString("fruit"));
txtSize.setText(obj.getString("size"));
txtColor.setText(obj.getString("color"));
} catch (JSONException e) {
e.printStackTrace();
//In case of exception, display whatever data is available on the QR Code
//This can be caused due to the format MisMatch of the JSON
Toast.makeText(getActivity(), result.getContents(), Toast.LENGTH_LONG).show();
txtSize.setText(result.getContents());
System.out.println("code QR: " + result.getContents());
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onClick(View view) {
//initiating the qr code scan
qrScan.initiateScan();
}
}
答案 0 :(得分:2)
此替换帮助:
public void onClick(View view) {
IntentIntegrator.forFragment(this).initiateScan();
}