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);
}
Related
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()
So I’ve got this Activity with a doSomething() method. This method must be called when the user leaves the Activity and resumes after a while. This code works fine. The problem is: When the user rotates the phone (orientation change), the method is also called. I don’t want the method to be called on Orientation Change. Here’s my Activity code
public class MainActivity extends AppCompatActivity
{
private static boolean callMethod=true;
#Override
protected void onResume() {
super.onResume();
if(callMethod)
doSomething();
}
#Override
protected void onPause() {
super.onPause();
callMethod=true;
}
private void doSomething()
{
Log.i(“doSomething()”,”Did something.”);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(callMethod)
doSomething();
}
}
Thanks in advance!
From API 13 you can use configChanges in manifest.
Add the following to the manifest. This prevents recreation of the activity on screen rotation:
<activity android:name=".Activity_name"
android:configChanges="orientation|keyboardHidden">
One note is after this, you should handle screen orientation change yourself. you should override the following function in your activity for that:
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
setContentView(R.layout.layout_landscape);
}
else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.layout);
}
}
I see in your comment that you added the isChangingConfigurations() flag, which should do the trick, but you should persist that state rather than making it a static variable. Otherwise, if your process is killed when your app goes to the background you'll lose that state.
public class MainActivity extends AppCompatActivity {
private static final String KEY_CALL_METHOD = "key_call_method";
private boolean callMethod = true;
#Override
protected void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.activity_main);
if (savedState != null) {
callMethod = savedState.getBoolean(KEY_CALL_METHOD);
}
}
#Override
protected void onResume() {
super.onResume();
if (callMethod) {
doSomething();
}
}
#Override
protected void onPause() {
super.onPause();
if (!isChangingConfigurations()) {
callMethod = true;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(KEY_CALL_METHOD, callMethod);
}
private void doSomething() {
Log.i("doSomething()", "Did something.");
}
}
Guys I am stuck in a problem with these two methods:-
When I change the orientation of device and set the text in edit text after retriving the text from bundle,it does't work.But the same code is working in onrestoreStoreInstante method.
Please have a look at my code:-
public class LifeCycleActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText user;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
user=(EditText)findViewById(R.id.et_user);
if(savedInstanceState!=null){
String s =savedInstanceState.get("Key").toString();
user=(EditText)findViewById(R.id.et_user);
user.setText(savedInstanceState.get("Key").toString());
Toast.makeText(this, s,Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "onCreate",Toast.LENGTH_SHORT).show();
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(this);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Toast.makeText(this, "onSaveInstanceState",Toast.LENGTH_SHORT).show();
outState.putString("Key", "Deepak");
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//String s =savedInstanceState.get("Key").toString();
//user.setText(s);
Toast.makeText(this, "onRestoreInstanceState",Toast.LENGTH_SHORT).show();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(this, "onStart",Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(this, "onResume",Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(this, "onPause",Toast.LENGTH_SHORT).show();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Toast.makeText(this, "onStop",Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "onDEstroy",Toast.LENGTH_SHORT).show();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Toast.makeText(this, "onRestart",Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent(LifeCycleActivity.this,SecondActivity.class));
}
}
when I set the text in edit text in oncreate method after getting the value from Bundle,it doesn't work.But the same code works in onRestoreInstanceState() method.
According to me , it should work for oncreate also as we can get the Bundle class object there.
Please help me to sort out this problem..
EditText and most of other views have their own methods to save/restore their own data. So in general it's not necessary to save/restore them on your code.
You can see this here on the Android TextView source code (remember that EditText extends from TextView) on line 3546:
if (ss.text != null) {
setText(ss.text);
}
so the reason you can't set it onCreate and can do it onRestoreInstanceState it's because during your activity super.onRestoreInstanceState(savedInstanceState) the activity calls the EditText.onRestoreInstanceState and the EditText restore it self to the previous value.
You can see it happening on the Activity source code on line 940
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (mWindow != null) {
Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
if (windowState != null) {
mWindow.restoreHierarchyState(windowState);
}
}
}
hope it helps.
Overview
onSaveInstanceState() is used to put the data to bundle
onRestoreInstanceState() is used to set the data available in
bundle to your activity
So do as follows:
i Guess until the activity is created onorientation change the
bundle is not available, that's way you are not able to retrieve it
in oncreate
Let the activity create in oncreate
Then restore the instance in onRestoreInstanceState
Hope this helps !
I'm an Android newbie. I'm writing an app to trace the Activity lifecycle using Log statements. I want to kill my app in order to see the onDestroy() event being called. I've added a button that calls finish to do this, but I've not been able to terminate the app. I've also tried System.exit(0), but my app won't terminate. What am I doing wrong?
public class MainActivity extends Activity {
private static final String LOG_DISPLAY = "DEBUG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(LOG_DISPLAY, "onCreate called");
}
#Override
protected void onPause() {
super.onPause();
Log.d(LOG_DISPLAY, "onPause called");
}
#Override
protected void onResume() {
super.onResume();
Log.d(LOG_DISPLAY, "onResume called");
}
#Override
protected void onStop() {
super.onStop();
Log.d(LOG_DISPLAY, "onStop called");
}
#Override
protected void onStart() {
super.onStop();
Log.d(LOG_DISPLAY, "onStart called");
}
#Override
protected void onRestart() {
super.onStop();
Log.d(LOG_DISPLAY, "onRestart called");
}
public void addListenerOnButton() {
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
//System.exit(0);
}
});
}
}
You must override onDestroy in order to check if it is called, and call your addListenerOnButton method too:
Try with this:
public class MainActivity extends Activity {
private static final String LOG_DISPLAY = "DEBUG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(LOG_DISPLAY, "onCreate called");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(LOG_DISPLAY, "onDestroy called");
}
#Override
protected void onPause() {
super.onPause();
Log.d(LOG_DISPLAY, "onPause called");
}
#Override
protected void onResume() {
super.onResume();
Log.d(LOG_DISPLAY, "onResume called");
}
#Override
protected void onStop() {
super.onStop();
Log.d(LOG_DISPLAY, "onStop called");
}
#Override
protected void onStart() {
super.onStop();
Log.d(LOG_DISPLAY, "onStart called");
}
#Override
protected void onRestart() {
super.onStop();
Log.d(LOG_DISPLAY, "onRestart called");
}
public void addListenerOnButton() {
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
MainActivity.this.finish();
//System.exit(0);
}
});
}
}
First add missing onDestroy implementation to show you logs :
#Override
protected void onDestroy() {
Log.d(LOG_DISPLAY, "onDestroy called");
super.onDestroy();
}
Then simply open activity and exit it with hardware back button. You will see onDestroy logs.
You will have same effect calling finish() programmatically as well, just dont forget to place call to your addListenerOnButton somewhere within onCreate
i have a set of words in an array and i am displaying them one by one like a slideshow using Handlers. the problem is when i switch mode (land to portrait or vice verse) it starts again from the first word.
i know i have to save the variables in onSaveInstanceState() but the problem is the value of the variable 'i' which i want to save is in a different method (updateUI()).
this is my activity:
public class WatSlideShow extends Activity {
RefreshHandler refreshHandler = new RefreshHandler();
TextView watwords;
int i = 0;
String wat1[] = { "SICK", "FUTURE", "PROBLEM", "DECEIVE", "SUFFER",
"FAITH", "PROTECT", "SUICIDE", "STEP", "WNJOY", "FAIL" };
class RefreshHandler extends Handler {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
WatSlideShow.this.updateUI();
}
public void sleep(long delayMillis) {
this.removeMessages(0);
sendMessageDelayed(obtainMessage(0), delayMillis);
}
};
public void updateUI() {
if (i < wat1.length) {
watwords.setText(wat1[i]);
refreshHandler.sleep(3000);
i++;
}
}
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.watslideshow);
updateUI();
}
how should i save the value of 'i' (which is the word being displayed) in onSaveInstanceState().
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
int currentI = ? // how to get value of 'i' here
outstate.putInt("Myint", currentI)
}
and then i can use this in oncreate():
int myInt = savedInstanceState.getInt("MyInt");
sorry but my java concepts not strong yet. still learning.
You declared i as a class member variable of your activty, you can access it anywhere in your activity.
protected void onSaveInstanceState(Bundle outState) {
outstate.putInt("Myint", i)
super.onSaveInstanceState(outState);
}
Update
public class MainActivity extends Activity {
private String[] wordList = { "SICK", "FUTURE", "PROBLEM", "DECEIVE", "SUFFER","FAITH", "PROTECT", "SUICIDE", "STEP", "WNJOY", "FAIL" };
private TextView tv;
private int current = 0;
private Handler handler = new Handler();
public void updateUI() {
current++;
if (current == wordList.length) current=0;
tv.setText(wordList[current]);
handler.postDelayed(new Runnable() {
#Override
public void run() {
updateUI();
}
}, 3000);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState!=null) current = savedInstanceState.getInt("current");
tv = (TextView) findViewById(R.id.tv);
updateUI();
}
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("current", current);
super.onSaveInstanceState(outState);
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacksAndMessages(null);
}
Lets assume your textview is named as MyTextView in your layout xml file. Your activity will need the following:
private TextView mTextView;
private static final String KEY_TEXT_VALUE = "textValue";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = (TextView) findViewById(R.id.main);
if (savedInstanceState != null) {
String savedText = savedInstanceState.getString(KEY_TEXT_VALUE);
mTextView.setText(savedText);
}
#Override
protected void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_TEXT_VALUE, mTextView.getText());
}
For more detail
see this
protected void onSaveInstanceState(Bundle bundle) {
bundle.putInt("Myint", i)
super.onSaveInstanceState(bundle);
}