Reputation: 45
This is my Class Code in which i want to acess toggle button but am getting nullpointer exception.i used ViewHolder Class to get the view from Layout and Acessing them here.but unable to find the error why am getting this NUllPOInter at
holder.stateOnOff.setText(); line
public class ColorSchemeFragment extends Fragment {
public class ViewHolder {
public ToggleButton toggleButton;
public TextView stateOnOff;
}
ViewHolder holder = new ViewHolder();
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.colorscheme, container, false);
holder.toggleButton = ((ToggleButton) container.findViewById(R.id.toggle));
holder.stateOnOff=(TextView)container.findViewById(R.id.tvstate);
holder.stateOnOff.setText("OFF");
holder.toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked){
holder.stateOnOff.setText("On");
}else{
holder.stateOnOff.setText("Off");
}
}
});
return view;
}
}
Upvotes: 2
Views: 4002
Reputation: 3366
No need to use a ViewHolder
. They are for recycling views through a ListView
or other scrollable views.
Also the container
object holds the parent layout, and not the one you are inflating. So it does not contain the views you are looking up and returns null.
public class ColorSchemeFragment extends Fragment {
public ToggleButton toggleButton;
public TextView stateOnOff;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.colorscheme, container, false);
toggleButton = (ToggleButton) view.findViewById(R.id.toggle);
stateOnOff=(TextView) view.findViewById(R.id.tvstate);
stateOnOff.setText("OFF");
toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked){
stateOnOff.setText("On");
}else{
stateOnOff.setText("Off");
}
}
});
return view;
}
}
Upvotes: 2