How onResume() working in android - android

Hi for me one doubt if I change any content or color of activity example, in activity1 I have one textview with data "apple" from shared preference. And I am clicking a button to start new activity2 there I am clicking one button to update the shared preference "apple" to "gova" I click back button of activity2 textview in activity should update. Is there any way to update without onResume() method or explain how onResume() working...?

onResume() is called every time your activity is shown to the user. Thus, if the user goes to another activity and then comes back to the first one, onResume() will be called. Your code should look like:
#Override
protected void onResume() {
super.onResume();
myTextView.setText(preferences.getString("myKey", "defaultValue");
}
If, for any reason, you'd prefer not to use onResume(), you can register a OnSharedPreferenceChangeListener, which will be called every time a shared pref value is changed.
Your first activity will include code that looks like this:
public class MainActivity extends AppCompatActivity {
SharedPreferences preferences;
SharedPreferences.OnSharedPreferenceChangeListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("myKey")) {
// update your textview
}
}
};
preferences.registerOnSharedPreferenceChangeListener(listener);
}
#Override
protected void onDestroy() {
super.onDestroy();
preferences.unregisterOnSharedPreferenceChangeListener(listener);
}
}

Just override onBackPressed method in second activity and in it set the value to shared preferences :
#Override
public void onBackPressed() {
// Set shared preference value
}

You should ideally use onBackPressed instead on onResume. Below is a code snippet on similar lines that should help
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Really go back?")
.setMessage("Are you sure you want to?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Activity1.super.onBackPressed();
//change sharedPreferences here
}
}).create().show();
}
Hope this helps

Related

Disable a button when an event occure in main activity

I have two activities named Main activity and Second Activity. Main activity has an event handler. I need to disable a button in second activity when an event occurs.
Main activity
public void myEventListener(int eventID){
switch (eventID) {
case : 0
// disable button of second activity here
break;
}
}
This is an easy one.
Use SharedPreference of changing data(boolean maybe) in MainAcitivity
Use SharedPreference.OnSharedPreferenceChangeListener in SecondActivity for listening to that specific data and changing button state at runtime in.
MainActivity.java
public class MainActivity extends AppCompatActivity {
SharedPreferences.Editor editor;
public void myEventListener(int eventID){
switch (eventID) {
case 0:
editor = getSharedPreferences("pref",MODE_PRIVATE).edit();
editor.putBoolean("event",true);
break;
}
}
}
SecondActivity
public class SecondActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
#Override
protected void onStart() {
super.onStart();
sharedPreferences=getSharedPreferences("pref",MODE_PRIVATE);
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onStop() {
super.onStop();
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals("event") && sharedPreferences.getBoolean(key,false))
{
//add your code to disable your button or any action you want
}
}
}
It's very simple to disable a button. Follow the below steps to achieve your problem.
Define a global boolean value as "false"
In onClickEvent override, the boolean value as "true".
Then check with the boolean value as follows
private boolean isClicked = false;
if(isClicked){
button.disabled(true);
} else {
button.disabled(false);
}
Please let me know if you have any issues while applying.
In you First Activity make Boolean static variable.
Example:
FirstActivity
create a Boolean static global variable
public static Boolean clicked = false;
onFirstActivity if Event occurs.
event occurred => clicked = true; otherwise it is false
SecondActivity
in second activity get the value to static boolean from FirstActivity
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (FirstActivity.clicked){
//Do Nothing
}else{
//Perform action
}
}
});
first make reference of second activity and set button visibility GONE or INVISIBLE It's Work
SeconActivity sa; //reference of second activity
public void myEventListener(int eventID){
switch (eventID) {
case : 0
sa.btnofsecondactivity.setVisibilty(View.GONE);
break;
}
}
You can go with LocalBroadCastManager.
in MainActivity wherever you want to trigger the method
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("event-occured"));
in SecondActivity register the LocalBroadcastManager and receive it.
public class SecondActivity extends AppCompatActivity {
private BroadcastReceiver mainActivityReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
mainActivityReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do whatever you want to do
Log.d("TAG", "broadcast received");
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(mainActivityReceiver, new IntentFilter("main-activity-initialized"));
}
#Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mainActivityReceiver);
}
Don't forget to unregister the listener in SecondActivity's onDestroy method. Taken reference from here.

Listening for Preference change

