简体   繁体   中英

Passing object list to another activity

In my code I am creating an area object by placing markers on map and taking its values from user then storing it in a list. Then I used parcelableArrayList to pass this list to another activity. What I want is that user presses displayArea button only then this activity is launched and list is displayed in AllAreas activty. But my app crashes whenever I click that button

Code for 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");

  }
 }

Part of mainActivity.java adding to list is

@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);



}

And of passing list in mainactivity is

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());
        }

    }
}

}

You are getting it with wrong key.you used the key "data" for putting it into bundle and trying to get it by the key "mylist"

bundle.putParcelableArrayList("data", areas);

change the line

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

to

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

let me know if it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM