[Android学习]Activity之间传递对象和对象集合

时间:2022-02-06 08:20:26

开发过程中,Activity之间传递数据是必不可少的,android中使用Intent和Bundle作为数据载体,在Activity之间传递,对于基础数据类型,Bundle已经提供相关的put,get方法,而作为自定义的类型则需要有特别的要求.

自定义类型,想要使用Bundle传递时,需要满足特定条件。即该类型需要实现Serializable接口或者Parcelable接口

(注意:如果目标对象中包含其他对象,则被包含的对象也需要实现Serializable接口或者Parcelable接口)

(关于Serializable接口和Parcelable接口就不在此做记录了)


步骤:

1.定义类,实现相关接口

2.使用Intent和Bundle对应的方法set数据

3.startActivity传递Intent对象


使用Serializable

一.传递对象

a).定义类,实现Serializable接口

public class Student implements Serializable
{
// members
private String name; private String age; private int id; // getter setter
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getAge()
{
return age;
}
public void setAge(String age)
{
this.age = age;
} /**
* Serializable
*/
private static final long serialVersionUID = 1L;
}

Student

b).使用Intent传递对象

// 使用Serializable
Button btnSerializable = (Button)findViewById(R.id.btnSerializable);
btnSerializable.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub // create data
Student student = new Student();
student.setName("stephen lee");
student.setAge("12");
student.setId(1); // bundle
Bundle bundle = new Bundle();
bundle.putSerializable(MainActivity.StudentKey,student); // intent
Intent intent = new Intent(arg0.getContext(),SecondActivity.class);
intent.putExtras(bundle); // navigate
startActivity(intent);
}
});

使用Serializable

c).获取传递的数据

Bundle bundle = this.getIntent().getExtras();
Student student = (Student)bundle.getSerializable(MainActivity.StudentKey);
if(student!=null)
textView.setText("name:" + student.getName() + "age:" + student.getAge() + "id:" + student.getId());

SecondActivity

二.传递对象集合

a).同上

b).同上(注意使用putSerializable()方法时,需要把List<>强转成为Serializable,并且集合中的成员都需要实现Serializable接口)

        Button btnSerializableList = (Button)findViewById(R.id.btnSerializableList);
btnSerializableList.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub // create data
List<Student> students = new ArrayList<Student>(); Student student1 = new Student();
student1.setName("hellenism");
student1.setAge("12");
student1.setId(1); Student student2 = new Student();
student2.setName("stephen lee");
student2.setAge("12");
student2.setId(2); students.add(student1);
students.add(student2); // bundle , 注意:使用putSerializable()方法时,需要把List<>强转成为Serializable,并且集合中的成员都需要实现Serializable接口
Bundle bundle = new Bundle();
bundle.putSerializable(MainActivity.StudentsKey,(Serializable)students); // intent
Intent intent = new Intent(v.getContext(),SecondActivity.class);
intent.putExtras(bundle); // navigate
startActivity(intent);
}
});

使用Serializable

c).同上(不足之处在于,由于获取数据时候,需要把Serializable强转成为对应的List<>,此处会有警告)

Bundle bundle = this.getIntent().getExtras();
List<Student> students = (List<Student>)bundle.getSerializable(MainActivity.StudentsKey);
if(students!=null)
textView.setText("name:" + students.get(1).getName() + "age:" + students.get(1).getAge() + "id:" + students.get(1).getId());

SecondActivity

使用Parcelable


一.传递对象

a).定义类,实现Parcelable接口

public class Person implements Parcelable
{
// members
private String name;
private String age;
private int id; // getter setter
public int getId()
{
return id;
} public void setId(int id)
{
this.id = id;
} public String getName()
{
return name;
} public void setName(String name)
{
this.name = name;
} public String getAge()
{
return age;
} public void setAge(String age)
{
this.age = age;
} // Parcelable
@Override
public int describeContents()
{
// TODO Auto-generated method stub
return 0;
} @Override
public void writeToParcel(Parcel dest, int flags)
{
// TODO Auto-generated method stub
dest.writeString(name);
dest.writeString(age);
dest.writeInt(id);
} public static final Parcelable.Creator<Person> CREATOR = new Creator<Person>() {
public Person createFromParcel(Parcel source) {
Person person = new Person();
person.age = source.readString();
person.name = source.readString();
person.id = source.readInt();
return person;
} public Person[] newArray(int size) {
return new Person[size];
}
};
}

Parcelable接口

b).使用Intent传递参数

// 使用Parcelable
Button btnParcelable = (Button)findViewById(R.id.btnParcelable);
btnParcelable.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub // create data
Person person = new Person();
person.setName("i am person");
person.setAge("12");
person.setId(1); // bundle
Bundle bundle = new Bundle();
bundle.putParcelable(MainActivity.PersonKey,person); // intent
Intent intent = new Intent(arg0.getContext(),SecondActivity.class);
intent.putExtras(bundle); // navigate
startActivity(intent);
}
});

使用Intent

c).获取传递的参数

Bundle bundle = this.getIntent().getExtras();
Person person = (Person)bundle.getParcelable(MainActivity.PersonKey);
if(person!=null)
textView.setText("name:" + person.getName() + "age:" + person.getAge() + "id:" + person.getId());

获取传递的参数

二.传递数据类型

a).同上

b).同上

        Button btnParcelableList = (Button)findViewById(R.id.btnParcelableList);
btnParcelableList.setOnClickListener(new View.OnClickListener()
{ @Override
public void onClick(View v)
{
// TODO Auto-generated method stub // create data
List<Person> persons = new ArrayList<Person>(); Person person1 = new Person();
person1.setAge("12");
person1.setName("stephen lee");
person1.setId(1); Person person2 = new Person();
person2.setAge("12");
person2.setName("hellenism");
person2.setId(2); persons.add(person1);
persons.add(person2); // bundle
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(MainActivity.PersonsKey, (ArrayList<? extends Parcelable>) persons); // intent
Intent intent = new Intent(v.getContext(),SecondActivity.class);
intent.putExtras(bundle); // navigate
startActivity(intent);
}
});

