简体   繁体   中英

Parcelable with arraylist<string> passing value from activity to fragment android

i need to send arraylist value from fragment to activity. I have tried with few codes but the return value is null.any help with code or tutorial of parcelable for arraylist<string> passing value from activity to fragment.

here's my code for passing arraylist :

Intent intent = getIntent();
intent.putExtra("key", selectImages);
setResult(RESULT_OK, intent);
 finish();      

here's Myparcelable class code:

import java.util.ArrayList;
import android.os.Parcel;
import android.os.Parcelable;

public class ObjectA implements Parcelable {

    public ArrayList<String> choices;

   public ObjectA (ArrayList<String> choices) {
             this.choices = choices;
    }
  @SuppressWarnings("unchecked")
    public ObjectA (Parcel parcel) {
          parcel.readArrayList(null);
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
         dest.writeStringList(choices);
    }

    // Method to recreate a ObjectA from a Parcel
    public static Creator<ObjectA> CREATOR = new Creator<ObjectA>() {

        @Override
        public ObjectA createFromParcel(Parcel source) {
            return new ObjectA(source);
        }

        @Override
        public ObjectA[] newArray(int size) {
            return new ObjectA[size];
        }
    };    
    }

here's code that used to extract in fragment(making it to display just to check the value):

    ArrayList<String> ar1 =  getActivity().getIntent().getParcelableExtra("key");
    Toast.makeText(getActivity(),
                    "Path of array in home Fragment: "+ar1,
                    Toast.LENGTH_LONG).show();

when i run the code the return value is null for ar1. where am i making mistake?

thanks,

    public void onActivityResult(int requestCode, int resultCode, Intent data){
            if (requestCode == 999) {           
                @SuppressWarnings("unchecked")
                ArrayList<String> ar1 =  data.getStringArrayListExtra("key"); 
                if(ar1.size()!= 0){
                for (int i = 0; i < ar1.size(); i++) {
                    String value = ar1.get(i);
                    Toast.makeText(getActivity(),
                            "Path of array in home Fragment: "+ar1,
                            Toast.LENGTH_LONG).show();
    }       }      }     }

Missed this Line: ArrayList<String> ar1 = data.getStringArrayListExtra("key"); thanks for the help

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