I am using Butter Knife to bind view's in my app Fragment, but I am getting null point exception when the app has no internet connection but working fine when in online. Don't know why it's happening like this.. Can any one have any idea on it let me know. Thanks in advance..
This is the way I am using it in my code..
public class MyFragment extends Fragment {
@BindView(R.id.myTextView)
TextView myTextView;
public MyFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Home");
getInfo();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_about_us, container, false);
ButterKnife.bind(this, view);
return view;
}
private void getInfo () {
if(isOnline(getActivity())) {
// Do some thing
myTextView.setText("Hi");
} else {
// do some thing
myTextView.setText("Hello");
}
}
}
Log:
FATAL EXCEPTION: main
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at butterknife.internal.Utils.findRequiredView(Utils.java:87)
at butterknife.internal.Utils.findRequiredViewAsType(Utils.java:104)
You are calling getInfo()
from onCreate()
, but butterknife performs the binding just in onCreateView()
which is called by the system after onCreate()
. So myTextView
is not initialized, when you access it in getInfo()
.
Move getInfo()
into onCreateView() after Butterknife.bind()
and it should work fine.