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.
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
}
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)
{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With