Home > Software design >  How can i use a variable from an Activity to another Activty?
How can i use a variable from an Activity to another Activty?

Time:04-28

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?

CodePudding user response:

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
   }
}

CodePudding user response:

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.

  • Related