SharedPreferences in Android dosent work - android

I created a sharedprefreference object and tries to retrieve my data within the same activity, is that an allowed operation? The issue is that once the application starts running, and i entered the text within the textview, the entered text does not reappear in a separate textview. The application suppose to take in the user's entered text and display is just several dp downward, however, the entered text just never reappeared. Thank you all so much in advance.
final static String My_PREFERENCES= "sharedPreferences";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
foodTV = (TextView) findViewById(R.id.foodTV);
foodET = (EditText) findViewById(R.id.foodET);
display = (TextView) findViewById(R.id.displayText);
SharedPreferences sharedPreferences =
getSharedPreferences(My_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.clear();
edit.putString("foodname", foodET.getText().toString());
edit.commit();
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(My_PREFERENCES, Context.MODE_PRIVATE);
String food = sharedPreferences.getString("foodname", "");
display.setText(food);
}
});
}

change your code to
foodTV = (TextView) findViewById(R.id.foodTV);
foodET = (EditText) findViewById(R.id.foodET);
display = (TextView) findViewById(R.id.displayText);
foodET.setOnEditorActionListener(
new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH ||
actionId == EditorInfo.IME_ACTION_DONE ||
event.getAction() == KeyEvent.ACTION_DOWN &&
event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
if (!event.isShiftPressed()) {
SharedPreferences sharedPreferences =
getSharedPreferences(My_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.clear();
edit.putString("foodname", foodET.getText().toString());
edit.commit();
return true;
}
}
return false;
}
});
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(My_PREFERENCES, Context.MODE_PRIVATE);
String food = sharedPreferences.getString("foodname", "");
display.setText(food);
}
});

In fact, I would suggest you using an amazing https://github.com/pilgr/Paper
See how's simple is that:
Only two things are needed:
Initialize library inside your app (or even Activity itself) class
Make calls!
MyApp.java
Just initialize Paper
Paper.init(getApplicationContext());
MyFragment.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Sample food name
String foodName = "apple";
// Write it to paper
Paper.book().write("foodname", foodName);
// Then restore what we have just saved!
String restoredFoodName = Paper.book().read("foodname");
}
Please do note that those calls are not asynchronous! But you can write few simple AsyncTask-s to make them be so.

Related

Save Changed Text Of a TextView

I have an Button in my first activity which changes it background onclick and save with SharedPreferences , but I want to set one more code that when I check the button it set the text of a TextView in my second activity to "Button-Checked" and when I uncheck it set the text of the TextView to "Button-Unchecked" and then SAVE the text (with SharedPreferences or anything else).
In my first activity:
public class MainActivity extends Activity {
private boolean likechek;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button like = (Button) findViewById(R.id.like);
like.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Dog.this);
sp.edit().putBoolean("like_", !likechek).commit();
LikeAnalayzer();
}
});
}
private void LikeAnalayzer() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
likechek = sp.getBoolean("like_", false);
UpdateLikeButton();
}
private void UpdateLikeButton() {
Button like = (Button) findViewById(R.id.like);
if(likechek){
like.setBackgroundResource(R.drawable.starf);
}else{
like.setBackgroundResource(R.drawable.star);
}
}
}
and Second (its empty):
public class Fav extends Activity {
TextView tv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fav);
tv = (TextView) findViewById(R.id.tv);
tv.setText("");
}
}
Thanks for your answer , I really need it.
If I understand you right, you want to set the text to the textView if the button is checked, so you could do it like the change of the background like this for example:
private void UpdateLikeButton() {
Button like = (Button) findViewById(R.id.like);
TextView myTextView = (TextView)findViewById(R.id.textView);
if(likechek){
like.setBackgroundResource(R.drawable.starf);
myTextView.setText("Button-Checked");
//and save in the shared preferences the state:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Dog.this);
sp.edit().putString("button_state", "Button-Checked").commit();
}else{
like.setBackgroundResource(R.drawable.star);
myTextView.setText("Button-Unchecked");
//and save in the shared preferences the state:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Dog.this);
sp.edit().putString("button_state", "Button-Unchecked").commit();
}
}
and if you want to set the text of the textView in the second activity just skip the part in the first one that is myTextView.setText("Button-Checked"); like this:
private void UpdateLikeButton() {
Button like = (Button) findViewById(R.id.like);
if(likechek){
like.setBackgroundResource(R.drawable.starf);
//and save in the shared preferences the state:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Dog.this);
sp.edit().putString("button_state", "Button-Checked").commit();
}else{
like.setBackgroundResource(R.drawable.star);
//and save in the shared preferences the state:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Dog.this);
sp.edit().putString("button_state", "Button-Unchecked").commit();
}
}
and do it in the second one like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fav);
tv = (TextView) findViewById(R.id.tv);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String buttonState = sp.getString("button_state", "");
tv.setText(buttonState);
}
Hopefully this helps you :)

Android Shared Preferences not displaying

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

Android: Store array of strings in shared preferences dynamically

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/

How can I save ints to be retained even when the application is not running?

When I click on an option I want a check sign to appear to show it has been purchased. I am using SharedPreferences and have made all the links; however, when I click back or exit and then re-enter the application, the check is gone and any history of anything I did before is gone. How do I save the data so that it is kept even when the application is off or I'm at another page in the game. This is my code so far:
ImageView tick1;
int mYellCheck, mYellCheck1;
public static String sharedPrefs = "MyData";
SharedPreferences data;
SharedPreferences.Editor editor;
int mYellAlpha;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.upgrades);
update();
coins = Replay.totalCoins + Replay4.totalCoins + Replay5.totalCoins
+ Replay6.totalCoins;
data = getSharedPreferences(sharedPrefs, MODE_PRIVATE);
tick1.setAlpha(mYellCheck);
}
public void update() {
TextView coinScore = (TextView) findViewById(R.id.tvScore);
coinScore.setText("You have " + coins + " coins");
tick1 = (ImageView) findViewById(R.id.ivtick1);
ImageView moreYellow = (ImageView) findViewById(R.id.ivMoreYellow);
ImageView back = (ImageView) findViewById (R.id.ivBack);
back.setOnClickListener(this);
moreYellow.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.ivMoreYellow:
mYellAlpha = 255;
SharedPreferences.Editor editor = data.edit();
editor.putInt("MoreYellowUpgrade", mYellAlpha);
editor.commit();
data = getSharedPreferences(sharedPrefs, MODE_PRIVATE);
mYellCheck = data.getInt("MoreYellowUpgrade", 0);
tick1.setAlpha(mYellCheck);
break;
case R.id.ivBack:
Intent i = new Intent ("m.k.zaman.SpotActivity");
startActivity(i);
break;
}
}
EDIT
or Should i just use internal storage?
Try replacing your current onClick call to R.id.ivMoreYellow with this:
case R.id.ivMoreYellow:
mYellAlpha = 255;
mYellCheck = data.getInt("MoreYellowUpgrade", 0);
tick1.setAlpha(mYellCheck);
SharedPreferences.Editor editor = data.edit();
editor.putInt("MoreYellowUpgrade", mYellAlpha);
editor.commit();
break;
You were first overwriting all of the data in the SharedPreferences, and then calling to receive that data that you just overwrote, so I placed the getInt() call before the putInt(). Do you change mYellAplha to anything other than 255 though? If you don't you will never notice a change in SharedPreferences if you are always saving and getting 255.

Android:problem in remember me functionality of login Activity

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..

Categories

Resources