Home > Blockchain >  App crashes as soon as i add onclicklistener when trying to display toast
App crashes as soon as i add onclicklistener when trying to display toast

Time:12-06

soon as i try to add a toast my app crashes, i think i'm doing everything correct, but maybe not, trying to get back into programming after long break and running into silly issues like this any ideas?

i wrote the same code in java and in kotlin and still the app crashes

it seems as soon as i add the on click listener the app no longer works

is this a problem in the code or issues with my ide.

home xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.home.HomeFragment">

    <TextView
            android:id="@ id/text_home"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:textAlignment="center"
            android:textSize="20sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>
    <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@ id/btnToast"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

main activity.java:

package com.example.javaapp;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.javaapp.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;

    Button btnToast;

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


          btnToast = findViewById(R.id.btnToast);
        btnToast.setOnClickListener(new View.OnClickListener() {
        @Override
       public void onClick(View view) {
         Toast.makeText(MainActivity.this,"hello test 123",Toast.LENGTH_LONG).show();
       }
    });


        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(binding.navView, navController);
    }



logcat


2022-12-05 16:36:37.852 18840-18840 Process                 com.example.javaapp                  I  Sending signal. PID: 18840 SIG: 9
---------------------------- PROCESS ENDED (18840) for package com.example.javaapp ----------------------------
2022-12-05 16:38:07.020 17039-17039 studio.deploy           install_server-bde4359e              E  Could not remove dir '/data/data/com.example.javaapp/code_cache/.ll/': No such file or directory
---------------------------- PROCESS STARTED (19001) for package com.example.javaapp ----------------------------
2022-12-05 16:38:07.581 19001-19001 Compatibil...geReporter com.example.javaapp                  D  Compat change id reported: 171979766; UID 10158; state: ENABLED
2022-12-05 16:38:07.601 19001-19001 ziparchive              com.example.javaapp                  W  Unable to open '/data/app/~~FeimdrJdwhN9iQHirqPvHg==/com.example.javaapp-WIltqAi8b9LeodOkfpOG5w==/base.dm': No such file or directory
2022-12-05 16:38:07.601 19001-19001 ziparchive              com.example.javaapp                  W  Unable to open '/data/app/~~FeimdrJdwhN9iQHirqPvHg==/com.example.javaapp-WIltqAi8b9LeodOkfpOG5w==/base.dm': No such file or directory
2022-12-05 16:38:07.728 19001-19001 GraphicsEnvironment     com.example.javaapp                  V  ANGLE Developer option for 'com.example.javaapp' set to: 'default'
2022-12-05 16:38:07.729 19001-19001 GraphicsEnvironment     com.example.javaapp                  V  ANGLE GameManagerService for com.example.javaapp: false
2022-12-05 16:38:07.729 19001-19001 GraphicsEnvironment     com.example.javaapp                  V  Neither updatable production driver nor prerelease driver is supported.
2022-12-05 16:38:07.732 19001-19001 NetworkSecurityConfig   com.example.javaapp                  D  No Network Security Config specified, using platform default
2022-12-05 16:38:07.733 19001-19001 NetworkSecurityConfig   com.example.javaapp                  D  No Network Security Config specified, using platform default
2022-12-05 16:38:07.752 19001-19026 libEGL                  com.example.javaapp                  D  loaded /vendor/lib64/egl/libEGL_emulation.so
2022-12-05 16:38:07.753 19001-19026 libEGL                  com.example.javaapp                  D  loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
2022-12-05 16:38:07.754 19001-19026 libEGL                  com.example.javaapp                  D  loaded /vendor/lib64/egl/libGLESv2_emulation.so
2022-12-05 16:38:07.806 19001-19001 example.javaapp         com.example.javaapp                  W  Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (unsupported, reflection, allowed)
2022-12-05 16:38:07.806 19001-19001 example.javaapp         com.example.javaapp                  W  Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (unsupported, reflection, allowed)
2022-12-05 16:38:07.807 19001-19001 Compatibil...geReporter com.example.javaapp                  D  Compat change id reported: 210923482; UID 10158; state: DISABLED
2022-12-05 16:38:07.807 19001-19001 Compatibil...geReporter com.example.javaapp                  D  Compat change id reported: 37756858; UID 10158; state: ENABLED
2022-12-05 16:38:07.810 19001-19001 AndroidRuntime          com.example.javaapp                  D  Shutting down VM
2022-12-05 16:38:07.812 19001-19001 AndroidRuntime          com.example.javaapp                  E  FATAL EXCEPTION: main
                                                                                                    Process: com.example.javaapp, PID: 19001
                                                                                                    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.javaapp/com.example.javaapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3676)
                                                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3813)
                                                                                                        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101)
                                                                                                        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
                                                                                                        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
                                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2308)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                                        at android.os.Looper.loopOnce(Looper.java:201)
                                                                                                        at android.os.Looper.loop(Looper.java:288)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:7898)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
                                                                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                                                        at com.example.javaapp.MainActivity.onCreate(MainActivity.java:27)
                                                                                                        at android.app.Activity.performCreate(Activity.java:8290)
                                                                                                        at android.app.Activity.performCreate(Activity.java:8269)
                                                                                                        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1384)
                                                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3657)
                                                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3813) 
                                                                                                        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101) 
                                                                                                        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
                                                                                                        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
                                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2308) 
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:106) 
                                                                                                        at android.os.Looper.loopOnce(Looper.java:201) 
                                                                                                        at android.os.Looper.loop(Looper.java:288) 
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:7898) 
                                                                                                        at java.lang.reflect.Method.invoke(Native Method) 
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) 
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936) 
2022-12-05 16:38:07.833 19001-19001 Process                 com.example.javaapp                  I  Sending signal. PID: 19001 SIG: 9
---------------------------- PROCESS ENDED (19001) for package com.example.javaapp ----------------------------

CodePudding user response:

you are assigning value to btnToast before the layout is created.

try this :

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

  binding = ActivityMainBinding.inflate(getLayoutInflater());
   
  setContentView(binding.getRoot());

    btnToast = findViewById(R.id.btnToast);
    btnToast.setOnClickListener(new View.OnClickListener() {
    
   @Override
   public void onClick(View view) {
     Toast.makeText(MainActivity.this,"hello test 123",Toast.LENGTH_LONG).show();
   }
});
  • Related