【问题标题】:Pass through Parcelable List<?> through bundle of activity通过 Parcelable List<?> 通过活动捆绑
【发布时间】:2015-03-09 14:09:36
【问题描述】:

如何通过Parcelable,一个List类型的对象在fragment中通过Bundle的Activity? 不断产生错误类型NPE,在OnCreateView中编写Parcelable。

// Fragment object в Activity
public Fragment systemFragList(){
          a = new AppsManagerFragment();
          b = new Bundle();
          dApps = new DataApps(this);
          //transmission through List the designer
          listCreater = new MakingListObject(dApps.getSystemAppsList()); 
          b.putParcelable("List", listCreater); // transfer Parcelable object through Bundle
          a.setArguments(b);

        return a;
    };

// Parcelable class
public class MakingListObject implements Parcelable {

    private List<ApplicationInfo> list;

 // get an object List <ApplicationInfo> constructor
    public MakingListObject(List<ApplicationInfo> l) { 
        this.list = l;
    }
    public MakingListObject(Parcel in) {
        in.readTypedList(list, ApplicationInfo.CREATOR); // read
    }
    public List<ApplicationInfo> getList(){ // vethod return list
        return list;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) { // write
       dest.writeTypedList(list);
    }
    @Override
    public int describeContents() {
        return 0;
    }

   CREATOR...
}

//Admission List to the Fragment in onCreateView()    
MakingListObject obj = (MakingListObject)this.getArguments().getParcelable("List"); // NPE ERROR
List<ApplicationInfo> listData = obj.getList();

【问题讨论】:

  • 请尝试更清楚地表达您的问题,很难理解您需要什么。
  • Emil,在 OnCreteView 中获取 Parcelable 时出现 NPE 错误。

标签: android list fragment parcelable


【解决方案1】:

使用Parcelable 的商店列表

Bundle dataToSend = new Bundle();
ArrayList<? super Parcelable> list = new ArrayList<>();

//add items here

并使用阅读它

Bundle receivedData = ...
receivedData.getParcelableArrayList("foo")

希望对你有帮助

【讨论】:

    【解决方案2】:

    你必须先初始化列表。

    public MakingListObject(Parcel in) {
        list = new ArrayList<ApplicationInfo>;
        in.readTypedList(list, ApplicationInfo.CREATOR); // read
    }
    

    【讨论】:

    • 代码可以看到构造函数初始化列表。尽管如此,我也尝试过,但仍然存在 NPE。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多