listener sharedpreferences - java

I've a problem with this code. I want keep preferences values in my app but I've problem with the listener. Does not work, its does not save new values. Any idea about error(s)?
EDIT: onResume() works because when I open an activity on my app and close it, the value of sharepreferences is correct. Dialogs and activities does not keep values.
public void onCreate(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String listpref) {
if(!preferencesChanged)preferenze();
}
};
sp.registerOnSharedPreferenceChangeListener(listener);
There are some buttons and other info activities called by intents.
A TextView that show a value from array and nothing.
public void onPause() {
super.onPause();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.unregisterOnSharedPreferenceChangeListener(listener);
protected void onResume() {
super.onResume();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String listpref) {
preferencesChanged = true;
}
};
sp.registerOnSharedPreferenceChangeListener(listener);
protected void onStop(){
super.onStop();
if(preferencesChanged){
//Update the app
preferenze();
}
public void preferenze()
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
CheckboxPreference = prefs.getBoolean("checkboxPref", true);
ListPreference = prefs.getString("listpref", "");
Others variables and most if/else.
Preferences.xml:
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.preferences);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String listpref) {

protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(this); sp.registerOnSharedPreferenceChangeListener(this); }
I think, you are missing registerOnSharedPreferenceChangeListener

Related

Chat application online status

I'm trying to make a chat app. Everything is working except one thing. So I want the users to see if the person they chat whit is online. I made that work but now every time the person is going in on an other chat the online status blink. I have found where the problem is but I dont know how to fix it.
So when a person1 is in the chat it can see a green box where it says online if person2 is online. But if person2 is going in to a chat the green box will blink for person1.
The problem is in onResume and onPause. So when person2 is going from mainActivity to chatActivity it will do onPause() on mainActivity and set online to 0 and the do onResume() on chatActivity where it sets it to 1.
I know that the order is ActivityA.onPause, ActivityB.onCreate, ActivityB.onStart, ActivityB.onResume, ActivityA.onStop. So I dont want it to do onPause() when it going from one Activity to another Activity but still do it when you tab down or close the app. is that possible?
public class BaseActivity extends AppCompatActivity {
private DocumentReference documentReference;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceManager preferenceManager = new
PreferenceManager(getApplicationContext());
FirebaseFirestore database = FirebaseFirestore.getInstance();
documentReference = database.collection(Constants.KEY_COLLECTION_USERS)
.document(preferenceManager.getString(Constants.KEY_USER_ID));
}
#Override
protected void onPause() {
super.onPause();
documentReference.update(Constants.KEY_AVAILABLE, 0);
}
#Override
protected void onResume() {
super.onResume();
documentReference.update(Constants.KEY_AVAILABLE, 1);
}
}
public class MainActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
preferenceManager = new PreferenceManager(getApplicationContext());
init();
loadUserDetails();
getToken();
setListeners();
listenConversations();
}
}
public class ChatActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityChatBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setListeners();
loadReceiverDetails();
init();
listenMessages();
}
#Override
protected void onResume() {
super.onResume();
listenAvailabilityOfReceiver();
}
}
Did fix it in a ugly way. I made variable that knows if the user is still in the app or not.
#Override
protected void onPause() {
super.onPause();
if (!stillInApp) {
DocumentReference documentReference;
PreferenceManager preferenceManager = new
PreferenceManager(getApplicationContext());
FirebaseFirestore database = FirebaseFirestore.getInstance();
documentReference = database.collection(Constants.KEY_COLLECTION_USERS)
.document(preferenceManager.getString(Constants.KEY_USER_ID));
documentReference.update(Constants.KEY_AVAILABLE, 0);
}
}
#Override
protected void onResume() {
super.onResume();
DocumentReference documentReference;
PreferenceManager preferenceManager = new
PreferenceManager(getApplicationContext());
FirebaseFirestore database = FirebaseFirestore.getInstance();
documentReference = database.collection(Constants.KEY_COLLECTION_USERS)
.document(preferenceManager.getString(Constants.KEY_USER_ID));
documentReference.update(Constants.KEY_AVAILABLE, 1);
stillInApp = false;
listenAvailabilityOfReceiver();
}

Is there anyway to use switchCompat without resetting while running app in java, Android?

I am having Stopwatch app.
I have Switchcompat for different backgrounds on the main layout.
When I tap the switch while running the time, it is reset to 00:00:00.
Is there any way to use the switch without resetting the timer?
Here are some parts of the code.
MainActivity
SwitchCompat switchCompat;
SharedPreferences sharedPreferences = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchCompat = findViewById(R.id.switchCompat);
sharedPreferences = getSharedPreferences("night", 0);
Boolean booleanValue = sharedPreferences.getBoolean("NightMode", false);
if (booleanValue) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
switchCompat.setChecked(true);
}
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
switchCompat.setChecked(true);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("NightMode", true);
editor.commit();
}else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
switchCompat.setChecked(false);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("NightMode", false);
editor.commit();
}
}
});
}
check out saving instance state pattern - store time value and re-store when Activity recreates
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("SwitchText", switchCompat.getText().toString());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchCompat = findViewById(R.id.switchCompat);
if (savedInstanceState != null) { // is null on first start
String switchText = savedInstanceState.getString("SwitchText");
// may be null when no value stored under given key
if (switchText != null) switchCompat.setText(switchText);
}
...
Activity gets recreated/restared because in onCheckedChanged you are calling AppCompatDelegate.setDefaultNightMode - this is forcing Activity to restart and apply new theme, and you have to write some additional code for saving previous state

