getFloatExtra() always returning the default value

Viewed 552

I am new to Android dev. I am trying to pass rating information from one activity to another activity. But the second activity does not seem to be receiving the value that I am passing through getFloatExtra, rather it's taking the default value. Please help me identify what I'm doing wrong.

Here is my First Activity:

public class FirstActivity extends AppCompatActivity {

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

    public void enter(View view) {
        RatingBar vRatingBar = (RatingBar) findViewById(R.id.ratingBar);
        float rate = vRatingBar.getRating();

        Intent goToSecond = new Intent();
        goToSecond.setClass(getApplicationContext(),SecondActivity.class);
        goToSecond.putExtra("stars",rate);
        startActivity(goToSecond);
    }
}

Here is my Second Activity:

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        Intent caller = new Intent();
        Float rating = caller.getFloatExtra("stars",0.0f);
        TextView vTextView = (TextView) findViewById(R.id.textViewSecondActivity);
        vTextView.setText("Welcome to The Second Activity. Your Rating:" + rating);
    }
}

And the output is attached as an image The First Activity, clicking the button will take to The Second Activity

The Second Activity

1 Answers

In the second activity you are creating a new Intent()

Replace:

Intent caller = new Intent();

by

Intent caller = getIntent();

    Bundle bundle = caller.getExtras();
    if(bundle!=null){
    float rating= bundle.getFloat("stars",0.0f);
    //continue...
   TextView vTextView = (TextView) findViewById(R.id.textViewSecondActivity);
        vTextView.setText("Welcome to The Second Activity. Your Rating:" + rating);
    }
Related