Search code examples
javaandroidbuttononcreate

How to set text of android button in onCreate Method?


I want to set the text of my button in onCreate Method, but it doesn't work.

Code in MainActivity-Class:

Button button;

Code in onCreate:

button = findViewById(R.id.button);
    button.setText("test");

Butto in xml:

<Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:alpha="0.5"
        android:background="@color/design_default_color_secondary_variant"
        android:onClick="checkPermissions"
        android:textSize="30sp" />

Here's the Exception:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setText(java.lang.CharSequence)' on a null object reference

I know that I can set the text of button in XML, but I want to set the text at app start via sharedpreferences, but it won't work if I can't even set a simple string onto it by calling this easy way.


Solution

  • To find id fragment you need view reference.

    @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            Button button= view.findViewById(R.id.button);
            button.setText("text");
    
        }