android: OnSharedPreferenceChangeListener for all activities - android

I'm using OnSharedPreferenceChangeListener in my main activity:
private SharedPreferences settings;
private OnSharedPreferenceChangeListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settings = PreferenceManager.getDefaultSharedPreferences(this);
listener = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {
MainActivity.this.refreshDisplay(null);
}
};
settings.registerOnSharedPreferenceChangeListener(listener);
}
public void refreshDisplay(View view){
//code
}
this way I should implement this listener inside all of my activities. because of I've menu in my action bar called settings. I want to know Is there any generic way(defining that listener inside a class and call it in other activities) to do that?
Thanks in advanced.

Create a SharedPrefsListenerActivity Class which extends Activity.
Add the listener inside SharedPrefsListenerActivity.
Make sure all other activities extend SharedPrefsListenerActivity.

Create BaseActivity implementing the listener (OnSharedPreferenceChangeListener())
Use BaseActivity (YourActivity extends BaseActivity)

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.

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());

Android PrefernceFragment implements OnPreferenceClickListener never invoked on clicks

I'm trying to implement OnPreferenceClickListener over PrefernceFragment and it seems like the onPreferenceClick() is never called.
I have another PrefernceFragment implementing OnSharedPreferenceChangeListener and it works just fine.
Is this a bug of the OS ? is the OnPreferenceClickListener not supposed to be supported for PrefernceFragment ?
If there is no need to register the fragment as listener as I read, then I really think my code is correct.
public class myClass extends PreferenceFragment implements OnPreferenceClickListener {
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(com.XX.ZZ.R.xml.YY);
}
#Override
public boolean onPreferenceClick(Preference preference) {
// never called.
}
}
PreferenceFragment doesn't have a onPreferenceClick() method. There is really no need to listen for click events since the Android fragment takes care of writing the preference values into memory. If you really need to watch for a click event, you can use findPreference(CharSequence key) to find each of the Preferences you want to watch and then call setOnPreferenceClickListener(this) on those.
You must set preferenceClickListener on your preference.
public class myClass extends PreferenceFragment implements OnPreferenceClickListener {
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(com.XX.ZZ.R.xml.YY);
Preference preference = findPreference("myPreference");
preference.setOnPreferenceClickListener(this);
}
#Override
public boolean onPreferenceClick(Preference preference) {
// never called.
}
UPDATE:
If you want to set onPreferenceClickListener to all preferences, you can do it like this:
public class myClass extends PreferenceFragment implements OnPreferenceClickListener {
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.menu.main);
Set<String> preferenceNames = getPreferenceManager().getSharedPreferences().getAll().keySet();
for (String prefName : preferenceNames) {
Preference preference = findPreference(prefName);
preference.setOnPreferenceClickListener(this);
}
}
#Override
public boolean onPreferenceClick(Preference preference) {
// or get preference.getKey() to select based on preference names
switch (preference.getOrder()) {
case 0:
return true;
case 1:
return true;
default:
return false;
}
}
}

Defining Interface inside activity

In my android application inside activity I am defining one interface like this :
public interface sideFilterInterface
{
public void changeFilters(int layoutId);
}
inside activity I use this interface like this
#Override
public void onCreate(Bundle savedInstanceState) {
mCallback = (sideFilterInterface) this;
mCallback.changeFilters(R.layout.filter_details);
}
I am implementing this interface in another fragment. when i tried this code it gives me error regarding casting here mCallback = (sideFilterInterface) this;
How to do this. Am I doing something wrong. Need help. Thank you.
The main thing is you are trying to cast your Activity into Listener if you are not implementing the Listener in your activity.
If you are calling the public void changeFilters(int layoutId) through the interface , the code will not execute as the method in the interface is abstract.You need to implement the listener in the activity and then do the code there . Something like :
public class YourActivity extends Activity implements sideFilterInterface{
#Override
public void onCreate(Bundle savedInstanceState) {
//some code
this.changeFilters(R.layout.filter_details);
}
#Override
public void changeFilters(int layoutId) {
//Implement here
}
}

How should onClick Listener by defined and instantiated for an Activity

My Activity has multiple lists so I have defined MyClickListener as below:
My question is how I should instantiate this class:
MyClickListener mMyClickListener = new MyClickListener();
Or maybe it is better to instantiate inside the onCreate(Bundle) and just define above. Whats considered the better way? I don't want too much in onCreate() its already full of stuff. Any thoughts on the declaration and instatiation? Whats the best way?
private class MyClickListener implements OnClickListener
{
#Override
public void onClick(View view) {
}
}
I use same kind of class mechanism as you mentioned in the question.
this is the way i use,
public class myActivity extends Activity
{
private MyListener listener = null;
private Button cmdButton = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cmdButton = (Button) findViewById(R.id.cmdButton);
cmdButton.setOnClickListener(getListener());
}
// method to fetch the listener object
private MyListener getListener()
{
if (listener == null)
{
listener = new MyListener();
}
return listener;
}
private class MyListener implements Button.OnClickListener
{
public void onClick(View v)
{
}
}
}
Why are you instantiating a listener like that in the first place? Just create a new one when you assign it to your listView.
listView.setOnClickListener( new MyListener());

Categories

Resources