Mayank Tripathi

Total Post:807

Posted by  Mayank Tripathi
 764  View(s)
Rate this:
  1. Mayank Tripathi


    Describe SharedPreference storage..

    SharedPreference is the simplest mechanism to store the data in android. You do not worry about creating the file or using files API.It stores the data in XML files. SharedPreference stores the data in key value pair.The SharedPreferences class allows you to save and retrieve key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: boolean, floats, int, longs, and strings.The data is stored in XML file in the directory data/data//shared-prefs folder.
    Application of SharedPreference

    • Storing the information about number of visitors (counter).
    • Storing the date and time (when your Application is updated).
    • Storing the username and password.
    • Storing the user settings.
    For storing the data
    SharedPreferences sf=getSharedPreferences("MyData", MODE_PRIVATE);
    SharedPreferences.Editored= sf.edit(); 
    ed.putString("name", txtusername.getText().toString()); 
    ed.putString("pass", txtpassword.getText().toString()); 

    In this example I have taken two activities. The first is MainActivity and the second one is SecondActivity.When user click on save button the user name and password that you have entered in textboxes, will be stored in MyData.xml file.

    Here MyData is the name of XML file .It will be created automatically for you. 

    MODE_PRIVATE means this file is used by your application only.

    txtusernameand txtpassword are two EditText control in MainActivity.

    For retrieving the data :

    Public static final String DEFAULT=”N? A”;

    DEFAULT is a String type user defined global variable.If the data is not saved in XML file and user click on load button then your application will not give the error. It will show message “No Data is found”. Here name and pass are same variables that I have used in MainActivity.

    SharedPreferences sf=getSharedPreferences("MyData", Context.MODE_PRIVATE);
    String Uname=sf.getString("name", DEFAULT);
    String UPass=sf.getString("pass", DEFAULT);
    Toast.makeText(this, "No data is found", Toast.LENGTH_LONG).show(); 
    Txtpassword.setText(UPass) ;

      Modified On Mar-28-2018 04:12:04 AM



Enter your email address here always to be updated. We promise not to spam!