如何在片段中导入“ gson”

时间:2019-07-13 17:39:14

标签: android gson fragment

在活动类中没有出现“ gson”错误,但是在编写预告片时出现错误。我该如何解决这个错误?

public class BarcodeReaderFragment extends Fragment {

@Override
public void receiveDetections(Detector.Detections < Barcode > detections) {
    final SparseArray < Barcode > qrcode = detections.getDetectedItems();
    if (qrcode.size() != 0) {
        Vibrator vibrator = (Vibrator) getActivity().getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(100);
        Intent my = new Intent(getActivity(), ResultActivity.class);
        my.putExtra("type", qrcode.valueAt(0));
        Gson gson = new Gson();
        String json = gson.toJson(qrcode.valueAt(0));
        SharedPreferences sp = getActivity().getSharedPreferences("list", Context.MODE_PRIVATE);
        addhistory(sp, json);
        startActivity(my);
        getActivity().finish();
        barcodeDetector.release();
    }
}

enter image description here

2 个答案:

答案 0 :(得分:0)

您需要按照here的描述将Gson库包含在您的项目中,然后它们像这样导入Gson类:import com.google.gson.Gson(将其直接放在package声明下)。

答案 1 :(得分:0)

请在您的应用gradle中使用gradle导入库

implementation 'com.google.code.gson:gson:2.8.5'

enter image description here