-1

I was trying to pass a variable named choice to another class but I do not know how I should go along doing this because it is inside the onClick. Here is an example of what I am trying to do.

public int choice;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //intent for first button
    Button button1= (Button) findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            choice = 1;
            startActivity(new Intent(MainActivity.this,Celeb1.class));
        }
    });
    //intent for second button
    Button button2= (Button) findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            choice = 2;
            startActivity(new Intent(MainActivity.this,Celeb1.class));
        }
    });

}

In a different class I would like to check if choice is equal to 1 or 0 and execute some code.

Zain Merchant
  • 104
  • 1
  • 10

3 Answers3

0

You can pass variable by this way

Intent intent = new Intent(MainActivity.this,Celeb1.class)
intent.putExtra("choice", 1);
startActivity(intent);

And in Celeb1 class you can get variable by using

Bundle extras = getIntent().getExtras();
int choice= extras.getInt("choice");

inside onCreate()

Mobile Apps Expert
  • 1,028
  • 1
  • 8
  • 11
0
//in main activity    
Intent i=new Intent(getApplicationContext(),Celeb1.class);
    i.putExtra("name","stack");//name is key stack is value
    startActivity(i);


    //In Celeb1 class

    Intent i=getIntent();
    String name=i.getStringExtra("name");
0

Do not make instance of Intent instead make object of Intent and pass extra values to your class

choice = 2;

Intent intent = new Intent(MainActivity.this, Celeb1.class);
intent.putExtra("choice",choice);
startActivity(intent);

That's It I am android beginner, Hope It will help you.

Sagar Yadav
  • 137
  • 2
  • 11