我正在尝试做的是传递位置列表以映射活动并将标记放在这些位置上。我试过在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);

}
}


然后在MapsActivity的onCreate()中

 Bundle extras = getIntent().getExtras();
    if(extras != null){
        locs=(ArrayList<Location>)getIntent().getParcelableExtra("setlocations");
        addMarkeratLocation();
    }


addMarkeratLocation()方法使用locs列表使用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));
}


触发意图时,我的应用程序崩溃。日志显示
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
为什么显示null?这是我第一次使用Parcelable接口。我缺少什么吗?任何输入将不胜感激,谢谢。

最佳答案

步骤1:首先使用Gradle脚本导入Gson库

在您的Gradle依赖项中添加此行

dependencies {
    compile 'com.google.code.gson:gson:2.7'
}


步骤2:将List转换为JSON字符串,并将JSON字符串从MainActivity传递到MapsActivity

        Location location1 = new Location("");
        location1.setLatitude(12.124);
        location1.setLongitude(77.124);
        Location location2 = new Location("");
        location2.setLatitude(12.765);
        location2.setLatitude(77.8965);

        List<Location> locations = new ArrayList<Location>();
        locations.add(location1);
        locations.add(location2);

        Gson gson = new Gson();
        String jsonString = gson.toJson(locations);
        Intent intent = new Intent(MainActivity.this,MapsActivity.class);
        intent.putExtra("KEY_LOCATIONS",jsonString);
        startActivity(intent);


步骤3:从Bundle中获取JSON字符串,并将其转换为List

        Bundle bundle = getIntent().getExtras();
        String jsonString = bundle.getString("KEY_LOCATIONS");

        Gson gson = new Gson();
        Type listOfLocationType = new TypeToken<List<Location>>() {}.getType();
        List<Location> locations = gson.fromJson(jsonString,listOfLocationType );


希望对您有帮助!!

09-25 21:46