Nabukodonosor
Nabukodonosor

Reputation: 699

How to pass an integer variable to another class

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.

Upvotes: 0

Views: 1391

Answers (2)

Ajay S
Ajay S

Reputation: 48602

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); 
     ....
}

Upvotes: 2

Android Killer
Android Killer

Reputation: 18499

First of all the variable name you have given is not good as it is not following CamelCase

so it should be result rather than Result.Now try as follows:

In Quiz Activity

Intent intent = new Intent(getApplicationContext(),Result.class);
intent.putExtra("result_variable", result);
startActivity(intent);

In Result Activity

getIntent().getIntExtra("result_variable", 0);

Upvotes: 1

Related Questions