How do I make global changes throughout my app in Android? - android

I have a settings menu in my app which controls the units used throughout the app - metric or US units. So when the user selects one of these in the options in the menu, I want my app to use the chosen units throughout in display and calculations.
I plan to do this by storing a boolean in sharedpreferences, then check the value of the boolean every time an activity is opened, and then make the appropriate changes.
Is there a better method to go about doing this?
Thanks

Yes you can extends Applications class and store your data over there using Getter and setter.
So that your data will be retained 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 in Activity like :
SocketManager socketManager = SocketManager.getInstance(this);
socketManager.setState(10);
socketManager.getState();
Add your Application to Maanifest file like this :
<application
android:name=".SocketManager"
android:icon="#drawable/first_aid"
android:label="#string/app_name" >
<activity .... />
</application>
Edit :
You should add your class name that extends Application into Application Tag not on Activity Tag
For further refrence check this link

You can have a look at Android Storage options: http://developer.android.com/guide/topics/data/data-storage.html
However, it seems like for your case SharedPreferences is OK

For just a boolean? If its just a single activity calling SharedPreferencesand assigning it would be fine.
If you have multiple activities in an application you could call it once and load it into a static class and call it that way or subclass the Application class.
But even then it's just a boolean and you should do whatever is most convenient for you.

Related

Is it necessary to declare Singleton to access a single object in my all activities?

I am building a menu from which the user can select items. They can edit their selections whenever necessary. The singleton would be a class containing the list of all selectable items. Whenever new activities are opened, the singleton would have the correct state of all items.
The reason I am asking this is because implementing Serializable creates a new instance (albeit almost identical) of the item.
Yes you could use a singleton for this. It would be something like:
public class MenuData {
private static MenuData instance;
private boolean isItemASelected;
public static MenuData getInstance() {
if (instance == null) {
instance = new MenuData();
}
return instance;
}
public boolean isItemASelected() {
return isItemASelected;
}
public void setItemASelected(boolean itemASelected) {
isItemASelected = itemASelected;
}
}
However I wouldn't recommend this. This data will only be around for as long as your Application is in memory. As soon as your app gets killed by Android all the variables will be cleared and the state will have been lost.
If your menu items are constant then I'd recommend using SharedPreferences to store the state. If they are dynamic then use the SQL database. This way the options are persisted even if your app gets killed.

Setting activity variables from different activity

I have some major variables in my main activity that I retrieve their values from internet once the user log in. after that, there are multiple activities that can alter these values in the database but this doesn't reflect in the current loaded values until the user log out/in. (the process where I retrieve data from internet)
what is the best way to update these values in main activity from activity 2 directly without logging out/in?
is there a way to set these variables without making intent and putting the new values in extra bundle? ( I need to change the values without returning back to the activity)
You can perhaps try putting the variables in a custom Application class as static members and then access them from anywhere through Application.xyzStaticMember(). Here's an example:
public class MyTestApp extends Application {
private static List<Int> testList;
public static void setList(List<Int> l) {
testList = l;
}
public static List<Int> getList() {
return testList;
}
}
Then access the members: MyTestApp.setList(null); or MyTestApp.getList();. Oh, and don't forget to use the class in the AndroidManifest.xml file!
<application android:name="com.example.MyTestApp"
/* ...more stuffs */ />

Keeping a session in all application life

I need to create a session and change it at times. In a specific activity should recover it and compare it to a different variable and modify the value of this session. I tried to create a class for this, but the change of activity, the value back to null. I need it to remain until the application is closed.
below:
import android.app.Application;
public class Util extends Application {
private static String idCorrente;
public void onCreate() {
super.onCreate();
idCorrente="0";
}
public static String getIdCorrente() {
return idCorrente;
}
public static void setIdCorrente(String id) {
Util.idCorrente = id;
}
}
I do not know exactly the right way to do it.
You need to store the data on the device somehow. I would recommend reading the Storage Options page of the Android Developers Guide.
Specifically, I think you will find SharedPreferences well-suited for your application.

Tracking user idle time within the app in Android