I am implementing Preferences according to Google tutorial. But I do not receive changes in my event listener. I realized that it is because I unregister the listener in onResume, like Google recommended. Did I miss something or is google advice wrong?
For proper lifecycle management in the activity, we recommend that you
register and unregister your
SharedPreferences.OnSharedPreferenceChangeListener during the
onResume() and onPause() callbacks, respectively:
public class MyActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener,
SharedPreferences.OnSharedPreferenceChangeListener {
public boolean onOptionsItemSelected(MenuItem item) {
case R.id.action_level: {
Intent intent = new Intent();
intent.setClass(this, GamePreferenceActivity.class);
startActivity(intent);
return true;
...
protected void onPause() {
Log.d(logTag, "onPause()");
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
sharedPref.unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
protected void onResume() {
Log.d(logTag, "onResume()");
super.onResume();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
sharedPref.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(MyPreferenceActivity.KEY_COMPLEXITY)) {
String value = sharedPreferences.getString(key, "EASY");
logic.setLevel(Level.valueOf(value));
restartGame(null);
}
}
My activity starts an intent with preferences activity.
public class GamePreferenceActivity extends Activity {
public static final String KEY_COMPLEXITY = "prefGameComplexity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new GamePreferenceFragment())
.commit();
PreferenceManager.setDefaultValues(this, R.xml.game_prefs, false);
}
}
public class GamePreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.game_prefs);
}
}
You need to call commit() or apply() to save changes in preferences.
Example:
// Access the default SharedPreferences
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(this);
// The SharedPreferences editor - must use commit() to submit changes
SharedPreferences.Editor editor = preferences.edit();
// Edit the saved preferences
editor.putString("UserName", "JaneDoe");
editor.putInt("UserAge", 22);
editor.commit(); //or editor.apply() -- Read below for difference between these two
Difference between commit() and apply():
apply() was added in 2.3, it commits without returning a boolean indicating success or failure.
commit() returns true if the save works, false otherwise.
apply() was added as the Android dev team noticed that almost no one took notice of the return value, so apply is faster as it is asynchronous.
This is the way how I register and unregister listener:
#Override
public void onResume() {
super.onResume();
// Register the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
Show us your onSharedPreferenceChanged, maybe you made mistake there.

How to make the android main activity to 'reload' from outside?

I have an android main activity showing some data which are taken from the database. Now I have a PreferenceActivity which is shown when the user wants to change some preference, or delete the content of the database. But if this is the case, how do I force a 'reload' or something of the main activity from a class outside the main activity?
Set a OnSharedPreferenceChangeListener listener in your MainActivity to automatically detect any changes in the preferences.
SharedPreferencesListener
MainActivity.java
public class MainActivity extends ... {
private SharedPreferences settings;
private SharedPreferences.OnSharedPreferenceChangeListener listener;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settings = PreferenceManager.getDefaultSharedPreferences(this);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// Refresh display
refreshDisplay();
}
};
// Register the listener on the SharedPreferences
settings.registerOnSharedPreferenceChangeListener(listener);
// Other code
}
public void refreshDisplay() {
// Retrieve entries from sharedPreferences & display them, e.g
String prefValue1 = settings.getString("key1", "default value 1");
String prefValue2 = settings.getString("key2", "default value 2");
// Update UI with these values
}
}
EDIT:
Here is how your PreferenceActivity should be:
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// R.xml.settings refers to the XML layout file named "settings"
// in your res/xml directory
addPreferencesFromResource(R.xml.settings);
}
}
If you just want to recharge an activity, you can do something like this:
finish();
startActivity(getIntent());

PreferenceActivity do something when preference are changed

I have preference xml and following code:
public class MainActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener
{
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Toast.makeText(getApplicationContext(), "DO SOMETHING", Toast.LENGTH_LONG).show();
}
}
I want to get notified over toast message, when one or more preferences are changed. I think upper code should work, but for some reason it doesn't.
I have for example CheckBoxPreference in my xml file. And when I check or uncheck CheckBox I want to be notified.
You have to set the listener like this for example:
PreferenceManager.getDefaultSharedPreferences(this).
registerOnSharedPreferenceChangeListener(this);
or, if You donĀ“t use the default shared preferences, You have to get Your prefs and then register them:
SharedPreferences preferences = getSharedPreferences("your_shared_prefs", Context.MODE_PRIVATE);
preferences.registerOnSharedPreferenceChangeListener(this);
You should register to listen to the shared preference changes:
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}

Check and Format preference string value before committing back to preferences

I have an EditTextPreference. After the user has edited the preference and pressed ok I then want to check the value for formatting errors before committing.
public class Preferences_Default extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.prefs_default);
}
}
#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);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
//This just calls a function to update the Pref Summary
Preference pref = findPreference(key);
initSummary(pref);
}
Where would I put the call to the function that checks the value and what is the code to re-commit the preference value if altered.
Friend, as you just specified, you have to check this in your code: you have to put it first line before it gets updated
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
//function to check
boolean b=check();
//This just calls a function to update the Pref Summary
if(b)
{
Preference pref = findPreference(key);
initSummary(pref);}
else{
//whatever you want to do show error
}
}

Categories

Resources