skip to Main Content

When I run the program, it gives an error and the program stops
It gets an error from the findViwById line
I don’t know where the problem is, please help
I take pictures of the log, mainActivity and layout

Logcast

---------------------------- PROCESS STARTED (10563) for package com.example.test0 ----------------------------

2023-05-23 15:20:13.344 10563-10563 AndroidRuntime com.example.test0 E FATAL EXCEPTION: main
Process: com.example.test0, PID: 10563
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test0/com.example.test0.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘android.view.View android.widget.Button.findViewById(int)’ on a null object reference
atandroid.app.ActivityThread.performLaunchActivity(ActivityThread.java:2835)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1615)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6687)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘android.view.View android.widget.Button.findViewById(int)’ on a null object reference
at com.example.test0.MainActivity.onCreate(MainActivity.java:19)
at android.app.Activity.performCreate(Activity.java:7028)
at android.app.Activity.performCreate(Activity.java:7019)
}

public class MainActivity extends AppCompatActivity {
Button button;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button.findViewById(R.id.button);  //<<<<<==== line19
    editText.findViewById(R.id.editText);
}

}

[[enter image description here](https://phpout.com/wp-content/uploads/2023/05/rpH2a.png)](https://phpout.com/wp-content/uploads/2023/05/u6Uez.png)

I have tried with all kinds of emulators and mobile phones, but it didn’t work

2

Answers


  1. You need to use findViewById(R.id.button) directly, without using button first.

    The final code will look like: button = findViewById(R.id.button)

    Same goes for the edit text as well. Then you can use the views.

    Login or Signup to reply.
  2. You need to change the calls to

    button = findViewById(R.id.button);
    editText = findViewById(R.id.editText);

    As findViewById returns a view and available in activity.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search