As far as I know, there is no system API for me to get user idle time. When I say user idle time, I mean user have some interaction on the touch screen within my app. Therefore, I want to track it by my self. The way come up to my mind is to extends Activity and override onuserinteraction method to save the last user active time.
But the challenge is that my app have multiple processes. I am not sure the following way is the correct and efficient way.
I want to use SharedPreference with MODE_WORLD_WRITEABLE flag to store the user last active time. To avoid the performance issue, I also cache the last active time within the activity in each activity. And I only save the new time to SharedPrefernces if the diff time > 1 second.
Is this way efficient compared to using aidl? Actually, is aidl also share variable using file? If yes, I think the two ways should have similar performance, right? Thanks.
Instead writing it down every time, from everywhere, make this a global function in your App:
public class MyApp extends Application {
private static SharedPreferences sPreference;
private static final long MIN_SAVE_TIME = 1000;
private static final String PREF_KEY_LAST_ACTIVE = "last_active";
private static final String PREF_ID_TIME_TRACK = "time_track";
public static void saveTimeStamp(){
if(getElapsedTime() > MIN_SAVE_TIME){
sPreference.edit().putLong(PREF_KEY_LAST_ACTIVE, timeNow()).commit();
}
}
public static long getElapsedTime(){
return timeNow() - sPreference.getLong(PREF_KEY_LAST_ACTIVE,0);
}
private static long timeNow(){
return Calendar.getInstance().getTimeInMillis();
}
#Override
public void onCreate() {
super.onCreate();
sPreference = getSharedPreferences(PREF_ID_TIME_TRACK,MODE_PRIVATE);
}
}
Add Application class to manifest: <application android:name="com.example.MyApp"
Place saving functionality in an abstract Activity class:
public abstract class TimedActivity extends Activity {
#Override
public void onUserInteraction() {
super.onUserInteraction();
MyApp.saveTimeStamp();
}
public long getElapsed(){
return MyApp.getElapsedTime();
}
}
Now, extend all your activities from this class, all of them will be auto-save time, and will be able to use getElapsed().

Is there any convention for a helper class in Android?

For every Activity I add to my app I'm noticing a lot of similar code being used in the initialization of the Activity. A helper class with a static method to wrap this similar code seems the way to go.
I first thought of a singleton class. I could add static methods/variables and use them across the application. I haven't really tried to see how would this work in an Android application. Searching a little bit more I saw something about creating a class extending Application. For this I did a simple test:
public class MyApp extends Application {
public static String DEMOTEXT = "WORKING!";
public static void ShowToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
}
MyApp.ShowToast(this, MyApp.DEMOTEXT); // Placed on onCreate of some Activity
This works exactly as I expected. Is this the way to go on Android or is there a better convention? Anything else I should consider when doing this?
By the way, should I use the final keyword on the string? What about the method?
EDIT: I just read this:
There is normally no need to subclass Application. In most situation,
static singletons can provide the same functionality in a more modular
way. If your singleton needs a global context (for example to register
broadcast receivers), the function to retrieve it can be given a
Context which internally uses Context.getApplicationContext() when
first constructing the singleton.
http://developer.android.com/reference/android/app/Application.html
Should I use a singleton then?
Application is primarily used for a global application initialization. You would create your own class, override Application.onCreate() and initialize your static application data there.
Dont forget to declare it in the AndroidMainfest.xml:
<application
android:icon="#drawable/icon"
android:label="#string/app_name"
android:name="your.package.path.to.MyApp">
A static helper class is made the way you did.
The convention is to use lower case letter at first position, so MyApp.showToast(...).
You would use final for the String if you would want to avoid madifications on other places (since it should be a contant).
// this would allow ...
public static String DEMOTEXT = "WORKING!";
// ... to do this somewhere else
MyApp.DEMOTEXT = "NOT WORKING!"
I haven't tried this but I think you should be able to do something like this as well.
public class MyActivity extends Activity {
private static final String DEMOTEXT = "WORKING!";
#Override
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
Toast.makeText(this, DEMOTEXT, Toast.LENGTH_SHORT).show();
}
}
Now for all activities that need to use that initialization could just extend your base activity class.
public class SomeActivity extends MyActivity {
...
// Should display the toast on create
...
}
Yes just use a singleton. Well in this case if your methods are static, you don't even need a singleton. Just a class with static methods.

Categories

Resources