Global variable data missing Android

0

Hello everyone, I'm creating an application that when I log in, the application brings the data Nome , Login , Senha and Foto(a url) of the server database, and save those data in a Singleton so that they are used in all other activitys . So far so good, everything works fine, but when I have buttoned the person to choose a photo from the gallery and upload it (all this is working), I realized that if I take a little time to choose the photo and wait in the gallery, the data that I recorded in Singleton 'get lost' (as if they were deleted or I do not know). I would like to know if you have a way to save this data without 'getting lost' when I leave my application in background . Note: I did not post any code because I believe it is not necessary, since it does not make any errors in it, but the data that 'disappear', I believe the android is somehow erasing them to release memory or something. But if you need to, just ask me to edit the question and put the code.

    
asked by anonymous 13.04.2016 / 22:56

1 answer

4

Suggestion to use instead of Singleton use the class SharedPreferences of android.

Usage example :

1. Name of your preferences

public static final String PREFS_NAME = "YourPreferences";

2. Restores preferences

The second parameter of the method [ getShardePreferenses ] ( link , int)) is the writing mode: constants for use MODE_PRIVATE , MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE

SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

3. Restores a new instance of SharedPreferences.Editor to create / modify values on object SharedPreferences

SharedPreferences.Editor editor = settings.edit();

4. Saves a new preference

editor.putString("Nome", "valorAqui");

5. Confirms writing data

editor.commit();

6. To recover the data simply repeat steps 1 and 2 and the second line:

settings.getString("Nome", "");

How can you store Strings can also store Integer , Long , Float , Double and Boolean .

Useful Link

    
14.04.2016 / 01:21