inflating class (not found)android.support.v7.preference.PreferenceScreen - android

hi i have an issue with my app trying to add dark mod light mod option but keep getting this error
android.view.InflateException: Binary XML file line #1: Error inflating class (not found)android.support.v7.preference.PreferenceScreen
Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v7.preference.PreferenceScreen" on path: DexPathList[[zip file "/data/app/~~v5IN-tkiKWj2WITYkTkFBg==/com.example.healthyfood-qVhJKjjdKKHFACt5cLcuZw==/base.apk"],nativeLibraryDirectories=[/data/app/~~v5IN-tkiKWj2WITYkTkFBg==/com.example.healthyfood-qVhJKjjdKKHFACt5cLcuZw==/lib/x86, /system/lib, /system_ext/lib]]
settings activity
public class Settings_activity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener,
androidx.preference.Preference.SummaryProvider<androidx.preference.ListPreference> {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, new SettingsFragment())
.commit();
ActionBar supportActionBar = getSupportActionBar();
if (supportActionBar != null)
supportActionBar.setDisplayHomeAsUpEnabled(true);
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
String darkModeString = getString(R.string.dark_mode);
if (key != null && sharedPreferences != null)
if (key.equals(darkModeString)) {
final String[] darkModeValues = getResources().getStringArray(R.array.dark_mode_values);
// The apps theme is decided depending upon the saved preferences on app startup
String pref = PreferenceManager.getDefaultSharedPreferences(this)
.getString(getString(R.string.dark_mode), getString(R.string.dark_mode_def_value));
// Comparing to see which preference is selected and applying those theme settings
if (pref.equals(darkModeValues[0]))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
if (pref.equals(darkModeValues[1]))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
if (pref.equals(darkModeValues[2]))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
if (pref.equals(darkModeValues[3]))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
}
}
#Override
public CharSequence provideSummary(ListPreference preference) {
String key = preference.getKey();
if (key != null)
if (key.equals(getString(R.string.dark_mode)))
return preference.getEntry();
return null;
}
#Override
protected void onDestroy() {
super.onDestroy();
PreferenceManager.getDefaultSharedPreferences(this)
.unregisterOnSharedPreferenceChangeListener(this);
}
}
settings fragments
public class SettingsFragments extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences,rootKey);
}
}
gradle
implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
implementation 'androidx.preference:preference:1.1.1'
implementation 'androidx.appcompat:appcompat:1.2.0'

Related

androidx SwitchPreferenceCompat on Toolbar

I want to use SwitchPreferenceCompat on toolbar,
How Can I do that?
Thank you very much.
my codes like that:
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
final SwitchPreferenceCompat switchPreference = (SwitchPreferenceCompat) findPreference("sync");
if(switchPreference != null){
switchPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean isOn = (Boolean) newValue;
SwitchPreferenceCompat switchPreference = (SwitchPreferenceCompat) preference;
switchPreference.setChecked(isOn);
return false;
}
});
}
}
}
}
xml/root_preferences.xml
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
<SwitchPreferenceCompat
app:key="sync" />
</PreferenceScreen>
Is it possible?
I need your help
Sorry for my bad English.
Thank you very much.

App crashes when changes are made to preferences on resume

I'm having an issue with my preference page crashing my app. On the first visit, it acts as expected. But as soon as I revisit the page and try to change a switch, the app crashes. Here's what the XML looks like for my preferences:
xmlns:app="http://schemas.android.com/apk/res-auto">
<PreferenceCategory
android:gravity="left"
android:title="#string/description_title"
app:iconSpaceReserved="false">
<SwitchPreference
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:key="#string/pallet_pref_key"
android:title="#string/pallet_pref"
app:iconSpaceReserved="false" />
<SwitchPreference
android:key="#string/nose_pref_key"
android:title="#string/nose_pref"
app:iconSpaceReserved="false" />
<SwitchPreference
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:key="#string/finish_pref_key"
android:title="#string/finish_pref"
app:iconSpaceReserved="false" />
</PreferenceCategory>
</PreferenceScreen>
The Java looks like this:
import android.os.Bundle;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import androidx.preference.SwitchPreference;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
private SharedPreferences sharedPref;
private boolean pNose;
private boolean pPallet;
private boolean pFinish;
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
sharedPref.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
if(s.equals(getResources().getString(R.string.pallet_pref_key))) {
pPallet = sharedPreferences.getBoolean(s,false);
SwitchPreference pNose = findPreference(getResources().getString(R.string.nose_pref_key));
SwitchPreference pFinish = findPreference(getResources().getString(R.string.finish_pref_key));
if (pPallet) {
pNose.setChecked(false);
pFinish.setChecked(false);
}
}
else if(s.equals(getResources().getString(R.string.nose_pref_key))) {
pNose = sharedPreferences.getBoolean(s,false);
SwitchPreference pPallet = findPreference(getResources().getString(R.string.pallet_pref_key));
SwitchPreference pFinish = findPreference(getResources().getString(R.string.finish_pref_key));
if (pNose) {
pPallet.setChecked(false);
pFinish.setChecked(false);
}
}
else if(s.equals(getResources().getString(R.string.finish_pref_key))) {
pFinish = sharedPreferences.getBoolean(s,false);
SwitchPreference pPallet = findPreference(getResources().getString(R.string.pallet_pref_key));
SwitchPreference pNose = findPreference(getResources().getString(R.string.nose_pref_key));
if (pFinish) {
pNose.setChecked(false);
pPallet.setChecked(false);
}
}
}
});
}
}
}
So basically I'm just trying to make it so only one switch can be enabled at a time. I did some research and found a few threads on here that mentioned I should add this code:
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
I'm thinking that's probably the reason for the crash, but when I add that code below the "OnSharedPreferenceChangeListener() {" statement onResume() and onPause() are greyed out unless I hoist it to the top in which case the this keyword throws an error. Does anyone see what I'm doing wrong?
Here's the error that I get on the crash:

