onSharedPreferenceChanged not working with Firebase job - android

I have a background service which request new data from the server if new data exists it updates the sharedpreferences in my firebase job there is notification show command that shows notification between 0, 20 sec.
Notiifcation is showing up in every 20 sec that means my job is working fine but my onSharedPreferenceChanged is not listening for the changes made for job service.
Is there anything any way to listen for the sharedPreferences changes from Job.
Home activity
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener
,SharedPreferences , SharedPreferences.OnSharedPreferenceChangeListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
testUtils.myjob(this);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
......
defaultSetup();
}
private void defaultSetup() {
SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(this);
shared.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(this);
shared .registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(this);
shared.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// if (key.equals(Preferences.LIST)) {
// Toast.makeText(this, "cool", Toast.LENGTH_LONG).show();
// }
// if (key.equals(Preferences.CHAT_LIST)) {
Log.e("Cool","cooooooooooooool");
Toast.makeText(this, "cool", Toast.LENGTH_LONG).show();
// }
}
#Override
public Map<String, ?> getAll() {
return null;
}
#Nullable
#Override
public String getString(String key, #Nullable String defValue) {
return null;
}
#Nullable
#Override
public Set<String> getStringSet(String key, #Nullable Set<String> defValues) {
return null;
}
#Override
public int getInt(String key, int defValue) {
return 0;
}
#Override
public long getLong(String key, long defValue) {
return 0;
}
#Override
public float getFloat(String key, float defValue) {
return 0;
}
#Override
public boolean getBoolean(String key, boolean defValue) {
return false;
}
#Override
public boolean contains(String key) {
return false;
}
#Override
public Editor edit() {
return null;
}
#Override
public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
}
#Override
public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
}
#Override
protected void onDestroy() {
super.onDestroy();
PreferenceManager.getDefaultSharedPreferences(this)
.unregisterOnSharedPreferenceChangeListener(this);
}
}
Firebase Job Service
public class FirebaseJobService extends com.firebase.jobdispatcher.JobService{
#Override
public boolean onStartJob(com.firebase.jobdispatcher.JobParameters job) {
String url = ApiUtil.getNewMessage();
final Context context = this;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray arr;
try {
arr = new JSONArray(response);
SharedPreferences pref1 = getSharedPreferences(Preferences.LIST, 0);
String chatList = pref1.getString(Preferences.CHAT_LIST, "[]");
arr = Utils.concatArray(arr, new JSONArray(chatList));
SharedPreferences.Editor editor = pref1.edit();
editor.putString(Preferences.CHAT_LIST, arr.toString());
editor.apply();
NotificationUtils.show(context);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestManager.getInstance(this).addToRequestQueue(stringRequest);
return false;
}
#Override
public boolean onStopJob(com.firebase.jobdispatcher.JobParameters job) {
return false;
}
}

Probably :
SharedPreferences pref1 = getSharedPreferences(Preferences.LIST, 0);
causing issue, because setting registerOnSharedPreferenceChangeListener for SharedPreferences which is returned by getDefaultSharedPreferences instead of by getSharedPreferences.
Note :
getDefaultSharedPreferences()- uses a default preference-file name
And
getSharedPreferences- retrieve and hold the contents of the preferences file 'name
So to get it work save Preferences.CHAT_LIST using getDefaultSharedPreferences or set registerOnSharedPreferenceChangeListener in Activity on instance which is returned by getSharedPreferences.

Related

I can't get api url from there to fragmentcategory?

I can't get from SharedPref to fragmentcategory.Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.kannada.newspaper.india.utils.SharedPref.getApiUrl()' on a null object reference I am getting this error i am new android devloper I have tried many times
Fragmentcategory
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view,savedInstanceState);
this.callbackCall = RestAdapter.createAPI(sharedPref.getApiUrl()).getHome(AppConfig.REST_API_KEY);
this.callbackCall.enqueue(new Callback<CallbackHome>() {
public void onResponse(Call<CallbackHome> call, Response<CallbackHome> response) {
CallbackHome responseHome = response.body();
if (responseHome == null || !responseHome.status.equals("ok")) {
return;
}
displayData(responseHome);
}
private void displayData(CallbackHome responseHome) {
displayCategory(responseHome.category);
}
public void onFailure(Call<CallbackHome> call, Throwable th) {
Log.e("onFailure", th.getMessage());
if (!call.isCanceled()) {
}
}
});
}
this Sharedpref
public class SharedPref {
private Context context;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";
public SharedPref(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences("setting", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public Boolean getIsDarkTheme() {
return sharedPreferences.getBoolean("theme", false);
}
public void setIsDarkTheme(Boolean isDarkTheme) {
editor.putBoolean("theme", isDarkTheme);
editor.apply();
}
public void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
public boolean isFirstTimeLaunch() {
return sharedPreferences.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}
public void setDefaultFilterRecipes(int i) {
editor.putInt("filter", i);
editor.apply();
}
public Integer getCurrentFilterRecipes() {
return sharedPreferences.getInt("filter", 0);
}
public void updateFilterRecipes(int position) {
editor.putInt("filter", position);
editor.apply();
}
public Integer getRecipesViewType() {
return sharedPreferences.getInt("recipes_list", RECIPES_GRID_2_COLUMN);
}
public void updateRecipesViewType(int position) {
editor.putInt("recipes_list", position);
editor.apply();
}
public void setYoutubeApiKey() {
editor.putInt("youtube_api_key", 0);
editor.apply();
}
public void saveConfig(String api_url, String application_id) {
editor.putString("api_url", api_url);
editor.putString("application_id", application_id);
editor.apply();
}
public String getApiUrl() {
return sharedPreferences.getString("api_url", "https://kalviaruvi.com/demoandroid/your_recipes_app/");
}
public String getApplicationId() {
return sharedPreferences.getString("application_id", "com.app.yourrecipesapp");
}
public void saveCredentials(String youtube_api_key, String fcm_notification_topic, String onesignal_app_id, String more_apps_url) {
editor.putString("youtube_api_key", youtube_api_key);
editor.putString("fcm_notification_topic", fcm_notification_topic);
editor.putString("onesignal_app_id", onesignal_app_id);
editor.putString("more_apps_url", more_apps_url);
editor.apply();
}
public String getYoutubeAPIKey() {
return sharedPreferences.getString("youtube_api_key", "0");
}
public String getFcmNotificationTopic() {
return sharedPreferences.getString("fcm_notification_topic", "your_recipes_app_topic");
}
public String getOneSignalAppId() {
return sharedPreferences.getString("onesignal_app_id", "0");
}
public String getMoreAppsUrl() {
return sharedPreferences.getString("more_apps_url", "https://play.google.com/store/apps/developer?id=Solodroid");
}
}

LiveData observer triggered after reloading fragment

My MainAcivity hosts 2 fragments, login and register. I have a LiveData observer on LoginFragment that observes user login live data, after which if user is authenticated MainMenuActivity intent will start. On main menu there's logout button that would start MainActivity and load LoginFragment.
But here's the problem, the observer on LoginFragment triggered immediately after loading the fragment, which straight up start MainMenuActivity intent again.
My LoginFragment:
public class LoginFragment extends Fragment {
public static LoginFragment newInstance(){
return new LoginFragment();
}
private LoginViewModel mLoginViewModel;
private LiveData<UserModelJSONPlaceholder> mUserModelLiveData;
private static final String TAG = "FragLogin";
private Button mBtnLogin;
private EditText mTxtUsername, mTxtPass;
private TextView mTxtRegister;
private CheckBox mCheckBoxRemember;
private TextView mTxtInvalid;
private Callbacks mCallbacks = null;
private ProgressBar mProgressBar;
private UserApiInterface mAPIInterface;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mPreferencesEditor;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login,container,false);
mBtnLogin = view.findViewById(R.id.btnLogin_login);
mTxtUsername = view.findViewById(R.id.txtUsername);
mTxtPass = view.findViewById(R.id.txtPass);
mCheckBoxRemember = view.findViewById(R.id.checkBoxRememberMe);
mTxtRegister = view.findViewById(R.id.txtRegister_login);
mProgressBar = view.findViewById(R.id.progressBar);
mTxtInvalid = view.findViewById(R.id.txtInvalid);
mProgressBar.setVisibility(View.GONE);
mTxtInvalid.setVisibility(View.GONE);
mAPIInterface = APIClient.getClient().create(UserApiInterface.class);
mSharedPreferences = getContext().getSharedPreferences("login",Context.MODE_PRIVATE);
mPreferencesEditor = mSharedPreferences.edit();
setListener();
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLoginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);
mUserModelLiveData = mLoginViewModel.getUserModelLiveData();
//observer would be triggered right after loading fragment after logout
mUserModelLiveData.observe(this, new Observer<UserModelJSONPlaceholder>() {
#Override
public void onChanged(UserModelJSONPlaceholder userModel) {
Log.d(TAG, "onChanged: Observer: "+userModel.getResponse());
mProgressBar.setVisibility(View.GONE);
String loginAuth = userModel.getResponse();
if(loginAuth.equals("OK")){
mPreferencesEditor.putString("name",userModel.getUserModel().getName());
mCallbacks.login_goMainMenu(userModel.getUserModel().getName());
}else{
mTxtInvalid.setVisibility(View.VISIBLE);
}
}
});
}
private void doLogin(){
mProgressBar.setVisibility(View.VISIBLE);
final String username = mTxtUsername.getText().toString().trim();
final String password = mTxtPass.getText().toString().trim();
mLoginViewModel.authLogin(username,password);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mCallbacks = (Callbacks) context;
}
private void setListener(){
mBtnLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
doLogin();
}
});
mTxtRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallbacks.login_goRegister();
}
});
mCheckBoxRemember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.isChecked()){
mPreferencesEditor.putBoolean("rememberMe", true).apply();
Log.d(TAG, "onCheckedChanged: Checked");
}else{
mPreferencesEditor.putBoolean("rememberMe", false).apply();
Log.d(TAG, "onCheckedChanged: Unchecked");
}
}
});
}
public interface Callbacks{
void login_goMainMenu(String name);
void login_goRegister();
}
}
My MainMenuActivity:
public class MainMenuActivity extends AppCompatActivity {
private static final String ARG_NAME = "arg_name";
private Button mBtnEnterQ,mBtnCreateQ;
private TextView mTxtName;
private Toolbar mToolbar;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
mBtnEnterQ = findViewById(R.id.btnEnterQ);
mBtnCreateQ = findViewById(R.id.btnCreateQ);
mTxtName = findViewById(R.id.txtUsername);
mToolbar = findViewById(R.id.toolbar);
mSharedPreferences = getSharedPreferences("login",MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
setSupportActionBar(mToolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.itemLogout:
doLogout();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void doLogout(){
mEditor.remove("rememberMe");
mEditor.apply();
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
finish();
}
}
and here's my ViewModel and Repo for LoginFragment:
public class LoginViewModel extends ViewModel {
private static final String TAG = "LoginVM";
private UserRepository mUserRepository;
LiveData<UserModelJSONPlaceholder> mUserModelLiveData;
public LoginViewModel() {
mUserRepository = UserRepository.getInstance();
}
public void authLogin(String username, String password){
mUserRepository.authLogin(username,password);
}
public LiveData<UserModelJSONPlaceholder> getUserModelLiveData() {
return mUserRepository.getUserModelLiveData();
}
}
public class UserRepository {
private static UserRepository instance;
private static final String TAG = "RepoUser";
private UserApiInterface mUserApiInterface;
MutableLiveData<UserModelJSONPlaceholder> userModelLiveData;
public static UserRepository getInstance(){
if(instance==null){
instance=new UserRepository();
}
return instance;
}
private UserRepository(){
mUserApiInterface = APIClient.getClient().create(UserApiInterface.class);
Log.d(TAG, "UserRepository: repoInit");
}
public void authLogin(String username, String password){
Log.d(TAG, "authLogin: REQUEST INIT");
Log.d(TAG, "authLogin: SERVER: "+ CONFIG.SERVER);
mUserApiInterface.getUser(username,password).enqueue(new Callback<UserModelJSONPlaceholder>() {
#Override
public void onResponse(Call<UserModelJSONPlaceholder> call, Response<UserModelJSONPlaceholder> response) {
if(response.isSuccessful()){
UserModelJSONPlaceholder r = response.body();
userModelLiveData.postValue(response.body());
}else{
Log.d(TAG, "onResponse: FAILED. "+response.errorBody());
}
}
#Override
public void onFailure(Call<UserModelJSONPlaceholder> call, Throwable t) {
Log.d(TAG, "onFailure: "+t.getMessage());
}
});
}
public LiveData<UserModelJSONPlaceholder> getUserModelLiveData() {
if(userModelLiveData == null)
userModelLiveData = new MutableLiveData<>();
return userModelLiveData;
}
}
Your problems is you make UserRepository is Singleton instance and always keep value of userModelLiveData easy way to fix it change method to this
public LiveData<UserModelJSONPlaceholder> getUserModelLiveData() {
userModelLiveData = new MutableLiveData<>();
return userModelLiveData;
}

My SharedPreferences is null . This is the error SharedPreferences.edit() is a null object references [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm using Model View Presenter in my application, and i try to save a value token in SharedPreferences. But, I got the SharedPreferences null, the error is SharedPreferences.edit() is a null object references. Please, help me to solve this. Thank you
This is my Fragment
public class SignUpFragment extends BaseFragment {
#NotEmpty(messageResId = R.string.rules_no_empty)
#Bind(R.id.Name)
EditText etName;
#NotEmpty(messageResId = R.string.rules_no_empty)
#Bind(R.id.email)
EditText etEmail;
#NotEmpty(messageResId = R.string.rules_no_empty)
#Bind(R.id.phone)
EditText etPhone;
#Bind(R.id.btnSignUp)
Button btnSignUp;
public static final String TAG = SignUpFragment.class.getSimpleName();
private SignUpPresenter presenter;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
public static void showFragment(BaseActivity sourceActivity) {
if (!sourceActivity.isFragmentNotNull(TAG)) {
FragmentTransaction fragmentTransaction = sourceActivity.getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_question, new SignUpFragment(), TAG);
fragmentTransaction.commit();
}
}
#Override
protected int getLayout() {
return R.layout.activity_sign_up;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
presenter = new SignUpPresenter(this);
sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initview();
}
#Override
public void onResume() {
super.onResume();
}
private void initview (){
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!validate()) {
onSignupFailed();
return;
} else {
presenter.signup();
}
}
});
}
#Override
public void onValidationSucceeded() {
super.onValidationSucceeded();
presenter.signup();
}
public void onSignupFailed() {
Toast.makeText(getContext(), "Login failed", Toast.LENGTH_LONG).show();
btnSignUp.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String name = etName.getText().toString();
String email = etEmail.getText().toString();
String password = etPhone.getText().toString();
if (name.isEmpty() || name.length() < 3) {
etName.setError("at least 3 characters");
valid = false;
} else {
etName.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
etEmail.setError("enter a valid email address");
valid = false;
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
etPhone.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
etPhone.setError(null);
}
return valid;
}
public void gotoQuestionActivity(String email, String name, String phone) {
QuestionActivity.startActivity((BaseActivity) getActivity(), email, name, phone);
getActivity().finish();
}
}
and this my Presenter
public class SignUpPresenter {
private SignUpFragment fragment;
public String token = "token";
SharedPreferences sharedpreferences;
private Context mContext;
public static final String MyPREFERENCES = "MyPrefs" ;
public SignUpPresenter(SignUpFragment fragment) {
this.fragment = fragment;
}
public SignUpRequest constructSignUpRequest() {
SignUpRequest request = new SignUpRequest();
request.setName(getAndTrimValueFromEditText(fragment.etName));
request.setEmail(getAndTrimValueFromEditText(fragment.etEmail));
request.setMobile(getAndTrimValueFromEditText(fragment.etPhone));
return request;
}
private String getAndTrimValueFromEditText(EditText e) {
return e.getText().toString().trim();
}
public SharedPreferences getSharedPreferences() {
return sharedpreferences;
}
void signup (){
this.register(constructSignUpRequest());
}
void register(final SignUpRequest signUpRequest) {
fragment.showProgressDialog(fragment.loading);
fragment.getApi().regsiterCustomer(constructSignUpRequest())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<GenericResponse>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
fragment.dismissProgressDialog();
Timber.e(e.getLocalizedMessage());
Toast.makeText(fragment.getContext(), fragment.connectionError, Toast.LENGTH_SHORT).show();
}
#Override
public void onNext(GenericResponse signUpResponse) {
fragment.dismissProgressDialog();
Toast.makeText(fragment.getContext(), signUpResponse.getInfo(), Toast.LENGTH_SHORT).show();
if (signUpResponse.getCode() == fragment.successCode) {
/*fragment.gotoActivationCodeActivity(SignUpRequest.getEmail(), SignUpRequest.get());*/
fragment.gotoQuestionActivity(signUpRequest.getEmail(), signUpRequest.getName(), signUpRequest.getMobile());
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(token, signUpResponse.getData().getToken());
editor.commit();
}
}
});
}
}
You missed to define the sharedpreferences in the second class like this, the way you did in the first class.
sharedpreferences = fragment.getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Place this line, just above the code,
SharedPreferences.Editor editor = sharedpreferences.edit();
inside onNext()

