I have a simple problem. I cannot find a way to use sharedPreferences between my Activities. One of them is a Settingsactivity and the other one is my MainActivity. I would like to save variables (show_idle_dialog and selected_currency) in the SettingsActivity to sharedPreferences and load it in the MainActivity. With my current code the MainActivity always loads the defValue.
SettingsActivity:
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
public class SettingsActivity extends AppCompatActivity {
public static final String KEY_PREF_CHECK_BOX_SHOW_IDLE_DIALOG = "check_box_show_idle_dialog";
public static final String KEY_PREF_CURRENCY_DROPDOWN = "currency_dropdown";
Boolean show_idle_dialog;
String selected_currency;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
show_idle_dialog = sharedPreferences.getBoolean(SettingsActivity.KEY_PREF_CHECK_BOX_SHOW_IDLE_DIALOG, true);
selected_currency = sharedPreferences.getString(SettingsActivity.KEY_PREF_CURRENCY_DROPDOWN, "currency_eur");
Log.i("abc", "put " + show_idle_dialog);
Log.i("abc", "put " + selected_currency);
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
public static final String SHARED_PREFS = "sharedPrefs";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
PreferenceManager.setDefaultValues(this, R.xml.root_preferences, false);
}
@Override
public void onResume(){
loadData();
super.onResume();
}
public void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
show_idle_dialog = sharedPreferences.getBoolean(SettingsActivity.KEY_PREF_CHECK_BOX_SHOW_IDLE_DIALOG, false);
selected_currency = sharedPreferences.getString(SettingsActivity.KEY_PREF_CURRENCY_DROPDOWN, "currency_eur");
Log.i("abc", "got " + show_idle_dialog);
Log.i("abc", "got " + selected_currency);
}
I would be very happy if someone knows what I've done wrong.