java - 通过 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
我尝试过不使用捆绑包和使用捆绑包,但似乎没有任何效果,如果我使用默认值,它总是会达到该值。如果有其他方法可以做到这一点,或者我做错了什么,我们将不胜感激。
解决方案
当您调用 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
推荐阅读
- bash - 更新焦油。bz2压缩文件
- c - 关于 do while 循环中的 continue 关键字的问题
- vue.js - Vue 表 2 setPage 方法在使用 fetch 后不起作用更多
- javascript - div toggle with another divs
- python - Python:在Windows剪贴板中将svg字符串复制为“image/svg+xml”格式,因此可以将其粘贴为svg图像
- html - 表格单元格与 Angular 7 中的表格标题不匹配
- gtk3 - 如何自定义标准 gtk_search_bar
- spring - 如何解决不支持的请求方法“GET”
- java - 优雅地处理java中的内存不足错误
- mysql - 使用 SELECT 语句更新多表导致:目标表不可更新