0

i declare int score = 100 in my 1st activity and use it to my 2nd activity, now the int score is declared as array in 2nd act. but its declared in local variable so how can i use it to my 3rd activity?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_level2);

    ans1 = findViewById(R.id.ans1);
    btn1 = findViewById(R.id.btn1);

   Intent i = getIntent();
    final int[] score2 = {i.getIntExtra("fscore", 0)};
   scr1 = (TextView) findViewById(R.id.scr1);
   scr1.setText(String.valueOf(score2[0]));

    btn1.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            String answer = ans1.getText().toString();
            if (score2[0] == 0)
            {
                Toast.makeText(getApplication(),"You Lose!", Toast.LENGTH_SHORT).show();
                gameover();
            }
            else
            {
                if (answer.equalsIgnoreCase("ANSWER2"))
                {
                    Toast.makeText(getApplication(),"CORRECT!!", Toast.LENGTH_SHORT).show();

                }

                else
                {
                    Toast.makeText(getApplication(),"Wrong Answer -10 Points", Toast.LENGTH_SHORT).show();
                    score2[0] = score2[0] - 10;
                    scr1.setText(String.valueOf(score2[0]));
                }

            }
        }
    });

}
public void gameover()
{

    Intent intent = new Intent(this, gameover.class);
    startActivity(intent);
}

}

1 Answers1

0

If you want to pass score on game over then your funtion body should look like :

    Intent intent = new Intent(this, gameover.class).putExtra("score",yourIntValue);
    startActivity(intent);

In your second activity :

intent.getIntExtra("score", defValue);  // store in a variable or add in an array

it will give you that int value you passed and you can either add it in your array or pass it to third activity using same method as above.

One thing I noticed that you got an int array because you tried making that variable final to use in inner functions right?

final int[] score2 = {i.getIntExtra("fscore", 0)};

Why don't you go for declaring a global scope variable with private access if you are using the same value multiple times.

private int score2;

assign it a value where you have written final int[ ] score2 = {i.getIntExtra("fscore", 0)};,

score2 = i.getIntExtra("fscore",0);

now use score2 wherever you want.There won't be a need of taking array here

Deep Patel
  • 2,584
  • 2
  • 15
  • 28