user3184333
user3184333

Reputation: 11

Having trouble with findViewById - returning null

I have the activity_main XML like this:

<LinearLayout ...>
    <EditText android.id="@+id/edit_text"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
    <Button android.id="@+id/my_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send"
        android:onClick="sendMessage" />
</LinearLayout>

The main java codes are:

public class MainActivity extends Activity {
    void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.activity_main);
        EditText editText = (EditText) findViewById(R.id.edit_text);
        if (editText == null)   
            Log.v("editText", "null editText");
        else
            Log.v("editText", "good editText");
    }
}

The display is correct and I can see the EditText and Button fields. However, I always got NULL for editText. I read the previous problems. Most of them were due to the fact that setContentView(R.layout.active_main) was not used. But I can't find out why I am having problem with my codes. Any help is greatly appreciated.

Upvotes: 1

Views: 79

Answers (2)

Chintan Soni
Chintan Soni

Reputation: 25267

You were using . instead of :. So please make your correction as below:

<LinearLayout ...>
    <EditText android:id="@+id/edit_text"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
    <Button android:id="@+id/my_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send"
        android:onClick="sendMessage" />
</LinearLayout>

Upvotes: 2

TwilightSun
TwilightSun

Reputation: 2335

Your XML has problem

android:id not android.id

Upvotes: 4

Related Questions