How to Save Data on Mobile

Asked

Viewed 41 times

0

Hello I have an application that receives certain data from an api, what should be done for the data received by the api to be saved on mobile? because I want the app to work without internet

  • It depends on the type of data. Photo? Text? Explain more.

  • is a text and a double value

1 answer

2

There are several ways, as you receive only one text and a double value, I recommend you use Sharedpreferences, which you can implement quickly and is much simpler than a database for few 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 good to go. The Second parameter when Voce reads from Sharedpreferences is a default value, in case what you ask for sharedPreferences is not there, as a way to prevent nullPointers.

Documentation in Portuguese, for more information

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.