[android] Add button to a layout programmatically

I'm having trouble adding a button to a layout that I've created in XML. Here's what I want to achieve:

//some class
else {
        startActivity(new Intent(StatisticsScreen.this, ScreenTemperature.class));
}
////

//ScreenTemperatureClass
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //this is where I call another class that
    //displays a nice graph
    setContentView(new GraphTemperature(getApplicationContext()));

}

I want to add a Button to this new screen so that it'll appear below the graph. I've tried creating a LinearLayout view, then create a Button and add it to this view but I just get NullPointerExceptions..

Any help would be appreciated. Thanks

EDIT#1

Here's what I've tried using that created a NullPointerException and 'force close':

Button buybutton;
LinearLayout layout;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(new GraphTemperature(getApplicationContext()));

    layout = (LinearLayout) findViewById(R.id.statsviewlayout);
    Button buyButton = new Button(this);
    buyButton.setText(R.string.button_back);
    buyButton.setLayoutParams(new LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    layout.addView(buyButton);

}

And here's the logcat error:

ERROR/AndroidRuntime(293): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.weatherapp/com.weatherapp.ScreenTemperature}: java.lang.NullPointerException
ERROR/AndroidRuntime(293):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
ERROR/AndroidRuntime(293):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
ERROR/AndroidRuntime(293):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
ERROR/AndroidRuntime(293):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)

theres abviously more lines to do with this error in logcat, not sure if you want it?

EDIT#2

So i tried bhups method:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GraphTemperature GT = new GraphTemperature(getApplicationContext());             
    layout = (LinearLayout) findViewById(R.id.statsviewlayout);
    Button buyButton = new Button(this);
    buyButton.setText(R.string.button_back);
    buyButton.setLayoutParams(new LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    layout.addView(GT); // line 27
    layout.addView(buyButton);       
    setContentView(layout);           
}

This method produced the same logcat error as above, NullPointerException, indicating it was something to do with line no. 27 which is the layout.addView line of code. Any ideas? Thanks again

This question is related to android button android-activity

The answer is


If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

then you can create a new Button for example and just add it:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to button

How do I disable a Button in Flutter? Enable/disable buttons with Angular Disable Button in Angular 2 Wrapping a react-router Link in an html button CSS change button style after click Circle button css How to put a link on a button with bootstrap? What is the hamburger menu icon called and the three vertical dots icon called? React onClick function fires on render Run php function on button click

Examples related to android-activity

Kotlin Android start new Activity The activity must be exported or contain an intent-filter How to define dimens.xml for every different screen size in android? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Not an enclosing class error Android Studio java.lang.IllegalStateException: Fragment not attached to Activity Soft keyboard open and close listener in an activity in Android android.app.Application cannot be cast to android.app.Activity Android Shared preferences for creating one time activity (example) Android ListView with onClick items