【问题标题】:ArrayList not received from one Fragment to another using bundle and Parcelable [duplicate]ArrayList 未使用 bundle 和 Parcelable 从一个 Fragment 接收到另一个 Fragment [重复]
【发布时间】:2018-02-15 06:31:36
【问题描述】:

我正在将ArrayList 从一个Fragment 传递给另一个。我正在使用Parcelable 来实现这一点。我正在使用Bundle 传递ArrayList。但是在另一个片段中我无法接收到这个.
这是 实现 Parelable

的类的代码
public class CurrentEntry implements Parcelable{

     String name;
     String people;
     String estimate;



    public CurrentEntry()
    {

    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPeople() {
        return people;
    }

    public void setPeople(String people) {
        this.people = people;
    }

    public String getEstimate() {
        return estimate;
    }

    public void setEstimate(String estimate) {
        this.estimate = estimate;
    }


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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.name);
        dest.writeString(this.people);
        dest.writeString(this.estimate);
    }

    public static final Parcelable.Creator<CurrentEntry> CREATOR
            = new Parcelable.Creator<CurrentEntry>() {
        public CurrentEntry createFromParcel(Parcel in) {
            return new CurrentEntry(in);
        }

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

    public CurrentEntry(Parcel in)
    {
        this.name=in.readString();
        this.people=in.readString();
        this.estimate=in.readString();
    }
}  

这是将 ArrayList 从一个 Fragment 发送到另一个 Fragment 的代码。

JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                   try
                   {

                       JSONObject object=new JSONObject(response.toString());


                       JSONArray data=object.getJSONArray("results");

                       for( i=0;i<data.length();i++)
                       {
                           JSONObject json = data.getJSONObject(i);
                           final CurrentEntry c=new CurrentEntry();
                           userUrl=json.getString("list");
                           JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, userUrl, null, new Response.Listener<JSONObject>() {
                               @Override
                               public void onResponse(JSONObject response) {
                                   try {
                                       JSONObject temp=response.getJSONObject("user");

                                       String foodie_name=temp.getString("first_name");
                                           String lname=temp.getString("last_name");
                                       c.setName(name+"\t"+lname);
                                       progressDialog.dismiss();

                                   } catch (JSONException e) {
                                       e.printStackTrace();
                                   }
                                 //  adapt.notifyDataSetChanged();
                               }
                           }, new Response.ErrorListener() {
                               @Override
                               public void onErrorResponse(VolleyError error) {

                               }
                           })

                           AppController.getInstance().addToRequestQueue(request,second_req);
                           c.setPeople(json.getString("no_people"));
                           String temp=json.getString("predicated_t");
                           c.setEstimate(temp+"min");
                         //  c.setNo(count);
                           TempUserStatusInfo info=new TempUserStatusInfo();
                           Bundle bundle=new Bundle();
                           bundle.putParcelable("myList",c);
                           info.setArguments(bundle);
                           current.add(c);
                           adapt=new NewAdapter(current,getActivity().getApplicationContext());
                           recyclerView.setAdapter(adapt);

                        }


                }
                   catch (JSONException e)
                   {
                       e.printStackTrace();
                   }

                }  

这是接收我设置SwipeCards的ArrayList的代码

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v=inflater.inflate(R.layout.temp_user_status_info, container, false);
        swipeCardsView=(SwipeCardsView)v.findViewById(R.id.swipeCard);
        infoAdapter=new CurrentInfoAdapter(info,getActivity());
        swipeCardsView.retainLastCard(false);
        swipeCardsView.enableSwipe(true);
        CurrentInfo currentInfo=new CurrentInfo();

        Bundle bundle=this.getArguments();
        if(bundle!=null){
            currentInfo=bundle.getParcelable("myList");
        }


        person_name=getArguments().getString("name");
        person_people=getArguments().getString("people");
        person_estimate=getArguments().getString("estimate");

        currentInfo.setName(person_name);
        currentInfo.setPeople(person_people);
        currentInfo.setEstimate(person_estimate);
        Log.i("name",person_name);
        Log.i("people",person_people);
        Log.i("estimate",person_estimate);
        info.add(currentInfo);
        swipeCardsView.setAdapter(infoAdapter);
        return v;
    }  

