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

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

jsc9年前 (2016-04-06)Android2826

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中使用PULL方式解析XML文件

Android中使用PULL方式解析XML文件

 Pull解析器的运行方式与 SAX 解析器相似。它提供了类似的事件,如:开始元素和结束元素事件,使用parser.next()可以进入下一个元素 并触发相应事件。跟SAX不同的是, Pull解析器产生的事件是一个数字,而非方法,因此可以使用一个s...

google Zxing实现二维码、条形码扫描,仿微信二维码扫描效果

google Zxing实现二维码、条形码扫描,仿微信二维码扫描效果

    了解二维码这个东西还是从微信中,当时微信推出二维码扫描功能,自己感觉挺新颖的,从一张图片中扫一下竟然能直接加好友,不可思议啊,那时候还不了解二维码,呵呵,然后做项目的时候,老板说要加上二维码扫描功能,然后自己的屁颠屁颠的去百度,google...

Android应用加入微信分享

Android应用加入微信分享

一、申请你的AppIDhttp://open.weixin.qq.com/  友情提示:推荐使用eclipse打包软件最后一步的MD5值去申请AppID二、官网下载libammsdk.jar包http://open.weixin.qq.com/download/?lang=zh_...

Android 学习之 开源项目PullToRefresh的使用

Android 学习之 开源项目PullToRefresh的使用

首先 下载 Android-PullToRefresh-master 下载地址  https://github.com/chrisbanes/Android-PullToRefresh 下载之...

GridView中item高度自适应

item高度自适应public class MyAdapter extends BaseAdapter {         GridView mGv;&n...

采用SharedPreferences保存用户偏好设置参数和读取设置参数

采用SharedPreferences保存用户偏好设置参数和读取设置参数

Android SDK支持那些文件存储技术? 1. 使用SharedPreferences保存key-value类型的数据 2. 流文件存储(使用openFileOutput和openFileInput方法,或FileInputStream和FileO...