Saving data upon closing app and retrieving that data

后端 未结 5 1873
没有蜡笔的小新
没有蜡笔的小新 2021-01-04 01:07

I know, there are plenty of questions in regards to saving/retrieving data on here. I was doing find looking things up on my own and really thought I could manage to find m

5条回答
  •  说谎
    说谎 (楼主)
    2021-01-04 01:31

    Serialize an object and pass it around which is more dependable than shared preferences (had lots of trouble with consistency with shared preferences):

    public class SharedVariables {
    
        public static  void writeObject(
                final Context context, String key, S serializableObject) {
    
            ObjectOutputStream objectOut = null;
            try {
                FileOutputStream fileOut = context.getApplicationContext().openFileOutput(key, Activity.MODE_PRIVATE);
                objectOut = new ObjectOutputStream(fileOut);
                objectOut.writeObject(serializableObject);
                fileOut.getFD().sync();
            } catch (IOException e) {
                Log.e("SharedVariable", e.getMessage(), e);
            } finally {
                if (objectOut != null) {
                    try {
                        objectOut.close();
                    } catch (IOException e) {
                        Log.e("SharedVariable", e.getMessage(), e);
                    }
                }
            }
        }
    

    Then use a class to use:

    public class Timestamps implements Serializable {
    
    private float timestampServer;
    
    public float getTimestampServer() {
        return timestampServer;
    }
    
    public void setTimestampServer(float timestampServer) {
        this.timestampServer = timestampServer;
    }
    
    }
    

    Then wherever you want to write to the variable use:

    SharedVariables.writeObject(getApplicationContext(), "Timestamps", timestampsData);
    

提交回复
热议问题