Saving data upon closing app and retrieving that data
Asked Answered
M

5

19

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 my answers without having to "ask a question", but I began to wonder something that I haven't seen an answer for on here.

MY SITUATION:

Naturally, I'm making an app. Upon closing the app, I want to save a simple array of numbers (0 or 1) or boolean values as it were. Upon starting the app, I want to search for that array, if it exists, and retrieve it for use within the app.

I began placing my code into the activity in which the array would be used. But, I started wondering if I would have to copy/paste the overridden onStop() function into all of my activities? Or do I do it in the main activity and somehow link the other activities.

Basically, no matter what state/activity the app is currently on when the app is closed, I want to be able to save the array of int/bool and open it back up when the app is started.

Maybe I didn't know how to search for what I wanted, so explaining it felt like the right thing to do.

I don't mind doing more searching, but if someone would point me in the right direction at the very least, I'd be extremely grateful.

EDIT: If there's a better way to do what I want than what I described (i.e. using a different state instead of onStop(), for instance), please feel free to throw out ideas. This is my first time actually having to deal with the activities' lifecycles and I'm a bit confused even after looking through the android development tutorials. I really think they're poorly done in most cases.

Milky answered 26/3, 2015 at 17:9 Comment(1)
From wiki : SharedPreferences is an API from Android SDK to store and retrieve application preferences. SharedPreferences are simply sets of data values that stored persistently. Persistently which mean data you stored in the SharedPreferences are still exist even if you stop the application or turn off the device.Juncaceous
C
17

When you application needs to save some persistent data you should always do it in onPause() method and rather than onStop(). Because if android OS kills your process then onStop() and onDestroy() methods are never called. Similarly retrieve data in onResume() method.

Carolus answered 26/3, 2015 at 17:16 Comment(2)
Thanks for the tip by the way. I'll be sure to do that.Milky
onPause is called when you throw up an interstitial as well, which may not be the ideal time to save for some games (i.e. interstitial after dying...)Ideography
M
3

Looking at the purpose you want to fulfill, SharedPreferences is all you want.

The documentation states:

"SharePreferences provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed)."

Mazzard answered 26/3, 2015 at 17:31 Comment(0)
C
2

Use SharedPreference to store small amount of data or use SQLite to store large amount of data. See this link

http://developer.android.com/guide/topics/data/data-storage.html

Chintzy answered 26/3, 2015 at 17:15 Comment(0)
P
0

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 <S extends Serializable> 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);
Prognostication answered 12/12, 2015 at 14:20 Comment(0)
M
-2

Best way to achieve that is:

  • create a class. Call it MySettings, or whatever suits you
  • in this class, define the array of ints / booleans you are going to share, as static. Create getter & setter method (property) to access that (also as static methods)
  • add a static load() method to MySettings that reads from SharedPreferences. When you launch the app (in your first activity or better in a subclass of Application) call MySettings.load(). This load method sets the array
  • add a static save() method. Public also. Now you can save from anywhere in you app. This save() method reads the array and writes in SharedPreferences

Code sample:

public class MySettings {
    private static List<Integer>  data;

    public static void load() {
        data = new ArrayList<Integer>();
        // use SharedPreferences to retrieve all your data

    }

    public static void save() {
        // save all contents from data
    }

    public static List<Integer> getData() {
        return data;
    }

    public static void setData(List<Integer> data) {
        MySettings.data = data;
    }
}
Mcgray answered 26/3, 2015 at 17:15 Comment(7)
definitely the best answer ... for now i will made all my methods static, and put whole code to the subclass of Aplication classRural
Sooo, is this good or no? lol. I'm all for sarcasm and what not, but at this point I'm just confused.Milky
I think it's a solution that works. Without adding the complexity of a Dependency Injection Framework like Dagger. I think you're starting out in Android Development and at every stage of learning you're going to find better solutions. But this one will work for you nowMcgray
Alright thanks for the honesty. I definitely don't need anything complex. I'd really like to hear @Rural 's reasoning for his comments, I'm a bit confused and the more opinions the better.Milky
Application subclassing(from docs): There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. ... in your first activity will ends with NPE if the first activity wasn't called, and yes, it may happend ... not "factory"(SomeClass.getInstance()) nor "helper"(String.format()) static methods, please, in OOP's world? ...Rural
Thanks. So this leaves an unanswered question still, I think. Where do I place the code to save if I want it to save no matter what activity it's in?Milky
Maybe I've explained myself in a way that Selvin understood that all code goes inside the Application Subclass. In his comment he quotes that it's not necessary to use Application subclass as a container for global vars (which I think is correct), but App subclass is a good place to initialize things and also to get low memory messages from Android. I've updated my answer with some sample codeMcgray

© 2022 - 2024 — McMap. All rights reserved.