Android: Accessing SharedPreferences inside a DialogFragment - java

So I have an activity with a few buttons each one with a TextView bellow, when I click on the button appears a Dialog Fragment with an EditText and a 'Done' button, I write something in the EditText, click 'Done' and ti changes the Text bellow the button I clicked, that is working fine. What I need is to replace the previous text with the new text in the shared preferences I that I already have.
My SharedPreferences: SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
Opening the Dialog and passing the TextView's ID:
fm = getFragmentManager();
myFragment = new Fragment_Subject_Edit();
FirstButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Bundle data = new Bundle();
data.putInt("ID", FirstText.getId());
myFragment.setArguments(data);
myFragment.show(fm, "ClassEditor");
return false;
}
});
Recieve ID in the Dialog Fragment:
if (getArguments() != null) {
Bundle data = getArguments();
int id = data.getInt("ID");
mTextView = (TextView) getActivity().findViewById(id);
}
Adding the new text to the TextView bellow the button:
DoneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newText = mEditText.getText().toString();
mTextView.setText(newText);
getDialog().dismiss();
}
});
The question here is really just how to update the Shared Preferences

You will simply use Editor to save your new data on SharedPreferences
So in this case your code will be like this
DoneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newText = mEditText.getText().toString();
mTextView.setText(newText);
SharedPreferences.Editor e = getActivity().getPreferences(Context.MODE_PRIVATE).edit();
editor .putString ("key","your_value");
editor .commit();
getDialog().dismiss();
}
});

Related

How to save Button Text with SharedPreferances set by EditText

I set the Button Text trough editText and a long Button Click. Afterwards the editText is set to an emptyString again. How do i save the Button name in SharedPreferances (as a String i guess) and read it when i restart the app?
package com.example.myapplication;
import ...
public class MainActivity<button1> extends AppCompatActivity {
Button button
EditText editText1
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button3);
button.setOnClickListener(v -> opensecondone());
button.setOnLongClickListener(v -> naming());
editText1 = (EditText) findViewById(R.id.tv_textView);
}
public boolean naming() {
button = this.findViewById(R.id.button3);
button.setText(editText1.getText().toString());
editText1.setText(" ");
return true;
}
public void opensecondone() {
Intent intent = new Intent(this, firmaeins.class);
startActivity(intent);
}
}
first you store your name in naming function
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("yourMessageKey", message);
editor.commit();
then you get the value inside your oncreate of activity :
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
String message = sharedPref.getString("yourMessageKey", "");

OnSaveInstanceState and OnRestoreInstanceState not saving on app quit

I am trying to save my programmatically created CardView and TextView using OnSaveInstanceState and OnRestoreInstanceState as in the sample code.
While debugging, I notice that values are saved but when I quit the app and reopen it, nothing is being restored.
What am I doing wrong?
**#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("key", userInput.getText().toString());
savedInstanceState.putInt("LayoutId", mConstraintLayout.getId());
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getString("key");
savedInstanceState.getInt("LayoutId");
}**
This are the methods I am using after 'OnCreate'
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = getApplicationContext();
mConstraintLayout = findViewById(R.id.top_left);
addButton = findViewById(R.id.add);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View popup = findViewById(R.id.popup);
popup.setVisibility(View.VISIBLE);
}
});
mButton = (Button) findViewById(R.id.create);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final CardView sticker = new CardView(mContext);
CardView.LayoutParams params = new CardView.LayoutParams(
CardView.LayoutParams.WRAP_CONTENT,
CardView.LayoutParams.WRAP_CONTENT
);
params.height=500;
params.width=500;
CheckBox privateCalendar = findViewById(R.id.checkPrivate);
CheckBox workCalendar = findViewById(R.id.checkWork);
CheckBox holidayCalendar = findViewById(R.id.checkHoliday);
if (privateCalendar.isChecked()){
sticker.setCardBackgroundColor(Color.parseColor("#FFCC00"));
}
else if (workCalendar.isChecked()){
sticker.setCardBackgroundColor(Color.parseColor("#FF8080"));
}
else if (holidayCalendar.isChecked()){
sticker.setCardBackgroundColor(Color.parseColor("#66B3FF"));
}
else{
sticker.setCardBackgroundColor(Color.parseColor("#FFCC00"));
}
sticker.setId(CardView.generateViewId());
sticker.getId();
sticker.setTag(CARD_VIEW_TAG);
sticker.setLayoutParams(params);
sticker.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
ClipData.Item item = new ClipData.Item((CharSequence) sticker.getTag());
String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
ClipData data = new ClipData(sticker.getTag().toString(), mimeTypes, item);
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(sticker);
sticker.startDrag(data
, shadowBuilder
, sticker
, 0
);
sticker.setVisibility(View.INVISIBLE);
return true;
}
});
TextView tv = new TextView(mContext);
tv.setLayoutParams(params);
tv.setBackgroundColor(Color.TRANSPARENT);
tv.setGravity(Gravity.CENTER);
userInput = findViewById(R.id.editText);
tv.setText(userInput.getText());
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
tv.setTextColor(Color.BLACK);
sticker.addView(tv);
mConstraintLayout.addView(sticker);
View popup = findViewById(R.id.popup);
popup.setVisibility(View.GONE);
}
});
}
SavedInstanceState and RestoreInstanceState will work if activity is recreated due to config change like orientation change or android system killed that activity due to memory issue, Then only savedInstanceState and restoreInstanceState comes in role.
If you finish activity by yourself and start activity again then there is no use of these methods.
Try to save data in SharedPreference instead savedInstanceState.
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
For Storing data:-
editor.putString("key", userInput.getText().toString());
editor.putInt("LayoutId", mConstraintLayout.getId());
editor.apply();
For retriving data:-
editor.getString("key", null); // getting String
editor.getInt("LayoutId", 0); // getting Integer
First of all if by "close the app" you mean destroy it, this will never work for you.
Second of all in onRestoreInstanceState you don't do anything with those values, you simply read them but don't store them anywhere.
If you mean to recreate the old form after switching back and forth between apps, with your app being destroyed in the background then, you need to only set values in onSaveInstanceState like you did, and in onCreate(Bundle savedInstance), you should do something like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstance == null) {
//read values from getIntent()
key = getIntent().getString("key);
LayoutId = getIntent().getInt("LayoutId");
} else {
//read values from savedInstanceState
key = savedInstanceState.getString("key");
LayoutId = savedInstanceState.getInt("LayoutId");
}
}

