'How can i use a variable from an Activity to another Activty?
In my MainActivity i have a score variable,
int score = 0;
however i have another activity which is the DisplayScore activity (which displays the score) txtFinalScore.setText("Score: " + score);
how can i use that same variable form my MainActivity to my DisplayScore activity so that i can display the score?
Solution 1:[1]
If I've understood well, here's how you should do it.
public class Main {
public static void main(String[] args) {
int score = 0; // the main activity thing
int displayScore = score; // the thing to use the same value as score
System.out.println("Score : " + displayScore); // to simulate the setText
}
}
Solution 2:[2]
This question explains perfectly how to use putExtra() and getExtra() methods for the Intent in Android, because I think that's what you need.
Also, if you find this difficult, you can store the score value into a sharedPreference and retrieve it from another activity. You can see the docs here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
| Solution 2 | AhmedSHA256 |
