Reputation: 2440
What is the correct way to pass a simple variable which has its value set to use in another class? I have a counter which is incremented with a button press and when counter = 3 a method is called which loads another activity which loads another screen with a string which states the button was pressed. Here is where I want to include the number 3 passed from the counter variable in the previous class, but I am not sure the correct way to do this. I tried creating an instance of the class and connecting to the variable that way but the value is never passed and it is always 0.
Upvotes: 3
Views: 39411
Reputation: 452
You can pass that value using the intent
Intent new_intent=new Intent(this,SecondActivity.class);
intent.putExtra("counter",10); //here the value is integer so you use the new_intent.putExtra(String name,int value)
startActivity(new_intent);
After that in the second activity class you can get that that values using Bundle
Bundle bundle = getIntent().getExtras();
int count = bundle.getInt("counter");
I think this may help you.
Upvotes: 1
Reputation: 94625
You may pass value via Intent - resource bundle.
Pass value from current activity,
Intent intent=new Intent(this,ResultActivity.class);
intent.putExtra("no",10);
startActivity(intent);
and in ResultActivity (onCreate),
Bundle bundle=getIntent().getExtras();
int value=bundle.getInt("no");
In case of non-activity classes, you may define a public method.
For instance,
public Integer getValue() //returns a value
{
return 10;
}
Or
public void setValue(Integer value)
{
...
}
Upvotes: 5
Reputation: 22066
You can also do it through define variable as "static" in one activity and in second activity use that variable with using <<classname>>.<<variableb>>
ex:
Activity1:
Static var = 5;
Activity2:
System.out.println(Activity1.var);
Upvotes: 1
Reputation: 1512
one way to do it would be when you build your new intent to do :
Intent itn = new Intent(...,...);
itn.putExtra(KEY,VALUE);
startctivity(itn);
And on the other class do something like :
this.getIntent.getStringExtra(KEY);
or
this.getIntent.getWHATEVERYOURVARIABLEWASExtra(KEY);
Hope it helps you, and it's the better way to pass arguments between 2 activities :)
Upvotes: 1
Reputation: 527
Try following code,
public class First
{
private static int myVarible = 0;
private void myMethod()
{
myVariable = 5; // Assigning a value;
}
public static int getVariable()
{
return myVariable;
}
}
public class Second
{
int i = First.getVariable(); // Accessing in Another class
}
Upvotes: 10