错误是

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String)' on a null object reference
                                                                         at biz.fyra.QueueApp.TempUserStatusInfo.onCreateView(TempUserStatusInfo.java:52)
                                                                         at android.support.v4.app.Fragment.performCreateView(Fragment.java:2248)
                                                                         at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1340)
                                                                     at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1569)

【问题讨论】:

  • 请停止对类名使用 [tag] 降价。相反,使用正确的名称 - 例如,ArrayList - 并用反引号括起来,` - ArrayList

标签: android android-fragments arraylist bundle parcelable


【解决方案1】:

问题是您没有设置字符串值,而是您尝试接收该值。这就是为什么你得到空指针异常。也传递字符串值。

TempUserStatusInfo info=new TempUserStatusInfo();
                       Bundle bundle=new Bundle();
                       bundle.putParcelable("myList",c) 
    bundle.putString("name",value);
    bundle.putString("people",value);
    bundle.putString("estimate",value);

【讨论】:

    【解决方案2】:

    使用正确的arraylist发送parceable arraylist而不是类对象

    putParcelableArrayListExtra("list", infoArrayList);
    

    自定义对象数组列表在哪里

    ArrayList<CurrentInfo> infoArrayList;
    

    在接收Fragment 类中使用这个

    ArrayList<CurrentInfo> infoArrayList = bundle.getParcelableArrayListExtra("list");
    

    【讨论】:

    • 不兼容类型给我错误
    • 你用过这个类 CurrentEntry 吗?
    • 是的,这是我的 ArrayList 自定义对象
    • 好的,让它可解析并使用它
    【解决方案3】:

    另一个想法是使用 Gson 生成 json 对象,然后将它的字符串发送该字符串,另一端再次使用 Gson 从该 json 字符串生成对象。

    将 Java 对象转换为 JSON

    Gson gson = new Gson();
    Staff obj = new Staff();
    String jsonInString = gson.toJson(obj);
    

    从 json 还原为对象:

    Gson gson = new Gson();
    Staff staff = gson.fromJson(jsonInString, Staff.class);
    

    将以下依赖项添加到您的 gradle 文件中:

    <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.6.2</version>
    </dependency>
    

    通过这样做,您不必序列化/反序列化,您可以将其作为字符串发送。

    【讨论】:

      【解决方案4】:

      您可以为此使用Serializable

      //for putting in bundle
      bundle.putSerializable("key", class_value)
      
      //for receieving
      object = arguments.getSerializable("key") as className
      

      不要忘记使用serializable 扩展类。

      【讨论】:

        【解决方案5】:

        尝试像这样将 arraylist 一个片段传递给另一个片段

        你的第一个片段

        ArrayList<ParcelableRow> parceArrayList = new ArrayList<ParcelableRow>();
        Bundle bundle=new Bundle(); bundle.putParcelableArrayListExtra("yourArraylist",parceArrayList);
        

        在其他 Fragment 中获取 Arraylist

        ArrayList<ParcelableRow> result = data.getParcelableArrayList("yourArraylist");
        

        【讨论】:

        • 收到 ArrayList 不兼容类型时出现错误。必需:ArrayList 找到:ArrayList
        • 你是如何接收arraylist的,你能显示代码吗?
        • ArrayList current=getArguments().getParcelableArrayList("MyList");
        • 你在 CurrentInfo 类中实现了 Parcelable 吗?
        • 否。有没有需要在 CurrentEntry 和 CurrentInfo 中实现 Parcelable 的情况?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-19
        • 2016-07-16
        • 2014-08-24
        相关资源
        最近更新 更多