Activity 传递ArrayList<bean>数据及其他基本运用

  1. 云栖社区>
  2. 博客>
  3. 正文

Activity 传递ArrayList<bean>数据及其他基本运用

kandy_aliyq 2018-07-22 10:18:00 浏览485
展开阅读全文

一、引用

1、Android Activity间传值选择,Serializable Or Parcelable
2、Android开发艺术探索 第2章 IPC机制 读书笔记
3、Andriod Parcelable 读写 boolean(布尔值)的步骤

二、实例

1、活动一:FirstActivity传递数据,用Intent或者用Bundle,按照key-value键值对来存放待传递数据


FirstActivity.class

1.1、传递基本类型数据
1.2、传递自定义bean,实现Serializable接口
1.3、传递自定义ArrayList<bean>,实现Parcelable接口
1.4、数据传递:startActivity(intent);单纯传递数据startActivityForResult(intent,requestCode);传递数据+数据返回的code设置
1.5、onActivityResult复写用来接受回传的数据,判断resultCode和requestCode来获取数据

    /**
     * 传递数据
     * 1、基本类型和基本类型list
     * 2、各种bean类
     * 3、各种list<bean>
     * */
    public void sendData(View v){
        //cars
        ArrayList<String> cars = new ArrayList<>();
        cars.add("法拉利");
        cars.add("奔驰");
        cars.add("宾利");

        //girl friend
        GirlFriend girlFriend = new GirlFriend("小丽",21,"C",165,45);

        //cards
        Card card_0 = new Card("工商银行",200,true);
        Card card_1 = new Card("建设银行",456,false);
        ArrayList<Card> cards = new ArrayList<>();
        cards.add(card_0);
        cards.add(card_1);


        Intent it = new Intent(this,SecondActivity.class);

        //基本类型和基本类型array举例--用Bundle一样的
        it.putExtra("name","帅哥");
        it.putExtra("age",23);
        it.putStringArrayListExtra("cars",cars);   //String类型数组
        it.putExtra("girlfriend",girlFriend);
        it.putExtra("cards",cards);


        this.startActivityForResult(it,1001);
    }

    /**
     * 数据回传:
     *
     * resultCode:是否有回传的标识
     * Activity.RESULT_OK = -1
     * Activity.RESULT_CANCELED = 0
     *
     * requestCode:具体回传的code标识
     * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK)
            return;

        switch (requestCode){
            case 1001:
                String result = data.getExtras().getString("result");
                LogUtil.i("从活动二回传过来的数据:"+result);
                tvResult.setText(result);
                break;
        }
    }

GirlFriend.class

1、实现Serializable接口,并加long serialVersionUID = 1L;
2、静态成员或者方法、transient关键字的并不参加序列化
3、已经默认实现了Parcelable的writeObject和readObject的方法,用Serializable接口是因为这个写法比较简单...

public class GirlFriend implements Serializable{
    private static final long serialVersionUID = 1L;

    private String name;
    private int age;
    private String cup;
    private int height;
    private int weight;

    public GirlFriend(String name,int age,String cup,int height,int weight){
        this.name = name;
        this.age = age;
        this.cup = cup;
        this.height = height;
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCup() {
        return cup;
    }

    public void setCup(String cup) {
        this.cup = cup;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "女友信息 {" +
                "姓名='" + name + '\'' +
                ", 年龄=" + age +
                ", 罩杯='" + cup + '\'' +
                ", 身高=" + height +
                ", 体重=" + weight +
                '}';
    }
}

Card.class

1、实现Parcelable接口,写法略微复杂但是可以实现传递ArrayList,但是速度更快
2、实现writeObject和readObject接口
3、注意boolean值的read和write
read : exist = in.readByte()!=0; //boolean的读
write : parcel.writeByte((byte)(exist ?1:0)); //boolean的写

public class Card implements Parcelable{
    private String bank;
    private int money;
    private boolean exist;

    public Card(String bank,int money,boolean exist){
        this.bank = bank;
        this.money = money;
        this.exist = exist;
    }

    public String getBank() {
        return bank;
    }

    public void setBank(String bank) {
        this.bank = bank;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public boolean isExist() {
        return exist;
    }

    public void setExist(boolean exist) {
        this.exist = exist;
    }


    //============================================================

    public static final Creator<Card> CREATOR = new Creator<Card>() {
        @Override
        public Card createFromParcel(Parcel in) {
            return new Card(in);
        }
        @Override
        public Card[] newArray(int size) {
            return new Card[size];
        }
    };


    /**
     * 对应Creator中的构造器
     * */
    protected Card(Parcel in) {
        bank = in.readString();
        money = in.readInt();
        exist = in.readByte()!=0;   //boolean的读
    }



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

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(bank);
        parcel.writeInt(money);
        parcel.writeByte((byte)(exist ?1:0)); //boolean的写
    }
}

2、活动二:SecondActivity接受FirstActivity数据,getIntent获取意图,用key-value键值对形式获取数据


SecondActivity.class

1、获取数据:getIntent().getExtras().getXXX();
2、返回数据:setResult(resultCode , Data); resultCode=Activity.RESULT_OK 当然也可以随便设置,不一定非用这个参数,只要和接受地方一致就行了

private void getInfo(){
        Intent it = getIntent();
        if(it != null){
            Bundle bd = it.getExtras();
            String name = bd.getString("name");
            int age = bd.getInt("age");
            ArrayList<String> cars = bd.getStringArrayList("cars");
            GirlFriend friend = (GirlFriend) bd.getSerializable("girlfriend");
            ArrayList<Card> cards = bd.getParcelableArrayList("cards");

            StringBuilder sb = new StringBuilder();
            sb.append("姓名="+name+",年龄="+age+"\n车子:");
            for (String car : cars){
                sb.append(car+"、");
            }
            sb.append(friend.toString()+"\n");
            sb.append("\n银行卡:\n");
            for(Card card : cards){
                sb.append("开户行="+card.getBank()+",存款="+card.getMoney()+",是否拥有="+card.isExist()+"\n");
            }

            LogUtil.i("从活动一传过来的数据:"+sb.toString());
            tvResult.setText(sb.toString());
        }
    }

    /**
     * 返回数据到前一个activity
     * */
    public void returnData(View v){
        Intent it = new Intent();
        it.putExtra("result","活动二结果...");
        setResult(Activity.RESULT_OK,it);
        finish();
    }

3、结果图

img_e70a2830a444919663027a286d180d1d.png
1.png
img_555895249dd79ab151fb024cf9f9092a.png
2.png
img_494bf1aae94be0cb46100ca7eb68aa58.png
back1.png

网友评论

登录后评论
0/500
评论
kandy_aliyq
+ 关注