Shimon Payyanadan Shimon Payyanadan - 4 months ago 8
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);
startActivity(intentsem);


//Sending the branch value to Navdrawer

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



}


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);
startActivity(l);
}


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

}

Answer

You need to use Intent: Activity A:

doneButton.setOnClickListener(new View.OnClickListener() {
            @Override
            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);
                 startActivity(intent);

            }
        });

Activity B:

int variable = getIntent().getIntExtra("my_value", 0);//0 is the default value if the getintExtra doesn't find the "my_value"
Comments