Shared preferences is working on Lollipop and marshmallow but not in kitkat

When i kill the app shared preferences key value is removing, I added token value in shared preferences, when i run in Lolipop, its fine but not working in kitkat, I tried a lot but not got satisfying result.
SplashActivity.java
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
String authToken = new DevicePreferences().getString(SplashActivity.this, Global_Variables.AUTH_TOKEN, "");
if (new DevicePreferences().getString(SplashActivity.this, Global_Variables.AUTH_TOKEN, "").equalsIgnoreCase("")) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashActivity.this, WelcomeActivity.class);
startActivity(i);
finish();
}
}, 3000);
} else {
Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
}
}
DevicePreferences.java
public class DevicePreferences {
public SharedPreferences get(Context context) {
return context.getSharedPreferences(Global_Variables.PREF_FILE_NAME, Context.MODE_PRIVATE);
}
public void addKey(Context context, String key, String value) {
SharedPreferences settings = get(context);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
editor.commit();
}
public String getString(Context context, String key, String defValue) {
SharedPreferences prefs = get(context);
return prefs.getString(key, defValue);
}
}
Global_Variables.java
public class Global_Variables {
public static final String PREF_FILE_NAME = "GFresh";
public static String AUTH_TOKEN = "auth_token";
}

onPreferenceClick and OnPreferenceClickListener

