Search code examples
javaandroidandroid-fragmentszxing

Android cannot resolve constructor - static Fragment


New to andorid, and im stuck trying to reference 'this' inside a Fragment.

Using the Navigation Draw template project, which has a static class for the main Fragment.

I'm trying to integrate the zxing barcode scanner, which wants a reference to the Fragment for the intent, but when using this it errors saying it cant resolve the constructor.

I assume due the static nature of the class, but not sure how to resolve it.

Ive tried this and PlaceholderFragment.this......

public static class PlaceholderFragment extends Fragment implements Button.OnClickListener {

    private Button scanBtn;

    private static final String ARG_SECTION_NUMBER = "section_number";

    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);

        scanBtn = (Button) view.findViewById(R.id.scan_btn);
        scanBtn.setOnClickListener(this);

        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }

    @Override
    public void onClick(View v) {

        // `this` here errors saying it cant find the constructor.  
        // Im trying to pass a reference to this fragment...

        IntentIntegrator integrator = new IntentIntegrator( this );
        integrator.initiateScan();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
        if (scanResult != null) {
            Toast.makeText(getActivity().getApplicationContext(), "You scanned", Toast.LENGTH_LONG).show();
        }

    }

}

Solution

  • ZXing uses app.Fragments and the Template project was using support.v4.app.Fragment.

    Google encourages using support fragments because they get bugfixed regularly, but it all depends on what your library decided.