SwitchPreference.isEnabled() not detecting if enabled/disabled properly - android

I'm trying to use SwitchPreference and trying to detect it's state using isEnabled() method.
Here's the code (in SettingsActivity.java):
#Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
spChanged = new
SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// your stuff here
if (key.equals(KEY_ENABLE_F)) {
SwitchPreference fPref = (SwitchPreference) findPreference(key);
if (fPref.isEnabled()) {
Toast.makeText(getBaseContext(), "Enabled", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Disabled", Toast.LENGTH_SHORT).show();
}
}
}
};
}
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(spChanged);
}
#Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(spChanged);
}
The problem is that the Toast with text "Enabled" is showing up no matter if switch in 'ON' or 'OFF'.
What could be wrong here?

Whoops! I should have tried it before posting the question. Anyways, I solved the issue by changing:
fPref.isEnabled()
to this:
fPref.isChecked()

Related

Android activity lifecycle confused between calls of function

When I run this app I am getting "On Resume" first instead of "On start" even "On create" not showing up, please tell me why? and "On Restart" toast is not displaying but test is getting updated.
public class MainActivity extends AppCompatActivity {
public int test=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast t=Toast.makeText(getApplicationContext(),"On create",Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER_VERTICAL,20,20);
t.show();
}
#Override
protected void onRestart() {
super.onRestart();
Toast t=Toast.makeText(getApplicationContext(),"On restart",Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER_VERTICAL,20,20);
TextView num=(TextView) findViewById(R.id.textNum);
test++;
num.setText(String.valueOf(test));
t.show();
}
#Override
protected void onStart() {
super.onStart();
Toast.makeText(getApplicationContext(),"On start",Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
Toast t=Toast.makeText(getApplicationContext(),"On resume",Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER_VERTICAL,10,20);
t.show();
}
#Override
protected void onPause() {
super.onPause();
Toast t= Toast.makeText(getApplicationContext(),"On Pause",Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER_VERTICAL,20,20);
t.show();
}
#Override
protected void onStop() {
super.onStop();
Toast.makeText(getApplicationContext(),"On Stop",Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(),"On destroy",Toast.LENGTH_SHORT).show();
}
}
Using Toast as a debugging method is really bad idea. Use logging and look at your logcat. You will see that the methods get called in the order that they should. Just don't do this.

Doing something when returning to an Activity from Background

