How to store a class object into Internal Memory Storage using serializable?

前端 未结 3 1531
心在旅途
心在旅途 2021-02-06 17:04

I need to store this object into the internal storage memory of the phone, and i have the

相关标签:
3条回答
  • 2021-02-06 17:24

    You're not allowed to just write into the internal storage (even if you get that permission). Try it with the external sd or your cache folder instead.

    0 讨论(0)
  • 2021-02-06 17:34

    change this

    out = new ObjectOutputStream(new FileOutputStream("appSaveState.data"));
    

    with

       File outFile = new File(Environment.getExternalStorageDirectory(), "appSaveState.data");
       out = new ObjectOutputStream(new FileOutputStream(outFile)); 
    

    as correctly pointed out by @e-x, the file will not be removed clearing application's data or uninstalling the app

    0 讨论(0)
  • 2021-02-06 17:48

    This was my aproach based on this post and this

    I wrote this on my User class

    private static File mFolder;
    public void saveData(Activity pContext) {
        //this could be initialized once onstart up
        if(mFolder == null){
            mFolder = pContext.getExternalFilesDir(null);
        }
        this.save();
        ObjectOutput out;
        try {
            File outFile = new File(mFolder,
                    "someRandom.data");
            out = new ObjectOutputStream(new FileOutputStream(outFile));
            out.writeObject(this);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static User loadData(Context pContext) {
        if(mFolder == null){
            mFolder = pContext.getExternalFilesDir(null);
        }
        ObjectInput in;
        User lUser = null;
        try {
            FileInputStream fileIn = new FileInputStream(mFolder.getPath() + File.separator + "someRandom.data");
            in = new ObjectInputStream(fileIn);
            lUser = (User) in.readObject();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (lUser != null) {
            lUser.save();
            Log.d("current User: ", lUser.nickname);
        } else {
            Log.d("current User: ", "null");
        }
        return lUser;
    }
    

    Edit:

    Then from my activity i call

    mUser = User.loadData(mSelf);
    

    or

    mUser = User.loadData(this);
    

    mSelf would be an instance I store

    Hope this helps :)

    0 讨论(0)
提交回复
热议问题