NullPointerException when sending a StringArray using Parcelable… here is a solution to the problem.
NullPointerException when sending a StringArray using Parcelable
I’m having a strange problem sending an intent with a parcelable object. This object has an array of strings. How to send an object from one Android Activity to another using Intents? I first create my object as packageable and then send it. Here is my code fragment:
public class MyObject implements Parcelable{
private String _title = null;
private String[] _genre;
private int _time = 0;
private String _disc = null;
private static final String TAG = "MyObject";
public MyObject (String title, String[] genre, int time, String disc) {
_title = title;
_genre = genre;
_time = time;
_disc = disc;
}
public MyObject(Parcel source) {
/*
* Reconstruct from the Parcel
*/
Log.v(TAG, "ParcelData(Parcel source): time to put back parcel data");
_title = source.readString();
try{
source.readStringArray(_genre);
}catch(Exception e){
Log.e(TAG,e.toString());
}
_time = source.readInt();
_disc = source.readString();
}
/*... Getters and setters and other stuff...*/
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
Log.v(TAG, "writeToParcel..."+ flags);
dest.writeString(_title);
dest.writeStringArray(_genre);
dest.writeInt(_time);
dest.writeString(_disc);
Log.i(TAG,_genre[0]);
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<MyObject> CREATOR = new Parcelable.Creator<MyObject>() {
public MyObject createFromParcel(Parcel in) {
return new MyObject(in);
}
public MyObject[] newArray(int size) {
return new MyObject[size];
}
};
}
It seems okay to send.
Intent displayInfo = new Intent(getApplicationContext(), MovieInfo.class);
displayInfo.putExtra(OBJECT, mySQLiteAdapter.getEntry(idSet));
startActivity(displayInfo);
However, when I try to get this data
Intent intent = getIntent();
myParcel = (MyObject) intent.getParcelableExtra(FBM2Activity.OBJECT);
I get NullPointerException from readStringArray. Does anyone know where I might go wrong?
Solution
Use _genre = source.createStringArray()
.
The reason behind this is that the expectation is readStringArray(String[] val)
an array element that has already been created String[]
with the val
correct number. When_genre
you call source.readStringArray(_genre)
, is . null