java如何将对象放到缓存里_java – 如何在Android中缓存/保存自定义类对象?

例.

public class MyClass implements Serializable

{

private static final long serialVersionUID = 1L;

public String title;

public String startTime;

public String endTime;

public String day;

public boolean classEnabled;

public MyClass(String title, String startTime, boolean enable) {

this.title = title;

this.startTime = startTime;

this.classEnabled = enable;

}

public boolean saveObject(MyClass obj) {

final File suspend_f=new File(SerializationTest.cacheDir, "test");

FileOutputStream fos = null;

ObjectOutputStream oos = null;

boolean keep = true;

try {

fos = new FileOutputStream(suspend_f);

oos = new ObjectOutputStream(fos);

oos.writeObject(obj);

} catch (Exception e) {

keep = false;

} finally {

try {

if (oos != null) oos.close();

if (fos != null) fos.close();

if (keep == false) suspend_f.delete();

} catch (Exception e) { /* do nothing */ }

}

return keep;

}

public MyClass getObject(Context c) {

final File suspend_f=new File(SerializationTest.cacheDir, "test");

MyClass simpleClass= null;

FileInputStream fis = null;

ObjectInputStream is = null;

try {

fis = new FileInputStream(suspend_f);

is = new ObjectInputStream(fis);

simpleClass = (MyClass) is.readObject();

} catch(Exception e) {

String val= e.getMessage();

} finally {

try {

if (fis != null) fis.close();

if (is != null) is.close();

} catch (Exception e) { }

}

return simpleClass;

}

并从活动中呼叫

if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))

cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"MyCustomObject");

else

cacheDir= getCacheDir();

if(!cacheDir.exists())

cacheDir.mkdirs();

MyClass m = new MyClass("umer", "asif", true);

boolean result = m.saveObject(m);

if(result)

Toast.makeText(this, "Saved object", Toast.LENGTH_LONG).show();

else

Toast.makeText(this, "Error saving object", Toast.LENGTH_LONG).show();

MyClass m = new MyClass();

MyClass c = m.getObject(this);

if(c!= null)

Toast.makeText(this, "Retrieved object", Toast.LENGTH_LONG).show();

else

Toast.makeText(this, "Error retrieving object", Toast.LENGTH_LONG).show();

不要忘记在清单文件中使用write_external_storage权限.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值