registerOnSharedPreferenceChangeListener is not called

neitherregisterOnSharedPreferenceChangeListener() is called nor onSharedPreferenceChanged() , i dunno why , i tried many solutions but nothing works
code for my PreferenceFragment
public class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle bundle, String s) {
addPreferencesFromResource(R.xml.settings);
}
SettingsActivity
public class SettingsActivity extends AppCompatActivity {
private Toolbar mSettingsToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mSettingsToolbar=findViewById(R.id.toolbarSettings);
setSupportActionBar(mSettingsToolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==android.R.id.home){
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
here is my method to setup sharedPreferenced
private void setupSharedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
autoplay = sharedPreferences.getBoolean(getString(R.string.autoplay_checkbox_key),getResources().getBoolean(R.bool.autoplay_checkbox_pref));
sharedPreferences.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
Toast.makeText(MainActivity.this,""+autoplay,Toast.LENGTH_SHORT).show();
onSharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals(R.string.autoplay_checkbox_key)){
autoplay=sharedPreferences.getBoolean(key,getResources().getBoolean(R.bool.autoplay_checkbox_pref));
Toast.makeText(MainActivity.this,""+autoplay,Toast.LENGTH_SHORT).show();
}
}
};
}
#Override
protected void onDestroy() {
super.onDestroy();
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
}
i searched a lot and used many solutions but still the same , so what should i do to make it work ? , is there any better solution to use ?!
thanks in advance
Can not see your complete codes, but below lines are valid:
private OnSharedPreferenceChangeListener listener; //listener is a class field instance
listener= new SharedPreferences.OnSharedPreferenceChangeListener() {//instantiate listener
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
//implementation goes here
}
};
prefs.registerOnSharedPreferenceChangeListener(listener); //then register it
finally it works , i just need to change my method to this
private void setupSharedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
autoplay = sharedPreferences.getBoolean(getString(R.string.autoplay_checkbox_key),getResources().getBoolean(R.bool.autoplay_checkbox_pref));
onSharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key==getString(R.string.autoplay_checkbox_key))
autoplay=PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean(getString(R.string.autoplay_checkbox_key)
,getResources().getBoolean(R.bool.autoplay_checkbox_pref));
}
};
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
}

Android SharedPreferences confusion

I am a beginner in android and I have a confusion regarding Shared Preferences implementation. My goal is to use a string where a user defines some text which will be used in MainFragment. Given the fact that user may change that string when application is running I need a listener as well. So according to one book so far I have a SettingsActivity and a SettingsFragment.
SettingsActivity so far:
public class SettingsActivity extends AppCompatActivity {
private SharedPreferences prefs;
private String stringIWantToSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getFragmentManager().beginTransaction().
replace(android.R.id.content, new SettingsFragment(), "settings_fragment").commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
protected void onResume() {
super.onResume();
stringIWantToSave = prefs.getString("stringIWantToSave", "myString");
}
}
SettingsFragment so far:
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
private SharedPreferences sharedPreferences;
private String stringIWantToSave;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
}
#Override
public void onPause() {
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
super.onPause();
}
#Override
public void onResume() {
super.onResume();
sharedPreferences.getString("stringIWantToSave", "myString");
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
}
My questions are:
• In which method and how should I save the changed value from the user?
• How can I implement the listener so that it will inform the MainFragment that the string has changed?
1. To achieve the SettingsActivity with EditTextPreference, first you have to create a PreferenceScreen that contains EditTextPreference.
preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference
android:key="pref_key_name"
android:title="Name"
android:summary="Enter your name here!"
android:dialogTitle="Enter name:">
</EditTextPreference>
</PreferenceScreen>
2. Create a Fragment extending PreferenceFragment. Do preference initialization and add OnSharedPreferenceChangeListener to update the UI when user input their name.
SettingsFragment.java:
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
// Preference Keys
public static final String KEY_PREF_NAME = "pref_key_name";
// Shared preference
SharedPreferences mSharedPreferences;
// Name preference
EditTextPreference mPreferenceName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// Shared preference
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
// Name preference
mPreferenceName = (EditTextPreference) getPreferenceScreen().findPreference(KEY_PREF_NAME);
// Initialize
initPreferences();
}
public void initPreferences()
{
// Name
String oldName = mSharedPreferences.getString(KEY_PREF_NAME, "Enter your name here!");
// Update view
mPreferenceName.setSummary(oldName);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPref, String key) {
if(key.equals(KEY_PREF_NAME))
{
// Name
String currentName = sharedPref.getString(key, "DEFAULT_VALUE");
// Update view
mPreferenceName.setSummary(currentName);
}
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
}
3. Finally, Create SettingsActivity and show SettingsFragment on its FrameLayout.
SettingsActivity.java:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// Settings Fragment
SettingsFragment settingsFragment = new SettingsFragment();
getFragmentManager().beginTransaction().replace(R.id.content, settingsFragment).commit();
}
#Override
protected void onResume() {
super.onResume();
}
}
HOW TO USE:
To use updated name from preference, get the name value from preference inside your activity or fragments onResume() method:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// Name
String name = sharedPreferences.getString(SettingsFragment.KEY_PREF_NAME, "DEFAULT_VALUE");
// Do something with name
................
........................
}
}
OUTPUT:
Hope this will help~

