android 对象保存到SP

本文介绍了如何使用Java的序列化将Android对象转换为字符串并保存到SharedPreferences中,以实现对象的持久化存储。通过创建一个工具类ContextUtils,提供saveObj2SP方法,将对象序列化后以Base64编码的形式保存。同时,被保存的对象需要实现Serializable接口。在示例中,创建了一个名为Entity的类并保存到SharedPreferences中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.工具类

package com.you.me.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;

import android.widget.TextView;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
* @author cao_zhi_qing
* @version Revision: 1.0 Date: 2015/1/2
*/
public class ContextUtils {
/**
* 把对象保存到以String形式保存到sp中
* @param context 上下文
* @param t 泛型参数
* @param spName sp文件名
* @param keyName 字段名
* @param
*/
public static void saveObj2SP(Context context, T t, String spName, String keyName) {

    SharedPreferences preferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
    ByteArrayOutputStream bos;
    ObjectOutputStream oos = null;
    try {
        bos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(bos);
        oos.writeObject(t);
        byte[] bytes = bos.toByteArray();

// String ObjStr = new String(bytes,0,bytes.length);
String ObjStr = Base64.encodeToString(bytes, Base64.DEFAULT);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(keyName, ObjStr);
editor.commit();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
if (oos != null) {
try {
oos.flush();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}

        }

    }

}

/**
 * sp文件名 和 字段名相同
 * @param context
 * @param t
 * @param spName
 * @param <T>
 */
public static <T> void saveObj2SP(Context context, T t, String spName) {
    saveObj2SP(context, t, spName, spName);
}


/**
 *从sp中读取对象
 * @param context
 * @param spName sp文件名
 * @param keyNme 字段名
 * @param <T>    泛型参数
 * @return
 */
public static <T extends Object> T getObjFromSp(Context context, String spName, String keyNme) {
    SharedPreferences preferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
    byte[] bytes = Base64.decode(preferences.getString(keyNme, ""), Base64.DEFAULT);
    ByteArrayInputStream bis;
    ObjectInputStream ois = null;
    T obj = null;
    try {
        bis = new ByteArrayInputStream(bytes);
        ois = new ObjectInputStream(bis);
        obj = (T) ois.readObject();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (ois != null) {
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return obj;
}

public static <T extends Object> T getObjFromSp(Context context, String spName){
    return  getObjFromSp(context,spName,spName);
}

}

2.被保存的对象要先序列化 Serializable。
package com.example.customView;

import java.io.Serializable;

/**
* @author cao_zhi_qing
* @version Revision: 1.0 Date: 2015/6/29
* @Description:请用一句话描述此类
*/
public class Entity implements Serializable {

private String name;
private String address;


public String getName() {
    return name;
}

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

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

}

3保存对象、获取对象。
package com.example.customView;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
private TitleView titleView ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Entity entity = new Entity();
entity.setName(“name”);
entity.setAddress(“address”);
ContextUtils.saveObj2SP(this,entity,”entity”);

    Entity entity1 = ContextUtils.getObjFromSp(this,"entity");
    System.out.println(entity1.getName());
    System.out.println(entity1.getAddress());
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值