-2

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
OSbOoL
  • 13
  • 4
  • did you call `setContentView(your_layout.xml)` first? Otherwise no view is inflated to your activity and `findViewById` can't find anything. – ChristianB Dec 28 '20 at 10:20
  • Yes, but the button is not in activity_main.xml. It is in fragment_recording.xml. – OSbOoL Dec 28 '20 at 10:47

2 Answers2

1

You better share the whole onCreate() code in order to get help.

By now, I could assume you don't call setContentView(R.layout.your_layout_with_button) in onCreate() method before accessing button by calling findViewById(R.id.button).

Whole code inside onCreate() will be looking smth like this:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.your_layout_with_button)

        val button = findViewById(R.id.button)
        button.setText("test")
    }
Dharman
  • 30,962
  • 25
  • 85
  • 135
reel
  • 189
  • 7
  • The onCreate is ok, the Button is in another fragment than in activity_main.xml. Can this be the mistake? But how can I get access to my button then? If I type "R.id." then my button was showing.... – OSbOoL Dec 28 '20 at 10:51
1

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");

    }
Amrish Kakadiya
  • 974
  • 1
  • 7
  • 25