Oyubu Obukohwo Oyubu Obukohwo - 1 month ago 8
Android Question

how to launch new activity based on spinner value

i am building this app that has a spinner and button on the first activity, but i have other activities which are lauched based on spinner value. but the problem now is when i click on button nothing happens, what could be wrong? this is my code

public class ow extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ow);
Button button1=(Button) findViewById(R.id.tac);

Spinner spin = (Spinner) findViewById(R.id.spinner);
final String text = spin.getSelectedItem().toString();
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (text.equals("GTB")) {
Intent intent = new Intent(ow.this, gtb.class);
startActivity(intent);
}else if(text.equals("ZENITH")){
Intent intent=new Intent(v.getContext(),z.class);
startActivity(intent);
}
}

});

}
}

Answer

Try this

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_ow);
       Button button1=(Button) findViewById(R.id.tac);

        final Spinner spin = (Spinner) findViewById(R.id.spinner);  
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = spin.getSelectedItem().toString();

                if (text.equals("GTB")) {
                    Intent intent = new Intent(ow.this, gtb.class);
                    startActivity(intent);
                }else if(text.equals("ZENITH")){
                    Intent intent=new Intent(v.getContext(),z.class);
                    startActivity(intent);
                }
            }

        });

    }}
Comments