Home > Mobile >  Trying to pass data through Bundle always gives null
Trying to pass data through Bundle always gives null

Time:12-13

so i'm trying to build an android application that pops a button randomly on the screen and the user has to tap the button to get a better score, but there is a timer and when it hits 0 it should start a new activity which shows the final score.

I implemented a Countdown Timer that when onFinish() is triggered, the new activity is started through an intent that is also going to send the score variable to the new activity.

Thing is, this all works well except that when i use toast.makeText i can see that the variable passed is null.

here is my code for the countdown timer

new CountDownTimer(timeleftinmilliseconds, 1000) {

        public void onTick(long millisUntilFinished) {
            countdownText.setText(" time left : "   millisUntilFinished / 1000);
            timeleftinmilliseconds=millisUntilFinished;
        }

        public void onFinish() {
            Intent finalintent;

            finalintent = new Intent(PlayTime.this,ScoreScreen.class);
            finalintent.putExtra("key",score);


            startActivity(finalintent);
        }

    }.start();

and this is the code from the ScoreScreen activity that receives the score (now storred in previousscore)

void Capture(){

    Bundle bundle = getIntent().getExtras();
    String previousscore = bundle.getString("key");
    Toast.makeText(getApplicationContext(), "" previousscore, Toast.LENGTH_SHORT).show();

}

thank you for any help!

CodePudding user response:

You are receiving as string but you are passing integer as score . So you need to receive as integer .change code like this , it will work.

        Bundle bundle = getIntent().getExtras();
        int previousscore = bundle.getInt("key");
        Toast.makeText(getApplicationContext(), "" previousscore, Toast.LENGTH_SHORT).show();

CodePudding user response:

you have passed the data from intent and you are trying to receive the data from bundle. it isn't possible, you have to use intent to receive data. You can use it like this.

Intent intent = getIntent(); 
int previousscore = intent.getIntExtra(“key”);

Toast.makeText(getApplicationContext(), "" previousscore, Toast.LENGTH_SHORT).show();
  • Related