条形码片段“在空对象引用上调用虚拟方法'void android.widget.Button.setOnClickListener(android.view.View $ OnClickListener)'”

时间:2016-10-09 17:32:04

标签: android android-fragments barcode zxing barcode-scanner

我正在尝试使用ZXing库在片段中进行条形码扫描。 我已经成功导入了库,但是当我从APP中选择这个片段时,APP崩溃并带有以下追溯:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                      at com.fastnetserv.barcodeapp.Barcode.onResume(Barcode.java:86)
                      at android.support.v4.app.Fragment.performResume(Fragment.java:2020)
                      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1107)
                      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
                      at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
                      at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
                      at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5254)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

这里是片段代码

package com.fastnetserv.barcodeapp;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.content.Intent;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;    

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link Barcode.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link Barcode#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Barcode extends Fragment implements OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public Barcode() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Barcode.
     */
    // TODO: Rename and change types and number of parameters
    public static Barcode newInstance(String param1, String param2) {
        Barcode fragment = new Barcode();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }    
    }

    private Button scanBtn;
    private TextView formatTxt, contentTxt;

    @Override
    public void onResume() {
        super.onResume();

        //instantiate button, text, content

        scanBtn = (Button) getActivity().findViewById(R.id.scan_button);
        formatTxt = (TextView) getActivity().findViewById(R.id.scan_format);
        contentTxt = (TextView) getActivity().findViewById(R.id.scan_content);

        scanBtn.setOnClickListener(this);   
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mListener = (OnFragmentInteractionListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    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();
            String scanFormat = scanningResult.getFormatName();
            formatTxt.setText("FORMAT: " + scanFormat);
            contentTxt.setText("CONTENT: " + scanContent);
        }else{
            Toast toast = Toast.makeText(getActivity(),
                    "No scan data received!", Toast.LENGTH_SHORT);
            toast.show();
        }
    }    

    @Override
    public void onClick(View v) {
        //respond to clicks
        if(v.getId()==R.id.scan_button){
        //scan
        IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
        scanIntegrator.initiateScan();
        }
    }    
}

我错过了什么或者我做错了什么?

2 个答案:

答案 0 :(得分:0)

您无法在Fragment中使用getActivity()实例化视图。

您必须执行以下操作并从onResume()中删除实例化:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
    scanBtn = (Button) view.findViewById(R.id.scan_button);
    formatTxt = (TextView) view.findViewById(R.id.scan_format);
    contentTxt = (TextView) view.findViewById(R.id.scan_content);
    scanBtn.setOnClickListener(this);
    return view;
}

答案 1 :(得分:0)

尚未为您的片段定义任何视图,因此无法找到相关的ID,从而导致Null Pointer Exception。片段中的覆盖 onCreateView()方法并提供一个视图,然后在此方法中编写findViewById代码

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout, container, false);
btn_name= (Button) view.findViewById(R.id.your_button_id);
return view;
}