I want to execute a function only when returning to the Application from the background.
I have included the method in onResume, and this does it to a certain extent. Problem is since onResume is fired even on creating the Activity and when returning to the activity from another activity (Ex: From pressing the back button), and the function is executed there as well.
How to avoid this and execute the function only when returning from background?
Ps: My application already has multiple places using startActivity so changing to startActivityForResult is a tedious task.
Also all my Activities are extending from a common BaseAppCompactActivity class and it's where my method is located, so this will apply to the whole application.
Edit 2:
My BaseAppCompactActivity is as below with LifecycleObserver implemented now. This doesn't seem to work though.
public class BaseAppCompactActivity extends AppCompatActivity implements LifecycleObserver {
private String TAG = BaseAppCompactActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
#Override
protected void onPause() {
super.onPause();
stopService();
}
#Override
protected void onPostResume() {
super.onPostResume();
startService();
}
// #Override
// protected void onResume() {
// super.onResume();
//// updateLastAccessedDate();
// }
private void startService() {
startService(new Intent(this, BusinessCacheService.class));
}
private void stopService() {
stopService(new Intent(this, BusinessCacheService.class));
}
#OnLifecycleEvent(Lifecycle.Event.ON_START)
private void updateLastAccessedDate() {
//Do something
}
}
Although its a duplicate . Here is a Java implementation i am sharing for sake of help ..
public class MyApplication extends MultiDexApplication implements LifecycleObserver {
private boolean previouslyInBackground;
#Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
#OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void onAppBackgrounded() {
previouslyInBackground=true;
}
#OnLifecycleEvent(Lifecycle.Event.ON_START)
void onAppForegrounded() {
if(previouslyInBackground){
// Do your stuff Here
}
previouslyInBackground=false;
}
}
Add the Gradle dependency from Lifecycle-aware components Documentation
You can use startActivityForResult instead of startActivity.
Then you can catch the returning inside onActivityResult method.
first set a global boolean variable like this:-
boolean isPaused = false;
now set a methods in your activity :-
#Override
protected void onUserLeaveHint() {
isPaused = true;
super.onUserLeaveHint();
}
or in your onResume method:-
#Override
protected void onResume() {
if(isPaused){
isPaused = false;
}
super.onResume();
}
Do like this
add these variable in your main activity
public static boolean isAppWentToBg = true;
public static boolean isWindowFocused = false;
public static boolean isBackPressed = false;
and also add these methods
private void applicationWillEnterForeground() {
if (isAppWentToBg) {
isAppWentToBg = false;
// Toast.makeText(getApplicationContext(), "App is in foreground", Toast.LENGTH_SHORT).show();
}
}
public void applicationdidenterbackground() {
if (!isWindowFocused) {
isAppWentToBg = true;
// Toast.makeText(getApplicationContext(), "App is Going to Background", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
isBackPressed = true;
Log.d(TAG, "onBackPressed " + isBackPressed + "" + this.getLocalClassName());
super.onBackPressed();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
isWindowFocused = hasFocus;
if (isBackPressed && !hasFocus) {
isBackPressed = false;
isWindowFocused = true;
}
super.onWindowFocusChanged(hasFocus);
}
#Override
protected void onStart() {
Log.d(TAG, "onStart isAppWentToBg " + isAppWentToBg);
applicationWillEnterForeground();
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop ");
applicationdidenterbackground();
}
What I would suggest is create a new boolean variable which say if that is created for the first time in resume and work on it.
Boolean isForeGround = true;
#Override
public void onPause() {
super.onPause();
isForeGround = false;
}
#Override
public void onResume() {
super.onPause();
if(!isForeGround){
isForeGround = true;
// write your code here
}
}

Pointing to wrong UI from posted Runnable after screen orintation changes

This is my little test program. My problem is that from run() method I access to fields of wrong (old) Activity, which was destroyed after screen orientation changed. What's the way to handle this situation?
And, by the way, I must have my activity been recreated, because in real application I have different layouts for portrait and landscape modes!
public class MainActivity extends Activity {
private EditText edit;
private Button button;
private ProgressDialog progressDialog;
private boolean isLoginInProgress = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText) findViewById(R.id.edit_timer);
button = (Button) findViewById(R.id.btn_start);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
if (edit.getText().toString().length() == 0) throw new Exception();
long dTime = Long.parseLong(edit.getText().toString());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
MainActivity.this.isLoginInProgress = false;
progressDialog.dismiss();
}
}, dTime);
progressDialog.show();
isLoginInProgress = true;
} catch (Exception e) {
Toast.makeText(MainActivity.this, "bad time value", Toast.LENGTH_SHORT).show();
}
}
});
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("loading");
if (savedInstanceState != null) { // activity is restarted
isLoginInProgress = savedInstanceState.getBoolean("fl_login");
edit.setText(savedInstanceState.getString("edit"));
}
if (isLoginInProgress) { // Show dialog again
progressDialog.show();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("fl_login", isLoginInProgress);
outState.putString("edit", edit.getText().toString());
}
#Override
public void onDestroy(){
super.onDestroy();
progressDialog.dismiss();
}
}
You Can Use Database(SQLITE) for Storing Your Values..

proper handling AlertDialog when configration change

I saw many solution to maintain AlertDialog and most of them doesn't work probably when screen dim down. but this which i made works fine is there any other light weight way to do that , I want to use it inside Fragment from ACL .
public class Test extends Activity {
AlertDialog dialog;
boolean dialog_should_be_shown = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button btn = new Button(this);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
createDialog();
}
});
setContentView(btn);
if (savedInstanceState != null) {
dialog_should_be_shown = savedInstanceState.getBoolean("flag",
false);
}
}
private void createDialog() {
dialog = new AlertDialog.Builder(Test.this).setMessage("HEllo")
.setCancelable(true).create();
dialog.show();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("flag", dialog_should_be_shown);
}
#Override
protected void onResume() {
super.onResume();
if (dialog_should_be_shown) {
createDialog();
}
}
#Override
protected void onPause() {
super.onPause();
if (dialog != null && dialog.isShowing()) {
dialog_should_be_shown = true;
dialog.dismiss();
} else {
dialog_should_be_shown = false;
}
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_test, menu);
return true;
}
}
UPDATE :
I dont want to retain Framgnet in memory.
use DialogFragment instead, it is included on the support library and you can retain it using setRetainInstance(true),
http://developer.android.com/reference/android/app/DialogFragment.html

preference activity listener in android

I am using the following code for adding a listener in prefernceactivity. But its not working.
Please give a idea for this.
public class Preference extends PreferenceActivity implements OnSharedPreferenceChangeListener {
OnSharedPreferenceChangeListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
}
}
You have to register your listener first.
The best way is to register it in onResume and unregister in onPause :
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
prefs = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
protected void onResume() {
super.onResume();
prefs.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
prefs.unregisterOnSharedPreferenceChangeListener(this);
}

Categories

Resources