Shimon Payyanadan Shimon Payyanadan - 1 year ago 63
Android Question

Pass value from an int variable in one class to another class

I was trying pass an int variable from one activity class(A) to another activity class(B). As I am a beginner, I am stuck here.

I have tried many methods but each time I run the code in debug mode , I can see that the int value which I have passed into the second class turns to 0.

Code for Activity A

public void startMainActivity(View view)
//Sending the semester value to Navdrawer
Intent intentsem = new Intent(LoginActivity.this, NavDrawer.class);
intentsem.putExtra("UserSemester", usersemester);

//Sending the branch value to Navdrawer

Intent intentbranch= new Intent(LoginActivity.this, NavDrawer.class);
intentbranch.putExtra("UserBranch", userbranch);


Code for Activity B

public void startSyllabusactivity(View view)

// for first year

int semester = getIntent().getIntExtra("UserSemester", 0);
if (semester==1 || semester==2) {
Intent l = new Intent(this, firstyear_syllabussubject_selector.class);

//rest of the actions with branches to be added***********************


Answer Source

You need to use Intent: Activity A:

doneButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                 Intent intent = new Intent(context, ActivityB.class);
                 intent.putExtra("my_value", 2); //2 is the value you want to pass
                 intent.putExtra("UserBranch", userbranch);


Activity B:

int variable = getIntent().getIntExtra("my_value", 0);//0 is the default value if the getintExtra doesn't find the "my_value"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download