将对象列表传递给另一个活动

时间:2015-07-29 14:27:15

标签: java android android-listview google-maps-markers android-arrayadapter

在我的代码中,我通过在地图上放置标记并从用户获取其值然后将其存储在列表中来创建区域对象。然后我使用parcelableArrayList将此列表传递给另一个活动。我想要的是用户只按下displayArea按钮然后启动此活动并在AllAreas activty中显示列表。但是,每当我点击该按钮时,我的应用程序就崩溃了

mapActivity的代码

 public class MainActivity extends    
 FragmentActivity implements View.OnClickListener,MapDropdown.DialogListener {

public static final String mapLongitude="longitude";
public static final String mapLatitude="latitude";
FragmentManager fm = getSupportFragmentManager();
Button displayareas;
Switch deleteareas;
private boolean del = false;
private int set = 0;
public ArrayList<Area> areas;


private GoogleMap newmap; // Might be null if Google Play services APK is not available.
LatLng m;
float radius;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    displayareas = (Button) findViewById(R.id.display);
    displayareas.setOnClickListener(this);
    deleteareas = (Switch) findViewById(R.id.delete);
    areas = new ArrayList<Area>();
    deleteareas.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                                     boolean isChecked) {

            if (isChecked) {
                del = true;
                Toast.makeText(getApplicationContext(), "Deleting enabled", Toast.LENGTH_LONG).show();
            } else {
                del = false;
                Toast.makeText(getApplicationContext(), "Deleting disabled", Toast.LENGTH_LONG).show();
            }

        }
    });
    Log.d("Map","MapCreated");
    setUpMapIfNeeded();

}
@Override
public void onClick(View v) {
    if (v.getId() == R.id.display) {
        Intent intent = new Intent(getApplicationContext(),AllAreas.class);
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("data", areas);
        intent.putExtras(bundle);
        startActivity(intent);

    }

}

@Override
protected void onResume() {
    super.onResume();
    //setUpMapIfNeeded();
}


private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (newmap == null) {
        // Try to obtain the map from the SupportMapFragment.
        newmap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (newmap != null) {
            setUpMap();
            Log.d("MAPS","Map working");


        }
        else Log.d("MAPS","not working");

    }
}


private void setUpMap() {

    newmap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));

    // Enable MyLocation Layer of Google Map
    newmap.setMyLocationEnabled(true);

    // Get LocationManager object from System Service LOCATION_SERVICE
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // Create a criteria object to retrieve provider
    Criteria criteria = new Criteria();

    // Get the name of the best provider
    String provider = locationManager.getBestProvider(criteria, true);

    // Get Current Location
    Location myLocation = locationManager.getLastKnownLocation(provider);

    // set map type
    newmap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    // Get latitude of the current location
    double latitude = myLocation.getLatitude();

    // Get longitude of the current location
    double longitude = myLocation.getLongitude();

    // Create a LatLng object for the current location
    LatLng latLng = new LatLng(latitude, longitude);

    // Show the current location in Google Map
    newmap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    // Zoom in the Google Map
    newmap.animateCamera(CameraUpdateFactory.zoomTo(20));
    newmap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My location"));

    Log.d("LATITUDE",String.valueOf(latitude));
    Log.d("LONGITUDE",String.valueOf(longitude));
    GoogleMap.OnMarkerClickListener listener = new GoogleMap.OnMarkerClickListener() {

        @Override
        public boolean onMarkerClick(final Marker marker) {
            if(del == false){
                m=marker.getPosition();

           MapDropdown dFragment = new MapDropdown();
            // Show DialogFragment
            dFragment.show(fm, "Dialog Fragment");}
            else if(del == true){
                marker.remove();
            }
            return true;


        }

    };

    newmap.setOnMarkerClickListener(listener);

    newmap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

        @Override
        public void onMapClick(LatLng latLng) {

            // Creating a marker
            MarkerOptions markerOptions = new MarkerOptions();

            // Setting the position for the marker
            markerOptions.position(latLng);

            // Setting the title for the marker.
            // This will be displayed on taping the marker
            markerOptions.title(latLng.latitude + " : " + latLng.longitude);


            // Animating to the touched position
            newmap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

            // Placing a marker on the touched position
            Marker mmarker = newmap.addMarker(markerOptions);
            m = latLng;
            Log.d("ADDED LATITUDE",String.valueOf(latLng.latitude));
            Log.d("ADDED LONGITUDE",String.valueOf(latLng.longitude));

            Toast.makeText(getApplicationContext(),"Block area updated",Toast.LENGTH_LONG).show();





        }
    });

}
@Override
public void onDialogPositiveClick(DialogFragment dialog , String s, String n){
    Log.d("Button","positive");
    Log.d("Name",n);
    Log.d("Radius",s);

    Log.d("On press LATITUDE",String.valueOf(m.latitude));
    Log.d("On press LONGITUDE",String.valueOf(m.longitude));
    Area newarea = new Area(n,m.latitude,m.longitude,Float.valueOf(s));
    Log.d("object",newarea.getId());
    Log.d("object",newarea.getName());
    areas.add(newarea);
    areas.get(0);
    Log.d("areas",areas.get(0).getName());



}
@Override
public void onDialogNegativeClick(DialogFragment dialog){
Log.d("Button","negative");

  }
 }

添加到列表的mainActivity.java的一部分是

@Override
public void onDialogPositiveClick(DialogFragment dialog , String s,
 String    n){
    Log.d("Button","positive");
   //areas is list name
    //m is current marker
    Area newarea = new Area(n,m.latitude,m.longitude,Float.valueOf(s));

    areas.add(newarea);



}

在mainactivity中传递列表是

public void onClick(View v) {
 //id of button that will launch Allareas activity
    if (v.getId() == R.id.display) {
        Intent intent = new Intent(getApplicationContext(),AllAreas.class);
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("data", areas);
        intent.putExtras(bundle);
        startActivity(intent);

    }

}

for AllAreas class

public class AllAreas extends ActionBarActivity {
//initial  layout
private Area a;
@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.areas);


    Bundle bundle = getIntent().getExtras();
    ArrayList<Area> arealist = bundle.getParcelableArrayList("mylist");
    if (arealist.isEmpty()) {
        Log.d("area list lala", "is empty");


    }
    else {
        for (int i = 0; i < arealist.size(); i++) {
            a = arealist.get(0);
            Log.d("area list lala", a.getName());
        }

    }
}

}

1 个答案:

答案 0 :(得分:0)

你得到错误的密钥。你使用密钥“数据”把它放入捆绑包并试图通过密钥“mylist”得到它

bundle.putParcelableArrayList("data", areas);

更改行

ArrayList<Area> arealist = bundle.getParcelableArrayList("mylist");

ArrayList<Area> arealist = bundle.getParcelableArrayList("data");

让我知道它是否有效。