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 :)
Related
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.
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 two activities where the main one has a TextView which can be altered in a sharedPreference in the second activity. When the user wants to change or "saves" the string, it saves it in the SP file, and returns back to the main activity. However, the TextView DOES not change to the new one and shows the old one. The app needs to restart for it to work.
My goal was to use the activity lifestle upon the systems onResume but that didn't pick up the new string at all.
I am asking how to change the TextView upon saving/returning from the second activity.
The line in question is: checkboxmessage = (sp.getString("checkboxdescr", ""));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//
// sp= PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
sp = getSharedPreferences("contactapp", 0);
// named preferences - get the default ones and finish with it
//SET TEXTS
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
TextView tv = (TextView) findViewById(R.id.sexycheckbox);
tv.setText(checkboxtext);
CheckBox cb = (CheckBox) findViewById(R.id.sexycheckbox);
////TOPCLEAR
TextView tt = (TextView)findViewById(R.id.toptext2);
tt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = (EditText)findViewById(R.id.edit_name);
EditText et2 = (EditText)findViewById(R.id.edit_number);
et.setText("");
et2.setText("");
CheckBox sexycheck;
sexycheck = (CheckBox)findViewById(R.id.sexycheckbox);
if (sexycheck.isChecked()) {
sexycheck.setChecked(false);
}
}
});
}
protected void onResume(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
sp = getSharedPreferences("contactapp", 0);
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
TextView tv1 = (TextView) findViewById(R.id.sexycheckbox);
tv1.setText(checkboxtext);
}
Change your code like this and see if it works:
#Override
protected void onResume() {
super.onResume();
tv1.setText("new Text test");
}
Even when You copy paste You still need to know what You coping.
replace theses lines
super.onCreate(savedInstanceState); //You call wrong parent method here
this.requestWindowFeature(Window.FEATURE_NO_TITLE); //you call this in onCreate already
setContentView(R.layout.activity_main); //you call this in onCreate already
sp = getSharedPreferences("contactapp", 0); //you call this in onCreate already
with
super.onResume(savedInstanceState);
in onResume() method.
I have found a very good solution to my problem on another post (Save entered text in editText via button)
however when I implement this code, my application crashes. Any advice would be appreciated, the error I receive is that the "String or" in the method makeTag() is not used. Please have a look
private Button savenotebutton1;
private SharedPreferences savednotes;
private EditText editText1;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.x1);
savenotebutton1 = (Button) findViewById(R.id.savenotebutton1);
editText1 = (EditText) findViewById(R.id.noteEditText1);
savednotes = getSharedPreferences("notes",MODE_PRIVATE);
editText1.setText(savednotes.getString("tag", "Default Value")); //add this line
savenotebutton1.setOnClickListener(saveButtonListener);
}
private void makeTag(String tag){
String or = savednotes.getString(tag, null);
SharedPreferences.Editor preferencesEditor = savednotes.edit();
preferencesEditor.putString("tag",tag); //change this line to this
preferencesEditor.commit();
}
public OnClickListener saveButtonListener = new OnClickListener(){
#Override
public void onClick(View v) {
if(editText1.getText().length()>0){
makeTag(editText1.getText().toString());
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(editText1.getWindowToken(),0);
}
}
};
}
You should replace this
String or = savednotes.getString(tag, null);
With
String or = savednotes.getString("tag", "Default Value")
Under your makeTag() function
Update: Error is about you are not register your activity into manifest.xml file.
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/