使用Intent传递参数

c).同上

Bundle bundle = this.getIntent().getExtras();
List<Person> persons = bundle.getParcelableArrayList(MainActivity.PersonsKey);
if(persons!=null)
textView.setText("name:" + persons.get(1).getName() + "age:" + persons.get(1).getAge() + "id:" + persons.get(1).getId());

获取参数

注意:

使用以上方法传递对象时,都是创建了新的实例,而非传递对象的引用,如果是传递引用,也就无需序列化了。

完整例子:

http://pan.baidu.com/s/1dDf5p8d

[Android学习]Activity之间传递对象和对象集合的更多相关文章

  1. Android之Activity之间传递对象

    在非常多时候,我们须要在Activity之间传递对象,比方当你点击了某列表的item,须要传递给下一个Activity该对象,那我们须要该怎么做呢? Android支持两种传递对象的方式.一种是bun ...

  2. Android基础 -- Activity之间传递数据(bitmap和map对象)

    原文:http://blog.csdn.net/xueerfei008/article/details/23046341 做项目的时候需要用到在2个activity之间传递一些数据,之前做的都是些字符 ...

  3. 大叔也说Xamarin~Android篇~Activity之间传递数组

    回到目录 我们在开发应用程序时,不可能只使用一个Layout或者一个Activity,比如你个管理系统,要求用户先登陆然后再使用,这时你至少要有两个activity吧,先登陆一个,然后成功后需要跳到别 ...

  4. Android学习总结——Activity之间传递参数

    核心内容:一.在 Activity 之间传递简单数据二.在 Activity 之间传递复杂数据 三.在 Activity 之间传递自定义值对象   软件环境:Android Studio   一.在 ...

  5. Android中如何使用Intent在Activity之间传递对象&lbrack;使用Serializable或者Parcelable&rsqb;

    http://blog.csdn.net/cjjky/article/details/6441104 在Android中的不同Activity之间传递对象,我们可以考虑采用Bundle.putSeri ...

  6. Activity之间传递数据或数据包Bundle,传递对象,对象序列化,对象实现Parcelable接口

    package com.gaojinhua.android.activitymsg; import android.content.Intent; import android.os.Bundle; ...

  7. Activity 之间 传递 List 封装的对象或者对象

    项目中遇到 从也个页面向还有一个页面跳转传递一个List 封装的对象 .按网上查的资料 须要把 对象 实现 Serializable接口. 写了一下.可是跳转直接崩溃.一直看错误之日找不到原因后来自习 ...

  8. Android 笔记-Fragment 与 Activity之间传递数据

    Fragment 与 Activity之间传递数据有两种方法.一种是使用setArgument,一种是使用接口回调.以下先学习第一种方法. (1)使用setArgument方法: 为了便于理解,我在这 ...

  9. 【Android 复习】 &colon; Activity之间传递数据的几种方式

    在Android开发中,我们通常需要在不同的Activity之间传递数据,下面我们就来总结一下在Activity之间数据传递的几种方式. 1. 使用Intent来传递数据 Intent表示意图,很多时 ...

随机推荐

  1. eclipse智能提示

    原文地址:http://www.cnblogs.com/myitm/archive/2010/12/17/1909194.html Windows→Preferences→Java→Editor→Co ...

  2. php大力力 &lbrack;019节&rsqb;php分页类的学习

    2015-08-26 php大力力019.php分页类的学习 [2014]兄弟连高洛峰 PHP教程14.2.1 分页需求分析 14:18 [2014]兄弟连高洛峰 PHP教程14.2.2 分页类中分页 ...

  3. 三维云模拟Three&period;js

    http://www.mrdoob.com/#/131/clouds http://www.webgl.com/2012/03/webgl-demo-clouds/ <!DOCTYPE html ...

  4. C&num;时间格式 tostring、toshortdatestring、toshorttimestring

    在c#语言中的时间处理有几种方式: 首先获取当前时间:var date=new DateTime.Now; date.ToString()----2111-1-20 11:44:47 date.ToS ...

  5. HDU 5948 Thickest Burger 【模拟】 &lpar;2016ACM&sol;ICPC亚洲区沈阳站&rpar;

    Thickest Burger Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)T ...

  6. Echoprint系列--Android编译与调用

    在Echoprint系列--编译中编译了源代码,这次将Echoprint移植到Android平台并測试识别歌曲功能. 一.编译库 1.环境准备 Android NDK,我的是android-ndk-r ...

  7. 在Service中使用广播接受者

    1.清单文件 <service android:name="com.example.callmethod.MyService"></service> 2.开 ...

  8. 学习python的&ast;args和 &ast;&ast;kwargs

    *args表示任何多个无名参数,它是一个tuple(元组):**kwargs表示关键字参数,它是一个dict(字典) def foo(*args, **kwargs): print 'args = ' ...

  9. Linux系统格式化新磁盘并挂载分区

    Linux系统格式化新磁盘并挂载分区 在虚拟机的设置界面中,我们可以选择添加硬盘 添加好硬盘后,我们输入命令fdisk -l 看到有一个未经分区的硬盘 Fdisk命令编辑这个硬盘 输入n创建分区,p选 ...

  10. 《linux就该这么学》第五节课,shell脚本的各种语句!

    第四章shell语句 (据课本和虚拟机实验排版,借鉴请改动)               4.2:shell脚本   脚本包括:脚本声明,脚本注释,脚本内容和命令 例:#!/bin/bash      ...