askIT

Android Parameter transfer between classes

This article aims at passing parameters from one class to another. This can be achieved with Intent.

In the example below the first class name is DietPlan.class and the next class is DietPlanView.class. A variable will be passed between the classes.

The variable that will be transfered is int with value 5:
    int dietPlanIdInt = 5;

First class (DietPlan.class)

// My variable
int dietPlanIdInt = 5;

// Start view
Intent i = new Intent(DietPlan.this, DietPlanView.class);
i.putExtra("dietPlanId", dietPlanIdInt);

startActivity(i);

Second class (DietPlanView.class)

// Get ID
// Here we are getting the varible from the
// other class that sent the variable
Bundle b = getIntent().getExtras();
int dietPlanId = b.getInt("dietPlanId");
Toast.makeText(this, "ID: " + dietPlanId, Toast.LENGTH_SHORT).show();

Add comment

avatar_blank_60.png

Comment:

Name:

Email:

Comments

No comments yet. You can be the first one to comment. Just write your comment in the form and click on the submit button.