在片段中获取结果的问题

问题描述 投票:0回答:1

美好的一天,我试图获得扫描片段中QR码的结果,因为活动一切正常,但转移后无法获得结果。怎么解决这个问题?

正如我理解“onActivityResult”方法中的问题。我需要一些解决方案的信息。如何改变片段?

我的代码在下面:

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();

}
}
java android android-fragments fragment qr-code
1个回答
2
投票

这个替换有助于:

    public void onClick(View view) {
        IntentIntegrator.forFragment(this).initiateScan();
   }
© www.soinside.com 2019 - 2024. All rights reserved.