当前位置:首页 > Android > 正文内容

Android经过Intent传输包含自定义类的ArrayList

jsc9年前 (2016-04-06)Android2775

Android通过Intent传输包含自定义类的ArrayList

前言

之前项目中通过Intent只是传输简单的字符串,这次因为需要在前一个页面联网获取对象数据,然后在下一个页面使用,所以考虑到使用Intent传输包含自定义类的ArrayList

Serializable

Java的对象序列化指的是将那些实现了Serializable接口的对象转换成一个字节序列,并且能在需要的时候再将这个字节序列完全恢复为之前的对象。

想实现对象的序列化,需要实现java.io.Serializable接口(注意,这个接口只是一个标记接口,并没有具体需要 override的方法)。当然,你也可以自己实现对象的序列化,但是我认为既然Java提供了这么一套对象序列化的机制,我们最好还是使用官方提供的方 法。

Example

创建一个简单对象,并且实现Serializable接口
package javastudy;

import java.io.Serializable;

public class Person implements Serializable {
	private static final long serialVersionUID = -6470574927973900913L;
	private String firstName;
	private String secondName;
	// example for transinet
	private transient String noSerializableString;

	public Person(String firstName, String secondName, String noSerializableString) {
		super();
		this.firstName = firstName;
		this.secondName = secondName;
		this.noSerializableString = noSerializableString;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getSecondName() {
		return secondName;
	}

	public void setSecondName(String secondName) {
		this.secondName = secondName;
	}

	public String getNoSerializableString() {
		if (noSerializableString != null) {
			return noSerializableString;
		} else {
			return "";
		}
	}

	public void setNoSerializableString(String noSerializableString) {
		this.noSerializableString = noSerializableString;
	}

	public String toString() {
		return "Person [ first name :" + getFirstName() + ", second name :" + getSecondName() + ", no serializable :"
				+ getNoSerializableString() + "]";
	}
}

再写一个类,用于实现对象的序列化和反序列化

package javastudy;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class TestSerializable {
	public static void main(String[] args) {
		Person person = new Person("Wang", "Zhengyi", "Genius");
		String fileName = "/tmp/person.out";

		// save object to file
		FileOutputStream fos = null;
		ObjectOutputStream out = null;

		try {
			fos = new FileOutputStream(fileName);
			out = new ObjectOutputStream(fos);
			out.writeObject(person);

			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		// read object from file
		FileInputStream fin = null;
		ObjectInputStream in = null;

		try {
			fin = new FileInputStream(fileName);
			in = new ObjectInputStream(fin);

			Person p = (Person) in.readObject();

			System.out.println(p);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fin != null) {
				try {
					fin.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

Intent传输包含自定义类的ArrayList

之所以之前介绍了Serializable,是因为这是实现Intent传输的前提,ArrayList包含的自定义类必须实现Serializable接口才能通过putSerializable()方法被传递。

还是用上面的Person类作为自定义的类,则第一个传递ArrayList的Activity关键代码如下:
// Intent Creation and Initialization
Intent passIntent = new Intent();
passIntent.setClass(MainActivity.this, SecondaryActivity.class);
                 
// Create custom class Object
Person p1 = new Person("Wang", "Zhengyi", "first");
Person p2 = new Person("Chen", "Shan", "second");
                 
// Create Array List of custom Class and add the Created object
ArrayList<Person> aListClass = new ArrayList<Person>();
aListClass.add(p1);
aListClass.add(p2);
                 
// Create a Bundle and Put Bundle in to it
Bundle bundleObject = new Bundle();
bundleObject.putSerializable("key", aListClass);
                 
// Put Bundle in to Intent and call start Activity
passIntent.putExtras(bundleObject);
startActivity(passIntent);

第二个接收ArrayList的Activity关键代码如下:

try{
    // Get the Bundle Object        
    Bundle bundleObject = getIntent().getExtras();
             
        // Get ArrayList Bundle
    ArrayList<Person> classObject = (ArrayList<Person>) bundleObject.getSerializable("key");
             
        Retrieve Objects from Bundle
    for(int index = 0; index < classObject.size(); index++){
                 
        Person person = classObject.get(index);
        Toast.makeText(getApplicationContext(), person, Toast.LENGTH_SHORT).show();
    }
} catch(Exception e){
    e.printStackTrace();
}


扫描二维码推送至手机访问。

版权声明:本文由微小站发布,如需转载请注明出处。

本文链接:https://jsc0.com/post/73.html

标签: ArrayList
分享给朋友:

“Android经过Intent传输包含自定义类的ArrayList” 的相关文章

Android自定义属性,format详解

1. reference:参考某一资源ID。    (1)属性定义:<declare-styleable name = "名称">       &...

android异步任务详解 AsynTask

android异步任务详解 AsynTask

android提供了一套专门用于异步处理的类。即:AynsTask类。使用这个类可以为耗时程序开辟一个新线程进行处理,处理完时返回。其实,AsynTask类就是对Thread类的一个封装,并且加入了一些新的方法。编程时,两者都可以实现同样的功能。本文后面将对AsynTask和Thread...

Android权限问题整理

Android权限系统非常庞大,我们在Android系统中做任何操作都需要首先获取Android系统权限,本文记录了所有的Android权限问题,整理一下分享给大家。访问登记属性 android.permission.ACCESS_CHECKIN_PROPERTIES读取或写入登记check-in数...

Android开发之资源文件存储

在android开发中,资源文件是我们使用频率最高的,无论是string,drawable,还是layout,这些资源都是我们经常使用到的,而且为我们的开始提供很多方便,不过我们平时接触的资源目录一般都是下面这三个。        /res...

获取Android手机中SD卡存储信息

SD卡作为手机的扩展存储设备,在手机中充当硬盘角色,可以让我们手机存放更多的数据以及多媒体等大体积文件。因此查看SD卡的内存就跟我们查看硬盘的剩余空间一样,是我们经常操作的一件事,那么在Android开发中,我们如何能获取SD卡的内存容量呢?首先,要获取SD卡上面的信息,必须先对SD卡有访问的权限,...

Location服务之LocationManager

Location服务之LocationManager

LocationManager系统服务是位置服务的核心组件,它提供了一系列方法来处理与位置相关的问题,包括查询上一个已知位置、注册和注销来 自某个LocationProvider的周期性的位置更新、注册和注销接近某个坐标时对一个已定义的Intent的触发等。今天我们就一起探讨一下 L...