I'm attempting to evaluate my preferences in my java code in order to enable/disable other options it they chose not to do other options... So far i'm trying to only implement the OnPreferenceClickListener however i never see the toast from the changes. What am i doing wrong? There seem to be alot of other questions like this but i cannot see my error in reference to them.
public class UserSettingActivity extends PreferenceActivity implements OnPreferenceClickListener{
SharedPreferences mPreferences;
Boolean frequency;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
#Override
public boolean onPreferenceClick(Preference preference) {
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
frequency = mPreferences.getBoolean("frequency", true);
Context context = getApplicationContext();
Toast.makeText(context, "Hello toast 0!", Toast.LENGTH_LONG).show();
if (!frequency) {
Context context2 = getApplicationContext();
Toast.makeText(context2, "Hello toast 1!", Toast.LENGTH_LONG).show();
} else if (preference.getKey().equals("schedulestop")) {
} else if (preference.getKey().equals("priority")) {
} else {
Context context3 = getApplicationContext();
Toast.makeText(context3, "Hello toast 0!", Toast.LENGTH_LONG).show();
}
return false;
}
}
You have to register for PreferenceClickListener each individual preference
somePreference.setOnPreferenceClickListener(this);
or you can use getSharedPreferences().registerOnSharedPreferenceChangeListener for all preferences.
public class UserSettingActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener{
SharedPreferences mPreferences;
Boolean frequency;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
#SuppressWarnings("deprecation")
#Override
protected void onPause()
{
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
protected void onResume()
{
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("schedulestop")) {
// do something
}
else if (key.equals(......
}
}
first implement "OnSharedPreferenceChangeListener"
PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener
Then
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
settings.registerOnSharedPreferenceChangeListener(this);
}
THEN
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
switch (key) {
case "pref_key_auto_delete":
boolean notificationStatus = SP.getBoolean(key, false);
Log.d("stat", String.valueOf(notificationStatus));
break;
case "pref_key_notification_list":
String downloadType = SP.getString(key, "n/a");
Log.d("stat", String.valueOf(downloadType));
break;
}

Categories

Resources