Reputation:
So I'm making a mobile game and have multiple activities throughout my project. I have been passing variables from one activity to the next using Intents, and then passing these variables back to other activities. So, for example, if there is a value x = 5 in Activity1, that value would be passed into Activity2. Then, if the player changes x to 6 in Activity2, this information would be passed back into Activity1.
This method works, but it seems very inefficient. Is there any way to create a global variable for the entire project in such a way so when I change it in one activity, it changes in all the activities?
Thanks
Upvotes: 0
Views: 9862
Reputation: 129
You should use SharedPreferences
https://developer.android.com/training/data-storage/shared-preferences
Upvotes: 1
Reputation:
Given your requirements:
public class X {
public static int val = 0;
}
and
{
X.val = 5;
}
Of course this is naive - but if you have more requirements you should specify them.
Upvotes: 0
Reputation: 658
There are multiple ways to achieve that, some of them are according to good architecure practices, some of them are not. Generally, Singleton pattern first pops on mind, but I would avoid Singleton since it is global state and anti-pattern.
I would add that variable in your Application class implementation, and access it as ((MyApplication) getApplication()).getMySharedVariable()
What can be even better, you can make that variable accessible trough listener (using Listener or Publish/Subscribe pattern) so whoever wants, they may subscribe to all changes that happen with your variable and react upon it imediatelly. Subjects from RxJava can be very helpful for achieving it.
Upvotes: 0
Reputation: 1387
Simple, create a singleton, store your variable there and then have your activities read from and write to the variable in the singleton.
How to declare a singleton:
Kotlin:
object MySingleton {
var myVariable: Int = 0
}
Java:
public class MySingleton {
private int myVariable = 0;
// Getter/setter
private static MySingleton instance;
public static MySingleton getInstance() {
if (instance == null)
instance = new MySingleton();
return instance;
}
private MySingleton() { }
}
Upvotes: 4