Check which one of two buttons has been pressed and pass a value to sharedpreferences

I have an activity with two buttons. Both buttons bring you to the next activity and at the same time a value is being given to sharedpreferences. I want to access this value in my very last activity.
How do I check which of the two buttons has been pressed?
What is the problem in my code? I always get the same value in the end. So it seems like I always press the same button, which I don't.
Here the first activity where the two buttons are in:
public void imagebutton (){
ImageButton btn = (ImageButton) findViewById(R.id.imageButton3);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Akt1.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("name2", "Geschlecht");
editor.clear();
editor.apply();
startActivity(new Intent(Akt1.this, Akt2.class));
}
});
}
//buttonclick mit datapass gemixt
private void imagebutton1 () {
ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("name","Geschlecht");
editor.commit();
Intent intent = new Intent (Akt1.this,Akt2.class);
startActivity(intent);
And here the code from the last activity where I want to access the value that has been passed to sharedpreferences from the buttonclick:
public class Akt6 extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Hiermit Layout mit Activity verbinden
setContentView(R.layout.activity_akt6);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name",null);
name ="Männlich";
SharedPreferences preferences2 = PreferenceManager.getDefaultSharedPreferences(this);
String name2 = preferences.getString("Name", "default");
name2 ="Weiblich";
//zeige Wert on screen
TextView textView19 = (TextView) findViewById(R.id.textView19);
textView19.setText(name);
You are getting the same value because of this:
String name = preferences.getString("Name", null);
...
String name2 = preferences.getString("Name", "default");
You're using the same key "Name". You stored the values with the keys "name" and "name2".
So if you want to get those values you need to write something like this:
String name = preferences.getString("name", null);
...
String name2 = preferences.getString("name2", "default");
Also you are storing always the same value "Geschlecht":
editor.putString("name2", "Geschlecht");
editor.putString("name","Geschlecht");
I'm not sure what are you doing on your activity, but if you need to know wich button has been pressed you can do the follow:
To your button listeners add this:
public void imagebutton (){
...
editor.putString("name2", "Geschlecht");
editor.putString("ButtonPressed","Button1"); // This is the new line
...
}
...
public void imagebutton1 (){
...
editor.putString("name2", "Geschlecht");
editor.putString("ButtonPressed","Button2"); // This is the new line
...
}
Then, to get the value of the button pressed in your activity do this:
...
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String button = preferences.getString("ButtonPressed","");
if(!button.isEmpty()){
switch(button){
case "Button":
//You have pressed the first button
break;
case "Button2":
//You have pressed the second button
break;
}
}
You should use constants for every String passed as sharedpref name and value to avoid human mistakes on your code.
Good luck!
What is the problem in my code? I always get the same value in the
end. So it seems like I always press the same button, which I don't.
1. In your method imagebutton1(), you are storing value for name into different sharedPreferences (myprefs):
// Akt1
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
and trying to get value of name from default sharedPreferences:
// Akt6
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
2. You have used KEY name to store value:
// Akt1
editor.putString("name","Geschlecht");
and getting value by using different KEY Name which is totally wrong.
// Akt6
String name = preferences.getString("Name", null);
How do I check which of the two buttons has been pressed?
SOLUTION:
Use same SharedPreferences to store and retrieve value.
Use same KEY "name" to store and retrieve value for name from SharedPreferences
Update your code as below:
Akt1.java
public void imageButton (){
ImageButton btn = (ImageButton) findViewById(R.id.imageButton3);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Akt1.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("name", "Male");
editor.commit();
startActivity(new Intent(Akt1.this, Akt2.class));
}
});
}
private void imageButton1 () {
ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Akt1.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("name", "Female");
editor.commit();
startActivity(new Intent(Akt1.this, Akt2.class));
}
});
}
Akt6.java
public class Akt6 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_akt6);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("name", "default");
TextView textView19 = (TextView) findViewById(R.id.textView19);
textView19.setText(name);
}
}
Hope this will help~

