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

前端 未结 3 1564
心在旅途
心在旅途 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: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 :)

提交回复
热议问题