Sasho
Sasho

Reputation: 79

One layout for 5 buttons

I am doing a screen where I will have 5 buttons that are all going to be from other layout. That other layout is only the button defined. So when I call to initialize the first button and set its text like this: Button button = (Button) findViewById(R.layout.layout_for_button); button.setText("text"); So it throws NullPointerException for the button. It's very strange and it does so on the first call of the button and I have to use that layout for 5 more.

Upvotes: 0

Views: 100

Answers (4)

fida1989
fida1989

Reputation: 3249

Android Basic Button Example:

res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button - Go to mkyong.com" />
 </LinearLayout>

MyAndroidAppActivity.java

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;

public class MyAndroidAppActivity extends Activity {

    Button button;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

            // Do something

            }

        });

    } 
}

Source

Upvotes: 0

Shakeeb Ayaz
Shakeeb Ayaz

Reputation: 6096

you need to check for R.id not R.layout inside findviewById

so do it this way

 Button button = (Button) findViewById(R.id.buttonID);
 button.setText("text");

where buttonID is from layout xml for button android:id="@+id/buttonID"

Upvotes: 1

jboi
jboi

Reputation: 11892

You're getting the NullPointerException because the findViewById does not find the button with an ID equal to the layout-Id. To find your button, you must do two things:

  • In the Layout-XML give the button an unique id with android:id="@+id/yourbutton". You get your button then with findViewById(R.id.yourbutton)
  • Call the findViewById from within the right context. Usually the context is the Activity your're coding the findViewById in.

Upvotes: 2

Festus Tamakloe
Festus Tamakloe

Reputation: 11310

This is quiet simple

Button button = (Button) findViewById(R.layout.layout_for_button); 
button.setText("text");

In your code above button is null

Something is wrong with findViewById(R.layout.layout_for_button)

May be your calling the findViewById from context

Upvotes: -1

Related Questions