Farid Farid - 3 months ago 11
Android Question

findViewById is null, am I not in the right View?

MainActivity.java:

public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
}
public void OnClickSendButton(View view) {
EditText editTxt = (EditText) view.findViewById(R.id.MessageEditText);
CharSequence toastText = editTxt.getText().toString();
}
}


activity_main.xml:

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.faridahamat.androidlayout.MainActivity">

<EditText
android:id="@+id/MessageEditText"/>
<Button
android:onClick="OnClickSendButton"/>
<GridLayout/>


I already called the
setContentView
to use the
activity_main.xml
, so why am I still not able to get the
MessageEditText
's content? If
MainActivity
already uses the
activity_main.xml
as its layout, shouldn't I be able to get whatever that is inside that layout by calling Views that are inside?

I'm newbie, so my understanding of
Activity
/
View
might be wrong, please explain.

Answer

No, you aren't. The view returned in an onClick is the view that was clicked not the root view.

Generally its considered a good practice to use findById to find all the views you'll need in onCreate, so you don't need to do repeated N time walks of possibly complex hierarchies.