android通过剪切板传递实体类数据

package com.example.androidtest;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.app.Activity;
import android.text.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView)findViewById(R.id.mytv);
    }

	public void onclick(View view){
    	MyData data = new MyData("xi","23");
    	String base64code = "";
    	try {
    		//编码加密
    		ByteArrayOutputStream bytearray = new ByteArrayOutputStream();
			ObjectOutputStream objectout = new ObjectOutputStream(bytearray);
			objectout.writeObject(data);
			 base64code = Base64.encodeToString(bytearray.toByteArray(),  Base64.DEFAULT);
			objectout.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	ClipboardManager clip = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
    	clip.setText(base64code);
    	getclip();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    public void getclip(){
    	ClipboardManager clip = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
    	String msg = clip.getText().toString();
    	MyData mydata = null;
    	//解码
    	byte[] bytearray = Base64.decode(msg, Base64.DEFAULT);
    	ByteArrayInputStream byteinput = new ByteArrayInputStream(bytearray);
    	try {
			ObjectInputStream out = new ObjectInputStream(byteinput);
			 mydata = (MyData)out.readObject();
		} catch (Exception e) {
			// TODO: handle exception
		}
    	tv.setText(mydata.toString());
    }
    
}
MyData类
package com.example.androidtest;


import java.io.Serializable;


public class MyData implements Serializable {


	private String name;
	private String age;
	public MyData(String n,String age){
		this.name = n;
		this.age = age;
	}
	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;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "name:"+name + " age:"+age;
		
	}
	
	
}
易错点:
剪切板导入的类是android.text.ClipboardManager;不是android.content.ClipboardManager;

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。