0

I am a newbie at Android programming.

I created a simple Empty Activity app in Android Studio and it has a bunch of UI fields. After I type in those input fields if I press the back button, the activity gets destroyed loosing all my entered data.

But if I press the home button and switch to another app and come back to my app the data is there.

What do i need to do so that I do not loose the data entered?

Update:

Looks like I will have to used shared preferences.

But wondering how the apps like Google Chrome might be persisting the huge amount of data like Web page, the input fields on the webpage etc

Mck
  • 129
  • 1
  • 10

2 Answers2

1

By pressing back you're essentially destroying the Activity and losing any inputted data.

You could use Shared Preferences to persist and retrieve any data you've entered.

First initialize SharedPreferences:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();

Then extract text you've entered from EditText, and replace YOUR_TEXT below.

editor.putString("unique_name", YOUR_TEXT);
editor.commit();

Keep in mind that

unique_name

has to be a unique name for each value you want to save.

After closing and returning to the activity you can retrieve value you have saved, like so:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String YOUR_TEXT = sharedPref.getString("unique_name", "");
Audrius
  • 64
  • 1
  • 5
  • I agree with this answer, but would like to see some more explanation of _how_ to use shared preferences. – Ben P. Oct 12 '18 at 19:30
  • Is that how the other apps (Like Google Maps, Chrome etc) do it to keep the full state (the web page, the scrollbar location, the input fields on a webpage etc) of the app? – Mck Oct 12 '18 at 19:32
  • Updated my answer. @Mck it is usually used for saving small amounts of data, in this case - a few strings. – Audrius Oct 12 '18 at 19:35
  • what do I use to save huge amount of data? – Mck Oct 12 '18 at 19:39
  • SQLite with a wrapper library such as Room. Alternatively, you can also use Firebase or Realm. – Audrius Oct 12 '18 at 19:40
1

For huge chunks of data you can use SQLite Database for android. You should use room for that purpose, Room is an Android library for data persistence. Check Room Practical Guide out.

If your data is small then you can use Shared Preferences too. If you only need to store user data such as inputs as long as the application is running, then you should use ViewModel for that. check this View Model Guide.

Ibtihaj Uddin
  • 138
  • 1
  • 8