I want to create simple app for learning purposes. You enter a text, app saves it using Shared Preferences. And in the TextView I want to display this saved text.
My code looks like this:
public class MainActivity extends Activity {
Button button;
EditText editText;
TextView textSaved;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
textSaved = (TextView) findViewById(R.id.savedtext);
editText = ( EditText ) findViewById(R.id.editText1);
LoadPreferences();
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SavePreferences("Text1", editText.getText().toString());
LoadPreferences();
}
});
}
protected void SavePreferences(String string, String string2) {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(string, string2);
editor.commit();
}
private void LoadPreferences() {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String stringSaved = sharedPreferences.getString("Text", "");
textSaved.setText(stringSaved);
}
TextView in xml:
<TextView
android:id="#+id/savedtext"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
But the shared preferences text isn't getting showed in TextView. Can anyone tell me what's wrong with my code?
You have saved it to preference "Text1", but are reading from "Text"
Change them to match, for example:
SavePreferences("Text", editText.getText().toString());
Use
SharedPreferences sharedPreferences = getPreferences("Pref_Name",MODE_PRIVATE);
Also the key is different while saving and fetching.
String stringSaved = sharedPreferences.getString("Text", "");
Use Text1 on both places
Replace following line
String stringSaved = sharedPreferences.getString("Text", "");
with
String stringSaved = sharedPreferences.getString("Text1", "");
For more about sharedPreferences from My tutorial.
Change this :
String stringSaved = sharedPreferences.getString("Text", "");
to this:
String stringSaved = sharedPreferences.getString("Text1", "");
for more informations you can check this http://developer.android.com/reference/android/content/SharedPreferences.html
Related
public class LoginActivity extends BaseActivity{
private SharedPreferences pref;
private SharedPreferences.Editor editor;
private EditText accountEdit;
private EditText passwordEdit;
private Button login;
private CheckBox rememberPass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
accountEdit =(EditText)findViewById(R.id.account);
passwordEdit = (EditText)findViewById(R.id.password);
rememberPass=(CheckBox)findViewById(R.id.remember_pass);
login = (Button)findViewById(R.id.login);
editor.putBoolean("remember_password",false);
boolean isRemember = pref.getBoolean("remember_password",false);
if(isRemember){
String account = pref.getString("account", "");
String password =pref.getString("password", "");
accountEdit.setText(account);
passwordEdit.setText(password);
rememberPass.setChecked(true);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String account =accountEdit.getText().toString();
String password = passwordEdit.getText().toString();
if (account.equals("admin")&& password.equals("123456"))
{ editor = pref.edit();
if(rememberPass.isChecked())
{
editor.putBoolean("remember_password",true);
editor.putString("account",account);
editor.putString("password",password);
}
else
{
editor.clear();
}
editor.commit();
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(LoginActivity.this,"account for password is invalid",
Toast.LENGTH_LONG).show();
}
}
});
}
}
I use Eclipse to code android.I got an error in LogCat,which is NullPointerException cause by "boolean isRemember = pref.getBoolean("remember_password",false);"
I don't know why.How to use getBoolean correctly?
Thanks in advance.
Because pref=null at
boolean isRemember = pref.getBoolean("remember_password",false);
initialized it before used
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
You have to create the object of the Shared preference than you can use it in yours code
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
than use
boolean isRemember = pref.getBoolean("remember_password",false);
Use this simple way to use prefrences
private SharedPreferences getPrefs;
//in OnCreate
getPrefs = PreferenceManager.getDefaultSharedPreferences(Activity_Name.this);
//At insertion value
getPrefs.edit().putBoolean("Key_Name", false).commit();
//At fetching Values
boolean a = getPrefs.getBoolean("Key_Name", false);
I am trying to retrieve the editText value and the button color using shared preferences. For the editText, it works very well but the problem is in saving and loading the color of the button. Note that I want to save the current color of the button by onWriteClick method and color the button by its color by onReadClick.
Here what I wrote:
Button btn ;
EditText c;
private static final String KEY = "key";
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c = (EditText) findViewById(R.id.editText1);
btn = (Button) findViewById(R.id.button);
preferences = getSharedPreferences("preferences", Context.MODE_PRIVATE);
}
//shared preferences
#SuppressLint("NewApi")
public void onWriteClick() {
Editor editor = preferences.edit();
Editor color = preferences.edit();
editor.putString(KEY, c.getText().toString());
//Here is the problem
color.putString(KEY, btn.setBackgroundColor("#FFFFF"));
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
editor.apply();
} else {
// This call is synchronous and should be done in a background
// thread
editor.commit();
}
}
public void onReadClick() {
String text = preferences.getString(KEY, null);
c.setText(text);
}
}
Any Help please
you are saving EditText content and Button color in the same SharedPreference location using KEY. Define two tag: TEXT_KEY, COLOR_KEY and save the text using TEXT_KEY and the color using COLOR_KEY
Button btn ;
EditText c;
private static final String TEXT_KEY = "tkey";
private static final String COLOR_KEY = "ckey";
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c = (EditText) findViewById(R.id.editText1);
btn = (Button) findViewById(R.id.button);
preferences = getSharedPreferences("preferences",Context.MODE_PRIVATE);
}
#SuppressLint("NewApi")
public void onWriteClick() {
PaintDrawable pd = (PaintDrawable) btn.getBackground();
Editor editor = preferences.edit();
editor.putString(TEXT_KEY, c.getText().toString()).commit();
editor.putInt(COLOR_KEY, pd.getPaint().getColor()).commit();
}
public void onReadClick() {
c.setText(preferences.getString(KEY, ""));
btn.setBackgroundColor(preferences.getInt(COLOR_KEY, 0);
}
}
On line 10 you should use
(Button) findViewById(R.id.button);
instead of
(EditText) findViewById(R.id.button);
The setBackgroundColor()-method expects an integer. http://developer.android.com/reference/android/view/View.html#setBackgroundColor%28int%29
You could use Color.parseColor() method to parse your color string.
http://developer.android.com/reference/android/graphics/Color.html#parseColor%28java.lang.String%29
colorputString(KEY, btn.setBackgroundColor(Color.parseColor("#FFFFF")));
Update:
Why are you trying to use a String to store the color? Simply use integer. And use the appropriate Getter-Method. setBackgroundColor()-method returns void.
color.putInt(KEY, btn.getBackgroundColor());
2nd Update:
There is no getBackgroundColor-method. But this question will help you: Is there such a method call "getBackgroundColor"?
So I have EditTextPreference in my Preferences, I want to type something in and save it, then i want to get that text in Activity. My key of EditTextPreference is B1. I tried this code :
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String samples = getPrefs.getString("B1", "");
b1.setText(samples);
<EditTextPreference
android:dialogTitle="Button 1"
android:key="B1"
android:summary="Set text on button 1"
android:title="Set text on button 1" />
I get java.lang.NullPointerException between those
String samples = getPrefs.getString("B1", "lol");
b1.setText(samples);
Declare:
SharedPreferences pref = this.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
Put a value (can be int, String, etc)
String tom = "tom";
pref.edit().putString("tom", tom).commit(); // To set a value to SharedPreferences
Get a value (remember the type)
String name = pref.getString("tom", null); // To get a value from SharedPreferences
See SharedPreferences
Try this
Home.java
public class Home extends Activity {
public SharedPreferences prefs;
String mValues;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
mValues= prefs.getString("male", "female");
}
}
Preferences.java
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.setting);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPref, String key) {
Editor editor = sharedPref.edit();
if(key.equalsIgnoreCase("B1")){
editor.putString("male","my value");
}
editor.commit();
}
}
Let me know if it works for you.
In order to write to SharedPreferences you can use:
Editor editor = getPrefs.edit();
editor.putString("B1", "you value here");
editor.commit();
I have only one edittext in my app from which I want to store strings array on button click. Just like history of any browser. I want to show the stored strings when my app starts. I have been trying to use shared preferences with single textview. I have attached the code for my activity.
public class MainActivity extends Activity {
Button insert;
EditText edt;
TextView txt1, txt2, txt3, txt4, txt5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.search_word);
txt1 = (TextView) findViewById(R.id.txt1);
insert = (Button) findViewById(R.id.insert);
insert.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
String text = edt.getText().toString();
editor.putString("key", text);
editor.commit();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_SHORT)
.show();
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(this);
String text = app_preferences.getString("key", "null");
txt1.setText(text);
}
}
My only one textview is populating, I want to show last five search history using this. Please give me some idea regarding this.
Serialize your data. Array -> String and String can be saved to the preference, maybe use JSON to encode / decode your data.
http://developer.android.com/reference/org/json/JSONObject.html
http://www.json.org/
i have create login page with 2 EditText and checkbox and login button.
if i set checkbox to Enabled i want to save data so next time user doesn't need to fill that fields..
i have uses this code but no luck..
public class LoginPage extends Activity {
EditText d_ID;
EditText password;
CheckBox cb;
ImageButton ib;
public static final String PREFS_NAME = "MyPrefsFile";
public String PREFS_USER;
public String PREFS__PASS;
String username;
String upass;
SharedPreferences pref
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.loginpage);
d_ID = (EditText) findViewById(R.id.dulzuID);
password = (EditText) findViewById(R.id.dulzuPASS);
cb = (CheckBox) findViewById(R.id.remember);
ib = (ImageButton) findViewById(R.id.login);
pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
username = pref.getString(PREFS_USER, null);
upass = pref.getString(PREFS__PASS, null);
d_ID.setText(username);
password.setText(upass);
ib.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
startActivity(new Intent(LoginPage.this, Features.class));
}
});
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton cb1, boolean bln) {
PREFS_USER = d_ID.getText().toString();//get user name from EditText
PREFS__PASS = password.getText().toString();//get user Password from EditText
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit().putString(PREFS_USER, username).putString(PREFS__PASS, upass).commit();
}
});
}
}
Any help??
Thanks...
I think you are confusing the variables for retrieving the value of the users password and the variables that identify the username/password values in the preferences. I think that you intend these:
public String PREFS_USER;
public String PREFS__PASS;
to be the identifiers for your stored username and password, however you then set them to be the values that you have pulled from the corresponding EditTexts. I have rewritten some of the code for you:
public static final String PREFS_NAME = "MyPrefsFile";
public static final String PREFS_USER = "prefsUsername";
public static final String PREFS__PASS = "prefsPassword";
...
pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
username = pref.getString(PREFS_USER, "");
upass = pref.getString(PREFS__PASS, "");
...
public void onCheckedChanged(CompoundButton cb1, boolean bln) {
username = d_ID.getText().toString();//get user name from EditText
upass = password.getText().toString();//get user Password from EditText
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit().putString(PREFS_USER, username).putString(PREFS__PASS, upass).commit();
}
Personally, I wouldn't do it like that though. I would check the value of the checkbox when the user submits the form, and only save the username & password at that point. What if the user unchecks and then rechecks the tick box before they have entered their password? You will save empty values and annoy your users.
You are doing small mistake in this part:
if (cb.isChecked()) {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
username = pref.getString(PREFS_USER, null);
upass = pref.getString(PREFS__PASS, null);
d_ID.setText(username);
password.setText(upass);
}
As your view is rendered each time when new activity starts.cb.isEnabled() will always give false because it is not enabled that time.
You can do stuff for your sol like this.
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
if(!pref.getstring(PREFS_USER,null).equals(null)||!pref.getstring(PREFS_USER,null).equals(""))
{username = pref.getString(PREFS_USER, null);
d_ID.setText(username);}
and same for password field
One thing that I would like to tell you: do not store the values when user clicks on check box save it when user presses login button.
If user clicked that check box when he has not entered details the you will save null values.
And why don't you serialize both the objects and save it to memory and again deserialize it when you need to read it?
public void serializeCredentials(String Username,String Password) {
try {
FileOutputStream fStream = openFileOutput(namefile.bin, Context.MODE_PRIVATE) ;
ObjectOutputStream oStream = new ObjectOutputStream(fStream);
oStream.writeObject(Username) ;
FileOutputStream fos = openFileOutput(passwordfile.bin, Context.MODE_PRIVATE) ;
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(Password) ;
oStream.flush() ;
oStream.close() ;
oos.flush() ;
oos.close() ;
Log.v("Serialization success", "Success");
} catch (Exception e) {
Log.v("IO Exception", e.getMessage());
}
}
Don't forget to deserialize when reading data; you can deserialize it similarly.
I think you need to write/initialize this line inside onCreate() method.
SharedPreferences pref;
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.loginpage);
pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
...
}
try doing the editing line by line.. at least in my case, it did the trick..
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton cb1, boolean bln) {
PREFS_USER = d_ID.getText().toString();//get user name from EditText
PREFS__PASS = password.getText().toString();//get user Password from EditText
SharedPreferences.Editor prefEditor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
prefEditor.putString(PREFS_USER, username);
prefEditor.putString(PREFS__PASS, upass);
prefEditor.commit();
}
});
And it would be much better if you follow N-JOY's suggestion to trigger saving data to SharedPreferences during login button click..