Java 如何使用 Intent.putParcelableArrayListExtra() 方法和 Parcelable 接口,我只想在两个活动之间传输数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20138757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:26:40  来源:igfitidea点击:

How to use Intent.putParcelableArrayListExtra() method and the Parcelable interface, I just want to transfer data in between two activity

javaandroid

提问by JulyChobits

Look at my code, wheather wrong in it.

看看我的代码,不管有没有错。

Activity one:

活动一:

Intent intent = new Intent(SendActivity.this, PickContactsActivity.class);
startActivityForResult(intent, 20);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        ArrayList<PickBean> cons = data.getParcelableArrayListExtra("data");
        for (int i = 0; i < cons.size(); i++) {
            JLog.e(LOG_TAG, "displayName:" + cons.get(i).displayName + "displayNumber" + cons.get(i).displayNumber);
        }
    }
}

Activity two:

活动二:

Intent data = new Intent();
ArrayList<PickBean> cons = new ArrayList<PickBean>();
for (int i = 0; i < conData.size(); i++) {
        cons.add(new PickBean(conData.get(i).displayName, conData.get(i).displayNumber));
    }
}
data.putParcelableArrayListExtra("data", cons);
setResult(RESULT_OK, data);
finish();

The PickBean code:

PickBean 代码:

public class PickBean implements Parcelable {
    public String displayName;
    public String displayNumber;

    public boolean selected = false;

    public PickBean() {
        super();
    }

    public PickBean(String displayName, String displayNumber) {
        super();
        this.displayName = displayName;
        this.displayNumber = displayNumber;
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(displayName);
        dest.writeString(displayNumber);
    }


    public final Parcelable.Creator<PickBean> CREATOR = new Parcelable.Creator<PickBean>() { 
        @Override 
        public PickBean createFromParcel(Parcel source) { 

            return new PickBean(source.readString(), source.readString()); 
        } 

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

It will always throws

它总是会抛出

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=20,
result=-1, data=Intent { (has extras) }} to activity 
{com.chishacai.smscenter/com.chishacai.smscenter.SendActivity}: java.lang.NullPointerException: expected receiver of type 

com.chishacai.smscenter.bean.PickBean, but got null

com.chishacai.smscenter.bean.PickBean,但为空

Caused by: java.lang.NullPointerException: expected receiver of type 
com.chishacai.smscenter.bean.PickBean, but got null

Please help me how to deal with this problem, thanks.

请帮我如何处理这个问题,谢谢。

回答by Pankaj Arora

//DataModel Class
 package com.DEECOUP.DataModel;


import android.os.Parcel;
import android.os.Parcelable;

public class OrderedData implements Parcelable {

private String _title, _subtitle, _person_type, _processed_name;
private Integer _price, _quantity;

public OrderedData(String title,  String subtitle , String person_type, String processed_name,
        Integer price, Integer quantity)
{
    _title = title;
    _subtitle =subtitle ; 
    _person_type = person_type;
    _processed_name = processed_name;
    _price = price;
    _quantity = quantity;
}


public OrderedData(Parcel in) {
    // TODO Auto-generated constructor stub

    String[] data = new String[6];

     in.readStringArray(data);
        _title = data[0];
        _subtitle =  data[1];
        _person_type=  data[2];
        _processed_name =  data[3];
        _price =  Integer.parseInt(data[4]);
        _quantity = Integer.parseInt(data[5]);
}


public String getTitle()
{
    return _title; 
}

public String getSubTitle()
{
    return _subtitle; 
}

public String getPersonType()
{
    return _person_type; 
}

public String getProcessedName()
{
    return _processed_name; 
}

public Integer getPrice()
{
    return _price; 
}

public Integer getQuantity()
{
    return _quantity; 
}


@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}


@Override
public void writeToParcel(Parcel dest, int flags) {
     dest.writeStringArray(new String[] {
                this._title,
                this._subtitle,
                this._person_type,
                this._processed_name,
                String.valueOf(this._price),
                String.valueOf(this._quantity)
            });
}


public static final Parcelable.Creator<OrderedData> CREATOR = new Parcelable.Creator<OrderedData>() {
    public OrderedData createFromParcel(Parcel in) {

         return new OrderedData(in); 
    }

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

//button click to send data on second activity
case R.id.btnOrderDetails:
        Intent intent = new Intent(SenderActiviry.this,
                RecieverActivity.class);
        intent.putParcelableArrayListExtra("data", orderedDataList);
        startActivity(intent);
        break;

   //  Add data to datamodel from first addtivity
global list
ArrayList<OrderedData> orderedDataList = new ArrayList<OrderedData>();

   and in on create
  orderedDataList.add(new OrderedData(_title, _subTitle,_person_Type,   _processName,_pRice,getFinalQuantity));

回答by SweetWisher ツ

Pass the data:

传递数据

Intent intent = new Intent(SendActivity.this, PickContactsActivity.class); 
Bundle bundle;
bundle.putParcelableArrayList("data", cons); // Be sure con is not null here
intent.putExtras(bundle);

Get the data:

获取数据

 ArrayList<PickBean> arrayParents = intent.getParcelableArrayListExtra("data");

Replace you method newArraywith :

将您的方法替换newArray为:

 public final Parcelable.Creator<PickBean> CREATOR = new Parcelable.Creator<PickBean>() { 
        @Override 
        public PickBean createFromParcel(Parcel source) { 

            return new PickBean(source); 
        } 

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

 public PickBean(Parcel data) {

        this.displayName = data.readString();
        this.displayNumber = data.readString();
 }