Monday, August 11, 2014

Shared preference in android store data in internal memory at current time onside of app

In shared preference we can store data in internal memory of app at current time of PP 

THIS IS USE MORE AND  MORE IF WE HAVE need to store data email,password and some other information of that application 

code are as follows

Activity or User interface:-






Sharedprefrence.class

public class Sharedprefrence extends Activity{
EditText edtemail,edtfirstname;
Button btnsave,btnget;
TextView txtemail,txtfirstname;
String email,firstname;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedprefrence);
edtemail=(EditText)findViewById(R.id.editText1);
edtfirstname=(EditText)findViewById(R.id.editText2);
txtemail=(TextView)findViewById(R.id.textView1);
txtfirstname=(TextView)findViewById(R.id.textView2);
btnsave=(Button)findViewById(R.id.button1);
btnget=(Button)findViewById(R.id.button2);

final SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
   final Editor editor = pref.edit();
   btnsave.setOnClickListener(new OnClickListener() {
@SuppressLint("NewApi")
@Override
public void onClick(View v) { 
editor.putString("email", edtemail.getText().toString());
editor.putString("firstname", edtfirstname.getText().toString());
editor.commit();
}
});
btnget.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
email=  pref.getString("email", null); 
firstname=  pref.getString("firstname", null);
  txtemail.setText(email);
  txtfirstname.setText(firstname);
}
});
}
}


Manifest file changes:-

Add a service of storage

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />



Thank you ..It may help you more.....

No comments:

Post a Comment