Search code examples
androidpreferences

Using getSharedPreferences to get time


I'm a complete beginner to Java and Android development and had a question about preferences.

A tutorial asked me to use preferences to read and save the time in which the onCreate method is called.

I've sat on this problem for at least two days but have come up with nothing. Can anyone give me an example on how to code such an action?

public static final String PREFS_NAME = "Time_Pref";
public class QuizSplashActivity extends QuizActivity {

@Override   

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);
    SharedPreferences = getSharedPreferences ("Time_Pref", "MODE_PRIVATE); 
}

But that's where I seem to get lost. I'm not even sure if I'm heading in the right direction.


Solution

  • I'd recommend you to read the dev guide's chapter about SharedPreferences. You can find it here.

    I suggest you to use System.currentTimeMillis() to get the time value to save.

    Basic code to save something to preferences should look like this:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // view setup stuff here...
    
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putLong("onCreateCallTime", System.currentTimeMillis());
        editor.commit();
    }
    

    Then use android.text.format.Time class to format that time after reading it from preferences:

    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    long timeMillis = settings.getLong("onCreateCallTime", 0);
    Time t = new Time();
    t.set(timeMillis);
    

    Read the Time class documentation to learn how to format/convert time with its methods :)