Set variable for reuse in case onclicklistener

How to reuse a variable set in case/switch. Basically want to set chart_loc as a variable to reuse when user clicks btn_engage

.setOnClickListener((dialog1, view) -> {

                    String chart_loc;

                    switch ( view.getId () ) {

                       
                            case R.id.chart_Aventure:

                              chart_loc = "adventure";
                            break;

                            case R.id.chart_Romance:

                              chart_loc = "romance";
                            break;

                              default: chart_loc = "";
                            break;
                     }

                    if (view.getId () == R.id.btn_engage){
                         Toast.makeText (this,"Chart: "+chart_loc, Toast.LENGTH_LONG).show ();

                    }
})

Answer

Define your variable globally, Like in YourActivity.java before onCreate() method.

String chart_loc = null;

and then you can assign value to your variable in Switch/Case like.

yourBtn.setOnClickListener((dialog1, view) -> {

                switch ( view.getId () ) {
          
                        case R.id.chart_Aventure:

                          chart_loc = "adventure";
                        break;

                        case R.id.chart_Romance:

                          chart_loc = "romance";
                        break;

                          default: chart_loc = "";
                        break;
                 }

                if (view.getId () == R.id.btn_engage){
                     Toast.makeText (this,"Chart: "+chart_loc, Toast.LENGTH_LONG).show ();

                }