-5

I read about SharedPreferences but did not understand where i need to put the saving data and where to put the get objects. In my app i get the full name when i open it in the first time by dialog. I need to save the full name for ever (until the user will delete the app or something).

Where and what should i write to save the data(in onDestroy)? Like :

 // Create object of SharedPreferences.
 SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
//now get Editor
 SharedPreferences.Editor editor= sharedPref.edit();
//put your value
 editor.putString("name", strName);
 editor.commit();
 SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
 String name = sharedPref.getString("name", "");

And where and what should i write to get the data(in onCreate)?

Ravenix
  • 1,010
  • 4
  • 15
  • 40

1 Answers1

0

You don't have to to anything in onDestroy(). If your app gets uninstalled your data in shared preferences will be removed as well.

editor.putString("name", strName);

The first parameter is the key and the second one ist the value.

if you want to save the user's name, you pass the first parameter "name" and for the second parameter, the user's name.

when you want to read the user's name later you use

String name = sharedPref.getString("name", "");

Again, the first parameter is the key. You want to read the user's name so you use "name" and the second parameter is the default value, if there hasn't been saved a value, yet.

Edric
  • 24,639
  • 13
  • 81
  • 91
phe
  • 169
  • 1
  • 8
  • hi friend,tell me what i need to write exactly and where(onCreate , onResume etc). for exmaple , what i need to write exactly to save and the same to get the string(the value is : private String strFullName). – Nir Avisrur Feb 28 '18 at 11:27
  • You create a dialog with a button. When the user clicks the button you save his name. Therefore, you register an onclicklistener for the button. In this listener you write editor.putString("name", strName); In the oncreate method of your main activity you read the name. So, you need to write String name = sharedPref.getString("name", ""); – phe Feb 28 '18 at 16:25
  • i tried and its not working. can you give me example the code to put in the dialog when i click on the dialog's button. and what to write the onCreate. anyway , thanks! – Nir Avisrur Feb 28 '18 at 20:23
  • I need more information. What did you try? What is not working? You can amend your question by updating it with this information. For instance: your code you have written so far and a description about the problems you face – phe Mar 01 '18 at 15:19
  • when i open my app i put the full name of the customer. i need to save the name every time when i reopen the app. that's all . where should i write the code and what? thanks – Nir Avisrur Mar 04 '18 at 09:07