How to make global changes throughout the application on Android?

I have a settings menu in my application that controls the units used in all applications - metric or US units. Therefore, when the user selects one of them in the options in the menu, I want my application to use the selected units during display and calculations.

I plan to do this by storing the boolean value in sharedpreferences, and then check the boolean value every time I open the activity and then make the appropriate changes.

Is there a better way to do this?

thanks

+1
source share
3 answers

Yes, you can extend the Application Class and save your data there using Getter and setter.

To keep your data stored throughout the application.

public class SocketManager extends Application { private static SocketManager singleton; public int mBluetoothState; public synchronized static SocketManager getInstance(Context context) { if (null == singleton) { singleton = new SocketManager(); } return singleton; } public synchronized void setState(int state) { mBluetoothState = state; } public synchronized int getState() { return mBluetoothState; } } 

Access it, for example:

  SocketManager socketManager = SocketManager.getInstance(this); socketManager.setState(10); socketManager.getState(); 

Add your application to the Maanifest file as follows:

  <application android:name=".SocketManager" android:icon="@drawable/first_aid" android:label="@string/app_name" > <activity .... /> </application> 

Edit:

You must add your class name, which extends Application in the application tag , and not on the activity tag

For further repetition check this link.

+4
source

You can see the Android Storage options: http://developer.android.com/guide/topics/data/data-storage.html

However, it seems, for your case, SharedPreferences OK

+2
source

Only for booleans? If its only one action that calls SharedPreferences and assigns it, it would be nice.

If you have several actions in the application, you can call it once and load it into a static class and call it that way or a subclass of the Application class .

But even then it is just logical, and you should do everything that is convenient for you.

+1
source

All Articles