OnSharedPreferenceChangeListener callback is never executed

I've my main activity that starts a new activity (SearchResultsActivity).
I also have a settings menu.
I want my SearchResultsActivity to be notified every time there is a new/edited setting from the settings menu.
I'm implementing the OnSharedPreferenceChangeListener the interface on SearchResultsActivity and registering itself to listen to any modification in the settings but for some odd reason the callback is never executed.
Here's my SearchResultsActivity code
public class SearchResultsActivity extends BaseActivity implements SearchResultsFragment.RouteResultsFragmentCommunicator, SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = SearchResultsActivity.class.getSimpleName();
private FragmentManager mFragmentManager;
private SearchResultsFragment mSearchResultsFragment;
private RouteFragment mRouteFragment;
private SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
// Set the toolbar
activateToolbarWithHomeEnabled();
pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// Initialize the FragmentManager
mFragmentManager = getFragmentManager();
mSearchResultsFragment = (SearchResultsFragment) mFragmentManager.findFragmentById(R.id.searchRouteResultsFragment);
}
#Override
protected void onResume() {
super.onResume();
pref.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
protected void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
#Override
protected void onPause() {
pref.unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.d(TAG, "onSharedPreferenceChanged callback");
}
}
For sake of simplicity I've removed parts of the code that has nothing to do with my issue.
So my problem is, "onSharedPreferenceChanged callback" is never printed on the logcat when I make a change on any setting.
Just in case, here's my settings implementation:
public class MySettings extends BaseActivity {
private static final String TAG = MySettings.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pref_with_actionbar);
// Set the toolbar
activateToolbarWithHomeEnabled();
getFragmentManager().beginTransaction().replace(R.id.content_frame, new MyPreferenceFragment()).commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==android.R.id.home) {
finish();
return true;
}
else {
return super.onOptionsItemSelected(item);
}
}
}
And the fragment:
public class MyPreferenceFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = MyPreferenceFragment.class.getSimpleName();
private EditTextPreference mMaxRadius;
private SharedPreferences mSharedPreferences;
private CheckBoxPreference mCheckBoxPreference;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
mMaxRadius = (EditTextPreference) findPreference(getResources().getString(R.string.pref_radius_key));
mSharedPreferences = getPreferenceManager().getSharedPreferences();
String maxRadius = mSharedPreferences.getString(getResources().getString(R.string.pref_radius_key), "Unknown");
mMaxRadius.setSummary("Max Radius: " + maxRadius);
mCheckBoxPreference = (CheckBoxPreference) findPreference(getString(R.string.pref_order_list_key));
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equalsIgnoreCase(getResources().getString(R.string.pref_radius_key))) {
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(sharedPreferences.getString(key, "Unknown") + " km");
}
else if (key.equalsIgnoreCase(getString(R.string.pref_order_list_key))) {
Preference orderByPreference = findPreference(key);
}
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
}
Please note that on MyPreferenceFragment the onSharedPreferenceChanged is called as expected, eveytime there is a settings change the MyPreferenceFragment#onSharedPreferenceChanged is executed. But SearchResultsActivity#onSharedPreferenceChanged is never called.
Can someone explain me what is wrong with SearchResultsActivity#onSharedPreferenceChanged never being executed when I change something on the settings?
Register your listener in onCreate() and unregister in onDestroy(). When you start the preference activity your main activity is paused, and unregisters.

Categories

Resources