Saving data on your phone [closed]

0

Hello, I have an application that receives a certain data from an api, what should be done so that the data received by the api is saved on the cell phone? because I want the application to work without the internet

    
asked by anonymous 14.01.2017 / 20:02

1 answer

2

There are several ways, as you get only a text and a double value, I recommend you use SharedPreferences, which you can implement quickly and is much simpler than a database for little data (which would be another option).

To save what you need, use something like this:

public static final String CONSTANTE_DOUBLE = "double"; //pode ser o que vc quiser nas duas, o que importa eh usar o mesmo pra salvar e acessar
public static final String CONSTANTE_STRING = "string";

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putDouble(CONSTANTE_DOUBLE, seuDouble);
editor.putString(CONSTANTE_STRING, seuTexto);
editor.commit();

Note that it works as a key-value pair, so the first argument of the put is the key, which you will use later to fetch this value, and the second is the content. This key usually uses a static constant.

And to get the value:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
double seuDouble = sharedPref.getDouble(CONSTANTE_DOUBLE, 0.0);
String seuString = sharedPref.getString(CONSTANTE_STRING, "");

Just pass the constant and you're done. The second parameter when you read SharedPreferences is a default value, in case you ask for sharedPreferences is not there, as a way to prevent nullPointers.

Documentation in Portuguese, to learn more

I think it was very clear, but any questions just call: D

    
14.01.2017 / 22:43