Passing Integer Between Activities and Intents in Android Is Always Resulting in Zero / Null

笑着哭i 提交于 2019-12-29 04:55:05

问题


I'm attempting to pass two integers from my Main Page activity (a latitude and longitude) to a second activity that contains an instance of Google Maps that will place a marker at the lat and long provided. My conundrum is that when I retrieve the bundle in the Map_Page activity the integers I passed are always 0, which is the default when they are Null. Does anyone see anything glaringly wrong?

I have the following stored in a button click OnClick method.

Bundle dataBundle = new Bundle();

dataBundle.putInt("LatValue", 39485000);
dataBundle.putInt("LongValue", -80142777);
Intent myIntent = new Intent();
myIntent.setClassName("com.name.tlc", "com.name.tlc.map_page");
myIntent.putExtras(dataBundle);
startActivity(myIntent);

Then in my map_page activity I have the following in onCreate to pick up the data.

Bundle extras = getIntent().getExtras(); 
System.out.println("Get Intent done");
if(extras !=null)
{
    System.out.println("Let's get the values");
    int latValue = extras.getInt("latValue");
    int longValue = extras.getInt("longValue");

    System.out.println("latValue = " + latValue + " longValue = " + longValue);

}

回答1:


System.out.println("Let's get the values");
int latValue = extras.getInt("latValue");
int longValue = extras.getInt("longValue");

Not the same as

myIntent.putExtra("LatValue", (int)39485000);
myIntent.putExtra("LongValue", (int)-80142777);

Also it might be because you do not keep the name of the Int exactly the same throughout your code. Java and the Android SDK are Case-sensitive




回答2:


Geeklat,

You don't need to use Bundle in this case.

Do your puts like this...

Intent myIntent = new Intent();
myIntent.setClassName("com.name.tlc", "com.name.tlc.map_page");
myIntent.putExtra("LatValue", (int)39485000);
myIntent.putExtra("LongValue", (int)-80142777);
startActivity(myIntent);

Then you can retrieve them with...

Bundle extras = getIntent().getExtras();
int latValue = extras.getInt("LatValue");
int longValue = extras.getInt("LongValue");


来源:https://stackoverflow.com/questions/5424135/passing-integer-between-activities-and-intents-in-android-is-always-resulting-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!