0

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.

3
  • Pass a Bundle with Intent. Commented Mar 3, 2013 at 17:42
  • @codingcrow putExtra() is fine. Commented Mar 3, 2013 at 17:47
  • @A--C Yes, it fine both the ways. Commented Mar 3, 2013 at 18:22

2 Answers 2

2

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); 
     ....
}
Sign up to request clarification or add additional context in comments.

3 Comments

Nope, didn't work, still 0. Just to be clear, this part is good: score.setText("Game over!\nYour score is:\n" + result); ? Also get the error "the local variable score is never read" for your int score.
@user2083882 now try it. i have edited my answer to make easy for you.
OK, now it works. I think it was some name conflict, cause my textview was also named score. Thanks a lot.
1

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

1 Comment

Sorry about the CamelCase. It didn't work. Still 0. Maybe I'm doing something wrong, although I copied your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.