栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Android中缓存/保存自定义类对象?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在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) {  }        }        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权限。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/508250.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号