Activity间传递double数据异常:无法在第二个Activity显示
Hey there! Let's dig into why your double population value isn't showing up in the Details Activity. The sending code you shared looks okay at a glance, but the problem almost always lies in how you're retrieving and displaying the value on the receiving end. Here are the most common fixes to check:
1. You're not retrieving the extra correctly in Details Activity
This is the #1 culprit. Make sure you're fetching the double value properly in the onCreate() method of your Details Activity, and then assigning it to your TextView. Here's the correct code pattern:
// Inside Details.java's onCreate() @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); // Get the double value from the Intent double population = getIntent().getDoubleExtra("Country_Population", 0.0); // 0.0 is a default value if the key isn't found (we'll talk about that next) // Assign it to your TextView (replace with your actual TextView ID) TextView populationTextView = findViewById(R.id.your_population_textview_id); populationTextView.setText(String.valueOf(population)); }
2. Mismatched Intent Extra Key
Double-check that the key you use to retrieve the value exactly matches the one you used to send it: "Country_Population". Intent extra keys are case-sensitive—so country_population or Country_population won't work. If the key doesn't match, getDoubleExtra() will return the default 0.0 value (which might show as "0.0" or be hidden if your TextView isn't properly set up).
3. Your TextView isn't properly referenced
Even if you retrieve the value correctly, if you haven't properly linked your TextView via findViewById(), nothing will show up. Double-check that the ID in findViewById() matches the one in your activity_details.xml layout file.
4. The source value is invalid
Before assuming the issue is with the Intent, confirm that pozycja.getPopulation() is returning a valid double value. Add a quick log statement right before sending the Intent to verify:
// In your click listener double populationToSend = pozycja.getPopulation(); Log.d("PopulationDebug", "Sending population: " + populationToSend); mIntent.putExtra("Country_Population", populationToSend);
If the log shows NaN, Infinity, or an unexpected value, the problem is with your data source, not the Intent transfer.
Start with checking the retrieval code and key match—those are the most likely fixes. Let me know if you still run into issues after trying these!
内容的提问来源于stack exchange,提问作者smitzer vojtech

