DarkVex DarkVex - 1 month ago 21
Android Question

Barcode Fragment "invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference"

I'm trying to use the ZXing library for make a Bar Code scan in a Fragment.
I have successful imported the library but when I choose from the APP this Fragment the APP crash with the following traceback:

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)


And here the Fragment code

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

}


What I've missing or what I'm doing wrong?

Answer

You haven't defined any view for your fragment, so it is unable to find that relevant id thus resulting in Null Pointer Exception. Override onCreateView() method in your fragment and provide a view in that and then write your findViewById code in this method like this

@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;
}