Tuesday, September 4, 2012

shared preference in android


Hello Dear Friends,

I am going to share a sample code in Android for for shared preference in android. Actually Shared Preference stored data at applications label, I think its should help you..

package shared.preference.test;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;

public class SharedPreference extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the app's shared preferences
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);
// Get the value for the run counter
int counter = app_preferences.getInt("counter", 0);
// Update the TextView
TextView text = (TextView) findViewById(R.id.text);
text.setText("This app has been started " + counter + " times.");
// Increment the counter
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("counter", ++counter);
editor.commit(); // Very important
}
}



It’s another example of shared preference where we can store data at application level for life long-

Step1- Create an activity and add below given code
 String USER_EMAIL = ""; //variable declaration is most important  
SharedPreferences myPrefs;
// use shared preference for store email id for next page
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString(USER_EMAIL, editTextSendMail.getText().toString());
prefsEditor.commit();
Step2- Create second activity and add get values from shared-preference
String USER_EMAIL = ""; //variable declaration is most important  
SharedPreferences myPrefs;
String prefEmail;
// get email-id from previous activity via shared preference
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",MODE_WORLD_READABLE);
prefEmail = myPrefs.getString(USER_EMAIL, "");
Log.e("***user email**", prefEmail);






2 comments:

  1. Hi Manish,

    Your tutorials are very helpful. I'm working on an app with login and logout functionality. How should I save the user information to keep the user logged in? I think it is risky to store the password in shared preference. If I want to store the username and password to be used inside an Android application, what is the best way to do it? I would really appreciate your reply.

    Thanks,
    Nidhi

    ReplyDelete
    Replies
    1. Yes you are right storing password is not a good idea. There are two way you can use in your application-

      1) use a boolean type of shared prefrence isLogout. Make it true in starting and on successfully login make it false, so next time on splash screen if isLogout==true send user for login else redirect directly on dashboard.

      2) convert yoour password in md5 or sha1 encrypted form and store it.

      Delete