Reputation: 1
I Have an Activity called Main2Activity, and it consists of a variable "double result1 " which is set equal to an expression. It looks like this:
double result1 = n1 * 2 - 29;
(Where n1 is an input given by the user)
I'm trying to use this variable in another class called MainActivityEnd. I tried this:
double finalResult = Main2Activity.result1 * 4;
When I print result1 in Main2Activity using setText
it prints the correct value.
But when I print finalResult
in MainActivityEnd
using setText
It always prints 0.0
Is there a reason for this?
Thanks for the help!
Upvotes: 0
Views: 3336
Reputation: 1364
Use Intents
or SharedPreferences
like other people has already mentioned here.
If however you are planning to put some global logic (like methods) then use Application class.
You can extend Application class like this:
public class YourApplication extends Application {
public double result1 = 29;
}
And then in any in your Activities:
YourApplication app = (YourApplication) this.getApplication();
System.out.printl(app.result1);
Make sure that you named your application class properly, it should be [YOUR_APP_NAME]Application
. And also don't forget to put your new application class into the manifest
:
<application
android:name=".YourApplication"
Upvotes: 0
Reputation: 63
If activities are in the same flow, you should use the following Android way - intents. Simply put, Intent is Android's way of changing values between activities when they are launched in sequential order.
So you should do the following in Main2Activity:
Intent intent = new Intent(Main2Activity.this, MainActivityEnd.class);
intent.putExtra("name", variable);
startActivity(intent);
where Main2Activity starts MainActivityEnd. The Intent is filled with the data MainActivityEnd needs, which in this case is "variable".
Afterwards you should catch the Intent in MainActivityEnd onCreate() method like this:
Intent intent = getIntent();
double finalResult = intent.getDoubleExtra("name", 0);
where "name" is the same name that was given in Main2Activity and 0 is a default value if there's wasn't a double value attached to Intent in Main2Activity.
That's the most common usage of this behaviour in Android.
Upvotes: 2