getIntent().getStringExtra() shows null

2019-04-29 11:42发布

问题:

I m using one EditText field and one spinner. I have to pass teh results of both to the next Activity. here, reqd_bloodgroup is the spinner item, i converted into String using: reqd_bloodgrp = String.valueOf(spinner.getSelectedItem()); inside onItemSelected() of spinner.

intent.putExtra("city", citySelected.getText().toString());
intent.putExtra("bloodgroup", reqd_bloodgrp);
intent = new Intent(FindDonor.this,SpecificDonor.class);
startActivity(intent);

Here when i try to display these, there's no problem. They're correctly displayed. But when i try to fetch them in SpecificDonor activity, they show null values. The code used here is:

String text_city,text_bloodgroup;
text_city = getIntent().getStringExtra("city");
text_bloodgroup = getIntent().getStringExtra("bloodgroup");
Toast.makeText(getApplicationContext(), text_city + " " + "bloodgrp: " + text_bloodgroup, Toast.LENGTH_SHORT).show();

What could be the problem?

回答1:

I think that you must do the:

intent = new Intent(FindDonor.this,SpecificDonor.class);

before adding extras. Try with:

intent = new Intent(FindDonor.this,SpecificDonor.class);
intent.putExtra("city", citySelected.getText().toString());            
intent.putExtra("bloodgroup", reqd_bloodgrp);
startActivity(intent);