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

2022-09-04 00:51:06

我想将-object保存到Android存储中的某个位置,以便快速检索并在其中显示数据。ArrayList<CustomClass>

这可能吗?如果是,那么哪种技术是合适的,SQLite还是外部存储?


答案 1

例。

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权限。


答案 2

这个问题并不是真正的Android特有的。我的意思是,如果您知道如何通过java.io.Serializable序列化数据,或者您有自定义的持久性格式,那么您只需要知道在哪里存储它。

您可以通过以下方式在本地设备上抓取文件:

FileOutputStream stream = null;
try{
   stream = mContext.openFileOutput("name.data", Context.MODE_PRIVATE);
   ObjectOutputStream dout = new ObjectOutputStream(stream);
   dout.writeObject(myArrayList);
   dout.flush();
   stream.getFD().sync();
} catch(IOException e) { //Do something intelligent
} finally {
   stream.close();
}

稍后必须使用 openFileInput() 来读回数据。

或者,您可以获取外部存储。这是相似的,但是您必须保证它甚至存在。就像连接外部存储甚至能够写入一样。由于您正在这里编写数据结构,并且通常外部存储是世界可读的,因此我认为这对于您的预期目的来说不是一个好主意(仅从您到目前为止所放置的内容来看)。

如果您的数据是结构化的,并且将被查询多次,并且始终加载起来可能相当大,那么请考虑使用作为操作系统一部分的sql lite工具。然而,我假设你也不需要这个,因为一个简单的列表就是这样,一个线性结构,你可能可以在一个文件中寻找(假设它少于1MB的数据:)


推荐