可以使用arraylist <string>将值从活动传递到片段android </string>

时间:2014-12-31 07:51:43

标签: android android-fragments arraylist parcelable

我需要从片段到​​活动发送arraylist值。我尝试过几个代码,但返回值为null。对arraylist<string>的parcelable代码或教程提供帮助,将值从活动传递到片段。

这是我传递arraylist的代码:

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

这里是Myparcelable类代码:

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];
        }
    };    
    }

这里的代码用于在片段中提取(使其显示只是为了检查值):

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

当我运行代码时,ar1的返回值为null。我在哪里弄错了?

感谢,

1 个答案:

答案 0 :(得分:2)

    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();
    }       }      }     }

错过了这一行:ArrayList<String> ar1 = data.getStringArrayListExtra("key"); 谢谢你的帮助