sharedpreferences is not saving the text value

**
I am trying to save the text variable using Sharedpreferences. I saved the variable by this code. But when I click the button the saved variable will go back to 0. I want to start counting from the saved value. please help me
**int counter = 0;
public static final String SHARED_PREF="shared";
public static final String TEXT="text";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
counterView=findViewById(R.id.counterid);
Btn=findViewById(R.id.button1);
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
counterView.setText(Integer.toString(counter));
SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(TEXT,counterView.getText().toString());
editor.commit();
}
});
SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String tValue = sp.getString(TEXT,"");
counterView.setText(tValue);
}
}
Considering the informations you've provided I think you needed to give the counter the value stored in SharedPreferences, to continue the count from that, when the button was pressed again.
Try this:
int counter = 0;
Button adBtn;
TextView counterView;
public static final String SHARED_PREF="shared";
public static final String TEXT="text";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counterView=findViewById(R.id.counterid);
adBtn=findViewById(R.id.button1);
adBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences counterSp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String correctCounterValue = counterSp.getString(TEXT,"");
counter = Integer.valueOf(correctCounterValue);
counter++;
counterView.setText(Integer.toString(counter));
SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(TEXT,counterView.getText().toString());
editor.commit();
}
});
SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String tValue = sp.getString(TEXT,"");
counterView.setText(tValue);
}

App crashes when using Shared Preferences

Im making a simple app, which counts the clicks of a button and saves the integer with a Shared Preferences. I tried it with the following code, but the app crashes all the time, if I try to open "Singleplayer"
public class Singleplayer extends AppCompatActivity {
private int sp1;
private int record;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singleplayer);
final Button button1 = (Button) findViewById(R.id.buttonspieler1);
final TextView lbl1 = (TextView)findViewById(R.id.lblspieler1);
final TextView lbl2 = (TextView)findViewById(R.id.lblrekord);
SharedPreferences data_record = getSharedPreferences("savegame", 0);
record = data_record.getInt("myKey1", 0);
lbl2.setText(String.valueOf(record));
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(final View v)
{
if(sp1< record) {
sp1++;
lbl1.setText(String.valueOf(sp1));
}
else if(sp1>= record)
{
sp1++;
record++;
lbl1.setText(String.valueOf(sp1));
lbl2.setText(String.valueOf(record));
}
}
});
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences data_record = getSharedPreferences("savegame", 0);
SharedPreferences.Editor editor = data_record.edit();
editor.putString("myKey1", String.valueOf(record));
editor.commit();
}
}
you are using sharedPrefrence in your onStop() so you will face many issue here, i suggest to use it at the end of click method
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(final View v)
{
if(sp1< record) {
sp1++;
lbl1.setText(String.valueOf(sp1));
}
else if(sp1>= record)
{
sp1++;
record++;
lbl1.setText(String.valueOf(sp1));
lbl2.setText(String.valueOf(record));
}
SharedPreferences data_record = getSharedPreferences("savegame", 0);
SharedPreferences.Editor editor = data_record.edit();
editor.putString("myKey1", String.valueOf(record));
editor.commit();
}
});
so why the app crash, because the sharedPref dosen't carry any value it's null
please check this

Get text from EditTextPreference and save it

I am trying to build a settings menu, but I'm having some troubles...
I cant get the text from EditTextPreference
I cant insert it on my sharedPreferences file
Can I have some help?
Prefs Class
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences.Editor editor = sharedPreferences.edit();
contact1 = (EditTextPreference) findPreference("contact1");
editor.putString("contact1", String.valueOf(contact1)).commit();
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
Prefs XML
<?xml version="1.0" encoding="utf-8"?>
<EditTextPreference
android:title="Contact 1"
android:key="#+id/contact1"
android:summary="Enter your contact">
</EditTextPreference>
<EditTextPreference
android:title="Contact 2"
android:key="#+id/contact2"
android:summary="Enter your contact">
</EditTextPreference>
Get data on main activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
number1 = settings.getString("contact1", "");
number2 = settings.getString("contact2", "");
contact1 = "tel: " + number1;
contact2 = "tel: " + number2;
use these way...
public class AdvancePreferenceExample extends PreferenceActivity implements OnSharedPreferenceChangeListener{
private static final String KEY_EDIT_TEXT_PREFERENCE = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
#Override
protected void onResume(){
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
updatePreference(KEY_EDIT_TEXT_PREFERENCE);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
updatePreference(key);
}
private void updatePreference(String key){
if (key.equals(KEY_EDIT_TEXT_PREFERENCE)){
Preference preference = findPreference(key);
if (preference instanceof EditTextPreference){
EditTextPreference editTextPreference = (EditTextPreference)preference;
if (editTextPreference.getText().trim().length() > 0){
editTextPreference.setSummary("Entered Name is " + editTextPreference.getText());
}else{
editTextPreference.setSummary("Enter Your Name");
}
}
}
}
}
here is sample

Categories

Resources