I have a problem that I am trying to solve for few hours but cannot solve it and I need some help. I am trying to retrieve URL strings from a Login activity and trying to pass it to the Main activity using a parcelable object but I receive NullPointerException on getParcelable method.
Following is the code that creates the URL parcelable object and puts it to Intent and calls the Main activity
public void onGetPremiumURLCompletion(List<String> urls){ String[] urlList = new String[urls.size()]; for (int i = 0; i < urls.size(); i++) {urlList[i] = urls.get(i);} URL urlParcelable = new URL(urlList); for (int i = 0; i < urlParcelable.getUrls().length; i++) {Log.w("url from parcelable",urlParcelable.getUrls()[i]);} Intent intent = new Intent(this,Home.class); intent.putExtra("PremiumURLList",urlParcelable); progress.dismiss(); startActivity(intent); }
And the following is the URL parcelable class
public class URL implements Parcelable { private String[] urls; public static final Parcelable.Creator<URL> CREATOR = new Parcelable.Creator<URL>() { public URL createFromParcel(Parcel in) { return new URL(in); } public URL[] newArray(int size) { return new URL[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeStringArray(urls); } private URL(Parcel in) { in.readStringArray(urls); } public URL(String[] urlList){ urls = urlList; } public String[] getUrls() { return urls; }}
Here is how I am receiving the parcelable object from the intent.
Bundle b = getIntent().getExtras(); URL urlList = b.getParcelable("PremiumURLList");
I am getting the following error on getParcelable line
Caused by: java.lang.NullPointerException at android.os.Parcel.readStringArray(Parcel.java:962) at com.rayat.pricewiz.entity.URL.<init>(URL.java:33) at com.rayat.pricewiz.entity.URL.<init>(URL.java:9) at com.rayat.pricewiz.entity.URL$1.createFromParcel(URL.java:14) at com.rayat.pricewiz.entity.URL$1.createFromParcel(URL.java:12) at android.os.Parcel.readParcelable(Parcel.java:2104) at android.os.Parcel.readValue(Parcel.java:2013) at android.os.Parcel.readArrayMapInternal(Parcel.java:2314) at android.os.Bundle.unparcel(Bundle.java:249) at android.os.Bundle.getParcelable(Bundle.java:1206) at com.rayat.pricewiz.view.activity.tabhome.Home.onCreate(Home.java:72) at android.app.Activity.performCreate(Activity.java:5426) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
Please help.
Thanks
Advertisement
Answer
Your problem is here:
private URL(Parcel in) { in.readStringArray(urls); }
urls
is null at this point, and the readStringArray(String[])
method expects a parameter that is non-null, and the same length as the resulting read array. I find that method to be nearly useless as it doesn’t really work unless you know in advance a fixed size for the array. Alternatively, I suggest you use createStringArray()
:
private URL(Parcel in) { urls = in.createStringArray(); }