开发者

Accessing a public variable from another class?

开发者 https://www.devze.com 2023-02-14 10:38 出处:网络
The app I\'m currently developing has more than one class created, with a corresponding .xml file for each. My app requires progressing from one screen to the next

The app I'm currently developing has more than one class created, with a corresponding .xml file for each. My app requires progressing from one screen to the next after a calculation has been completed.

In one class, I have declared a public double called V, which is the result of a voltage calculation.

When the user presses "NEXT", a new class (ed: Activity?) is called, and the xml file will change the screen view to a new layout.

In this new class, I need to use the var开发者_运维知识库iable (double V) for a new calculation.

I thought that if a variable was public, it could be used anywhere in the package. Do I need to import this variable, or re-declare it somehow?

Any answers would be much appreciated. I've tried everything that I can think of, but Eclipse just keeps saying V cannot be resolved.


I'm assuming by "a new class is called", you're talking about launching a new Activity with an Intent, like so:

Intent intent = new Intent(this, Activity2.class);
startActivity(intent);

Assuming this is the case, you can just pass the variable along as an extra in the Intent object, and then retrieve it from the newly launched Activity. For example:

Intent intent = new Intent(this, Activity2.class);
intent.putExtra("voltage", V);
startActivity(intent);

Now, within your Activity2.java document, in your onCreate(), add this:

Intent intent = getIntent();
double V;
//return -1 if unable to retrieve
if(intent != null) V = intent.getDoubleExtra("voltage", -1);

Then V should be populated with the correct voltage value.

0

精彩评论

暂无评论...
验证码 换一张
取 消