I have an instance of a Place Object
called spiliaBeach
which takes in the arguments you see below:
public PlaceObject spiliaBeach = new PlaceObject(R.string.spilia_beach,R.string.spilia_description,"2 Km from the Port",R.string.beach_category);
PlaceObject.java class:
private int name = 0;
private int description = 0;
private String locationDistance = "distance";
private int category = 0;
PlaceObject(int name, int description, String locationDistance, int category) {
this.name = name;
this.description = description;
this.locationDistance = locationDistance;
this.category = category;
}
In the MainActivity
i pass that data through a Bundle
to my DetailsActivity
like so :
Intent detailsIntent = new Intent(this, DetailsActivity.class);
Bundle intentBundle = new Bundle();
intentBundle.putInt("name",beachDB.spiliaBeach.getName());
intentBundle.putInt("description",beachDB.spiliaBeach.getDescription());
intentBundle.putString("distance",beachDB.spiliaBeach.getLocationDistance());
//Log.d(TAG,"Location distance : " + beachDB.spiliaBeach.getLocationDistance());
//intentBundle.putInt("category",beachDB.spiliaBeach.getCategory());
detailsIntent.putExtra("data",intentBundle);
startActivity(detailsIntent);
and try to retrieve it like this inside the onCreate()
of DetailsActivity
:
private void getIntentData(Intent intent) {
Bundle dataBundle = intent.getBundleExtra("data");
if(dataBundle != null) {
name = dataBundle.getInt(NAME_KEY);
description = dataBundle.getInt(DESC_KEY);
locationDistance = dataBundle.getString(LOC_DIST_KEY);
Log.d(TAG, "location distance : " + locationDistance + '\n' + "description : " + description);
} else {
Log.d(TAG,"Bundle is null");
}
}
but the logcat says that the locationDistance
variable is null
and it throws a ClassCastException
saying that the String returned cannot be cast to an Integer when nothing is an Integer directly in that line, right? Any ideas why?
Declare your PlaceObject
class as Parcelable and implement all required methods as per guide https://www.vogella.com/tutorials/AndroidParcelable/article.html
Then you will be able to save the object as
intentBundle.putParcelable(placeObject);
and retrieve it as
Bundle dataBundle = getIntent().getExtras();
PlaceObject object = (PlaceObject) dataBundle.getParcelable(KEY);
EDIT: you pass R.string.spilia_beach
which is integer id, in order to get a string use getString(R.string.spilia_beach) etc