Search code examples
androidandroid-snackbar

I'm trying to implement a snackbar in android studio but the app keeps crashing when i use it


I'm trying to implement a snackbar in android studio where when i click the button in the center of the screen, it will display the snackbar and say "moving to second screen". if the user clicks the button "CLOSE" within the snackbar, the app will close.

the problem is that when i open the app and click the button in the center of the screen, the entire app crashes

this is the code that i have so far:

import androidx.appcompat.app.AppCompatActivity;
import androidx.coordinatorlayout.widget.CoordinatorLayout;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


import com.google.android.material.snackbar.Snackbar;

public class MainActivity extends AppCompatActivity {

    Button button;

    CoordinatorLayout layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent);

                Snackbar snackbar = Snackbar.make(layout, "moving to second screen",
                        Snackbar.LENGTH_LONG).setAction("CLOSE",new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view)
                                    {
                                        MainActivity.this.finish();
                                        System.exit(0);



                                    }
                                });

                snackbar.show();
            }
        });
    }
}

Solution

  • variable layout is not initialised and you have directly used it in Snackbar code

    you can use following code to resolve your crash

    Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "moving to second screen",
                            Snackbar.LENGTH_LONG).setAction("CLOSE",new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view)
                                        {
                                            MainActivity.this.finish();
                                            System.exit(0);
    
    
    
                                        }
                                    });
    

    or you can initialise layout variable like this

    layout = findViewById(R.id.top_parent_container_id);
    

    here top_parent_container_id is id that you have used in your xml layout for top parent