11

How to pass an integer variable to another class

 3 years ago
source link: https://www.codesd.com/item/how-to-pass-an-integer-variable-to-another-class.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to pass an integer variable to another class

advertisements

I have one class with public int Result; Later in the game I use that variable to store number of points user makes. Now, I have another activity/class called Result and I have a textView in that activity and I need to use the Result variable to sexText to that textView. I made an instance of my game class and called it g in the Result class and than I did something like this:

score = (TextView) findViewById(R.id.tvResult);
        score.setText("Game over!\nYour score is:\n" + k.Result);

But I always get 0. I think it's because I get default value of the variable, not the real one. How can I pass the final value added to my variable after game ends?

I also tried this in the game activity, to pass the variable as an intent:

Intent i = new Intent(Quiz.this, Result.class);
            i.putExtra("newResultVariable", Result);
            startActivity(i);

Also get 0.


To pass the variable as an intent.

To do programming in any language you should follow naming convention of language.

In Quiz.java

Intent intent = new Intent(context,Result.class);
intent.putExtra("newResultVariable", result);
startActivity(intent);

In Result.java to get value.

public void onCreate(Bundle bundle) {
    ....
    int score = 0;
    TextView scoreTextView = (TextView) findViewById(R.id.tvResult);

    Bundle extras = getIntent().getExtras();
    if(extras !=null) {
       score = extras.getInt("newResultVariable", 0);
    }

     scoreTextView.setText("Game over!\nYour score is:\n" + score);
     ....
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK