Preference application basically save the data in mobile for temporary period. Android preference is used to store and retrieve primitive information.
Create new application with any name from file menu option.
File → New Project → Application name → select API → Add Blank Activity → Activity Name → finish.
In activity_main.xml layout file design your application.
Add following Controls:-
Import Package and write following coding in MainActivity.java class file.
import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends ActionBarActivity { Button bt; EditText et,et1; public static final String Mypref="Myprefs"; public static final String name="names"; public static final String no="nos"; SharedPreferences sharedPreferences; @Override public SharedPreferences getSharedPreferences(String name, int mode) { return super.getSharedPreferences(name, mode); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt=(Button)findViewById(R.id.bt1); et=(EditText)findViewById(R.id.editText); et1=(EditText)findViewById(R.id.editText2); sharedPreferences=getSharedPreferences(Mypref, Context.MODE_PRIVATE); if(sharedPreferences.contains(name)) { et.setText(sharedPreferences.getString(name,"")); } if(sharedPreferences.contains(no)) { et1.setText(sharedPreferences.getString(no,"")); } bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name1=et.getText().toString(); String n=et1.getText().toString(); SharedPreferences.Editor edt=sharedPreferences.edit(); //String names; edt.putString(name,name1); edt.putString(no,n); } }); }
Run your Application and the enter details in EditText, then click save button to save the details.
Now close the application and start it again, now you will understand the concept of preference. It just save your data for temporary period.