首页 > 解决方案 > 通过 intnet 和 Bundle Java Android Studio 传递值

问题描述

我一直在尝试将坐标从一个活动传递到另一个活动,一个纬度和一个经度。在我的 Activity1 中,我有:

Intent intent = new Intent(FindLocation.this, FinalRestaurant.class);
Bundle extras = new Bundle();
extras.putDouble ("LocationLat", currentMarkerLocation.latitude);
extras.putDouble ("LocationLng", currentMarkerLocation.longitude);
intent.putExtras(extras);

Toast.makeText(FindLocation.this, currentMarkerLocation.latitude + ", " + currentMarkerLocation.longitude, Toast.LENGTH_LONG).show();

在我的第二个活动中,我有:

Bundle bundle = getIntent().getExtras();
lat = bundle.getDouble("LocationLat");
lng = bundle.getDouble("LocationLng");

Toast.makeText(FinalRestaurant.this, lat + ", " + lng, Toast.LENGTH_LONG).show();

我的应用程序只是崩溃并且没有进入第二个活动,因为捆绑包为空。确切的错误: Attempt to invoke virtual method 'double android.os.Bundle.getDouble(java.lang.String)' on a null object reference

我尝试过不使用捆绑包和使用捆绑包,但似乎没有任何效果,如果我使用默认值,它总是会达到该值。如果有其他方法可以做到这一点,或者我做错了什么,我们将不胜感激。

标签: javaandroidandroid-intentandroid-bundle

解决方案


当您调用 startActivity 时,您只是以新的意图调用它,而不将包传递给它。

所以不要这样称呼

startActivity(new Intent(Activity1.this, Activity2.class));

像这样称呼它

Intent intent = new Intent(FindLocation.this, FinalRestaurant.class);
Bundle extras = new Bundle();
extras.putDouble ("LocationLat", currentMarkerLocation.latitude);
extras.putDouble ("LocationLng", currentMarkerLocation.longitude);
intent.putExtras(extras);
startActivity(intent);  // Pass Intent created here 

推荐阅读