How to pass an array of Uri between Activity using Bundle

[亡魂溺海] 提交于 2019-12-30 09:33:49

问题


I need to pass an array of Uri to another activity, to pass an array of String I use simply

String[] images=getImagesPathString();

    Bundle b = new Bundle();
    b.putStringArray("images", images);

But using an array of Uri

 Uri[] imagesUri=getImagesUri();

this doesn't works because there isn't a method "putUri(Uri x)" in Bundle

How could I solve this problem?


回答1:


You should look into the Parcelable interface to see how to pass things on an intent

http://developer.android.com/intl/es/reference/android/os/Parcelable.html

Maybe you can implement a ParcelableUri class that implements that interface.

Like this (not tested!!):

public class ParcelableUri implements Parcelable {

private Uri[] uris;

public ParcelableUri(Parcel in) {
    Uri.Builder builder = new Uri.Builder();

    int lenght = in.readInt();
    for(int i=0; i<=lenght; i++){           
        uris[i]= builder.path(in.readString()).build();
    }
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(uris.length);
    for(int i=0; i<=uris.length; i++){
        dest.writeString(uris[i].toString());
    }
}

public static final Parcelable.Creator<ParcelableUri> CREATOR = new Parcelable.Creator<ParcelableUri>() {

    public ParcelableUri createFromParcel(Parcel in) {
        return new ParcelableUri(in);
    }

    public ParcelableUri[] newArray(int size) {
        return new ParcelableUri[size];
    }
};



回答2:


From what I know plain arrays cannot be put into Bundles. But you can put Uri-s into ArrayList and then call Bundle.putParcelableArrayList().

example:

 ArrayList<Uri> uris = new ArrayList<Uri>();
 // fill uris
 bundle.putParcelableArrayList(KEY_URIS, uris);

later on:

    ArrayList<Parcelable> uris =
            bundle.getParcelableArrayList(KEY_URIS);
    for (Parcelable p : uris) {
        Uri uri = (Uri) p;
    }



回答3:


Isn't the Uri parcelable? You can try to create an array of parcelable elements (Uri) and put it in the Bundle.




回答4:


You can use JSONObject to wrap any object and stringify it quickle. Going back from string to JSON is really trivial



来源:https://stackoverflow.com/questions/12943873/how-to-pass-an-array-of-uri-between-activity-using-bundle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!