Search code examples
androidnullfindviewbyid

Android findViewById returning null


I'm using a button to call a method that just places input text into a textview. Whenever I use findViewById, it returns null.

public void encode(View view){
  TextView out = (TextView) view.findViewById(R.id.encoderout);
  EditText in = (EditText) view.findViewById(R.id.encoderin);
  out.setText(in.getText().toString());
  out.setTypeface(font);
}

My xml is here

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
    >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/input"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    >
    <EditText android:id="@+id/encoderin"
        android:layout_width="0dp"
        android:layout_weight="2"
        android:layout_height="wrap_content"
        android:hint="Text to encode"/>
    <Button android:id="@+id/encoderbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="encode"
        android:text="Encode!"/>
</LinearLayout>
<TextView android:id="@+id/encoderout"
    android:text="test"
    android:layout_width="fill_parent"
    android:layout_weight="1"
    android:gravity="center"
    android:layout_height="wrap_content"/>
</LinearLayout>

Almost every post I could find said that cleaning the project helped solve the problem but not in this case.

EDIT: ADDITIONAL INFO

I'm using Fragments, and this is my fragment code

public static class Encoder extends Fragment{
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.encoder, container, false);       
    return view;
  }
}

It's calling up into the Activity because of the way buttons work. I can call the find methods fine in the fragment, but not when I have to go back to the activity.

I can verify the view is not null, it prints out fine when the toString is called in the method.

Solution: Never realized that I had to use the main view, thought I was SUPPOSE to use the button view. I'm very new to this (started today) thankyou everyone for the input!


Solution

  • <Button android:id="@+id/encoderbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="encode"
        android:text="Encode!"/>
    

    The parameter view in callback method encode(View view) in the Java code is supplied with the Button view itself but not the Activity.

    See Reference below:

    http://developer.android.com/reference/android/widget/Button.html