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/
Related
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 :)
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"?
I have a single string which the user will edit and will be displayed back to him when he uses the app. He can edit the string at any time. I am familiar with SQLite databases, but because for this purpose I am using only one string/one record, I felt SharedPreferences would be better. However, after following two different tutorials, I am unable to get it so save the data. In both cases I have needed to amend the tutorial code because I will be using two activities, one to view the code, the other to edit it. I was unable to find a tutorial for using sharedpreferences for two activities. Below is the code.
Class to view the code:
public class MissionOverviewActivity extends Activity {
TextView textSavedMem1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mission_view);
textSavedMem1 = (TextView)findViewById(R.id.textSavedMem1);
LoadPreferences();
textSavedMem1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
finish();
return;
}});
};
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
textSavedMem1.setText(strSavedMem1);
}
}
Class to edit the code and return to the view page
public class MissionDetailActivity extends Activity {
EditText editText1;
Button buttonSaveMem1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mission_edit);
editText1 = (EditText)findViewById(R.id.editText1);
buttonSaveMem1 = (Button)findViewById(R.id.buttonSaveMem1);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
}
Button.OnClickListener buttonSaveMem1OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM1", editText1.getText().toString());
viewStatement();
}
};
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
protected void viewStatement() {
Intent i = new Intent(this, MissionOverviewActivity.class);
startActivity(i);
}
}
If any body could answer this question, or point me in the direction of a sharedpreferences tutorial that uses two classes (for edit and displaying), It would be greatly appreciated!
Thanks
getPreferences(int) is private for Activity, you want to share the same SharedPreference between activities you should use this way:
SharedPreferences prefs = this.getSharedPreferences(
"yourfilename", Context.MODE_PRIVATE);
and use the same method when you want to reload it. here the doc for getPrerences(int)
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
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..