Waqas Aamer
Waqas Aamer

Reputation: 59

How do I use variable of one activity in another activity in android studio

I have two activities classes. A value from user is taken in the first activity and stored in a integer datatype variable.

final EditText areanumber1 = (EditText) findViewById(R.id.editTextplotarea);
areanumber1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            int plotarea1 = Integer.parseInt(areanumber1.getText().toString());
            plotarea = plotarea1;
        }
});

When the next button is clicked it moves to next activity. Now I want to use that plotarea variable in another activity.

Second activity:

nextactivity = (Button) findViewById(R.id.buttonnext);
nextactivity.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        totallengthofwall = noofwalls * plotarea;
        startActivity(new Intent(getApplicationContext(), roomActivity.class));
    }
});

Upvotes: 0

Views: 5668

Answers (2)

You should use intent bundles to pass variables trough activities.

E.G:

Intent secondAcvitity = new Intent (getApplicationContext(), roomActivity.class);
secondAcvity.putExtra("NameOfVariable", plotarea1);
startActivity(secondActivity);

EDIT:

First activity:

final EditText areanumber1 = (EditText) findViewById(R.id.editTextplotarea);
areanumber1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            int plotarea1 = Integer.parseInt(areanumber1.getText().toString());
            plotarea = plotarea1;
            Intent secondActivity = new Intent (getApplicationContext(), roomActivity.class);
            secondActivity.putExtra("NameOfVariable", plotarea1);
            startActivity(secondActivity);
        }
});

Then you should call intent in your new activity:

Second activity:

public .... onCreate(){
int newPlotarea1 = getIntent().getIntExtra("NameOfVariable", 0);
}

Upvotes: 1

Sandeep Singh
Sandeep Singh

Reputation: 1127

For this either you can make variable static or pass that variable using Intent.

    startActivity(new Intent(getApplicationContext(),roomActivity.class).putExtra("plotarea", plotarea));

Upvotes: 0

Related Questions