Search code examples
androidandroid-fragmentsfindviewbyid

findViewById returns null in fragment class


  • The findViewById() returns null in fragment class. The Toast for the ImageButton shows something but the object for Switch i.e. mySwitch returns null... please help....

    public MyAdapter(Context context, List<ListItems> values) {
    
        super(context, R.layout.list_item, values);
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    
        View v = convertView;
        LayoutInflater inflater = LayoutInflater.from(getContext());
    
        if( v == null){
            v = inflater.inflate(R.layout.list_item, parent, false);
        }
    
        ListItems currLoc = LocationList.get(position);
    
        TextView theTextView = (TextView) v.findViewById(R.id.list_item_textview);
        theTextView.setText(currLoc.getLocation());
    
        TextView theTextView2 = (TextView) v.findViewById(R.id.list_item_textviewP);
        theTextView2.setText(currLoc.getProfile());
    
        ImageView theImageView = (ImageView) v.findViewById(R.id.imageview1);
        Toast.makeText(getActivity(), "image view="+theImageView, Toast.LENGTH_SHORT).show();
        theImageView.setImageResource(R.drawable.bullet);
    
    
        Switch mySwitch=(Switch) v.findViewById(R.id.onoff);
        Toast.makeText(getActivity(), ""+mySwitch, Toast.LENGTH_SHORT).show();
    
    
        return v;
    }
    

Solution

  • I got it.... I had defined the findViewById in onGetView I had to declare it on OnCreateView Sorry.....