Dik*_*sha 1 android location arraylist android-intent
我要做的是将一个位置列表传递给地图活动并将标记放在这些位置上.我已尝试在MainActivity中使用
public class MainActivity extends AppCompatActivity implements Parcelable {
ArrayList<Location> locs=new ArrayList<>();
...
locs.add(location);
...
Intent in = new Intent(context,MapsActivity.class);
in.putExtra("setlocations",locs);
startActivity(in);
...
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeList(locs);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在MapsActivity的onCreate()中
Bundle extras = getIntent().getExtras();
if(extras != null){
locs=(ArrayList<Location>)getIntent().getParcelableExtra("setlocations");
addMarkeratLocation();
}
Run Code Online (Sandbox Code Playgroud)
该addMarkeratLocation()方法使用locslist来使用for循环添加标记
public void addMarkeratLocation(){
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.mipmap.dott);
LatLng addpoint=new LatLng(0.0,0.0);
for(int i=0;i<locs.size();i++){
addpoint = new LatLng(locs.get(i).getLatitude(), locs.get(i).getLongitude());
mMap.addMarker(new MarkerOptions().position(addpoint).icon(icon));
}
mMap.moveCamera(CameraUpdateFactory.newLatLng(addpoint));
}
Run Code Online (Sandbox Code Playgroud)
触发意图时我的应用程序崩溃了.logcat显示
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
为什么显示null?这是我第一次使用Parcelable界面..有什么我想念的吗?任何意见都将不胜感激,谢谢.
`Location` class is not a Parcalable class.
Run Code Online (Sandbox Code Playgroud)
Intent.putExtra()函数只接受原始和Parcelable数据类型.所以你无法List<Location>通过意图.相反,您可以使用Gson库来序列化Location的arraylist并将其作为Json字符串传递给MapActivityIn ,并将MapActivityJson字符串反序列化为Location数组.
| 归档时间: |
|
| 查看次数: |
252 次 |
| 最近记录: |