How to implement a ClickListener for a button from a custom layout to use in a FragmentDialog

I'm try to set the action for ImageButton. When the DialgoFragment is called and is shown on screen, I want to preess the button and get an action. When I put my action inside that onClick in the code below it didn't work. I'm sure that's not the right way of doing it.
I'm using this class as fragment:
public class GeneralDialogFragment extends DialogFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout to use as dialog or embedded fragment
View v = inflater.inflate(R.layout.activity_dialog, container, false);
ImageButton mImageButton = (ImageButton) v.findViewById(R.id.image_button);
mImageButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String name = "";
SharedPreferences prefs = getActivity().getSharedPreferences("MY_PREFS_NAME", Context.MODE_PRIVATE);
String yourmessage = prefs.getString("msg", null);
if (yourmessage != null) {
name = prefs.getString("msg", "No name defined");//"No name defined" is the default value.
}
ScrollTextView txt = (ScrollTextView) v.findViewById(R.id.scroll_text);
txt.setText(name);
txt.setTextSize(220);
txt.startScroll();
}
});
return v;
}
And in this activity_dialog layout I have an ImageButton:
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/image_button"
android:src="#drawable/ic_image_500px"/>
Edited: Now the action is in the class above. The error actually is in the action. I have the MainActivity where I press this send button:
public void send(View view){
EditText mEditText = (EditText)findViewById(R.id.text_msg);
String MESSAGE = mEditText.getText().toString();
SharedPreferences.Editor editor = getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).edit();
editor.putString("msg", MESSAGE );
editor.commit();
Intent intent = new Intent(this, MessageActivity.class );
startActivity(intent);
}
It calls the MessageActivity where I call the GeneralDialogFragment class which shows the ImageButton with this code:
DialogFragment mDialog = new GeneralDialogFragment();
mDialog.show(getSupportFragmentManager(), "Dialog TAG");
Because of v which you've added it before, it's working without any errors:
View v = inflater.inflate(R.layout.activity_dialog, container, false);
ImageButton mImageButton = (ImageButton) v.findViewById(R.id.image_button);

Reload SharedPreferences

I'm quite new to Android Prorgramming and have a problem understandig SharedPreferences.
I have a Main Activity and a Settings Activity.
I want to be able to change a SharedPreference (here called firstWaitTime) in the Settings Activity and work with it in the Main Activity.
I can Set the new value in the settings, but in the Main Activity i only see the new value when i close and reopen the app.
I Think i would need a OnPrefrenceChanged Listender but i have no idea how to implement it...
The Main one looks like this:
public class MainActivity extends ActionBarActivity {
//Radio Button
private int stufe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
int firstWaitTime = settings.getInt("firstWaitTime", 12);
int secondWaitTime = settings.getInt("secondWaitTime", 8);
int thirdWaitTime = settings.getInt("thirdWaitTime", 6);
//TEST
final TextView test = (TextView) findViewById(R.id.test);
test.setText("" + firstWaitTime);
}
The Settings Activity looks like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
final SharedPreferences settings = this.getSharedPreferences("settings", MODE_PRIVATE);
//BUTTON
final EditText edit1 = (EditText) findViewById(R.id.edit1);
Button save=(Button) findViewById(R.id.savebtn);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//prefs = getSharedPreferences(prefName, MODE_PRIVATE);
//SharedPreferences.Editor editor = prefs.edit();
SharedPreferences.Editor editor = settings.edit();
//---save the values in the EditText view to preferences---
editor.putInt("firstWaitTime", Integer.parseInt(edit1.getText().toString()));
//---saves the values---
editor.commit();
Toast.makeText(getBaseContext(), "Saved", Toast.LENGTH_SHORT).show();
}
});
}
What is the best way to achieve this?
onCreate() will not be called as Android hasn't killed the Activity. Try putting your code in onResume() instead. For more info read up on the Android Activity lifecycle.

Categories