I'm trying to implement Global variables in and Android Studio Application that uses BLE gatt services.
I need to save a number received from BLE in a global variable.
So I have created this class:
public class Globals extends Application {
private List<Float> current = new ArrayList<>();
public float getCurrent() {
return current.get(current.size()-1);
}
public void setCurrent(float someVariable) {
this.current.add(someVariable);
}
}
I have also modified the manifest with android:name. I can use correctly these functions in both the main activity and in some fragment. But I want to implement it in other extends different from Application or Activity.
In another java file I have this class:
class SerialSocket extends BluetoothGattCallback {
// Here how can i get the function declared in Globals??
Globals globalClass = (Globals) getApplicationContext();
Obviousy I can't use getApplicationContext() inside the BluetoothGattCallback extend, but what code can I use?
You can create a static instance of Globals and access.
public class Globals extends Application {
private static Globals instance;
private List<Float> current = new ArrayList<>();
#Override
public void onCreate() {
instance = this;
super.onCreate();
}
public float getCurrent() {
return current.get(current.size()-1);
}
public void setCurrent(float someVariable) {
this.current.add(someVariable);
}
public static Globals getInstance() {
return instance;
}
public static Context getContext(){
return instance;
// or return instance.getApplicationContext();
}
}
Now anywhere in app you can access the current variable or change the value by
Globals.getInstance().getCurrent();
Related
Good day everybody! Here's my question:
I need to make a Tutorial for my app. For doing this, I've created a class called TutorialClass which contains some methods that I need to call from several other classes. The working flow is quite like this:
Class 1:
//...
if(Tutorial.tutorialStep==Tutorial.TUTORIAL_STEP1){
Tutorial.TutorialStep1();
Tutorial.tutorialStep=Tutorial.TUTORIAL_STEP2;
}
Class 2:
//...
if(Tutorial.tutorialStep==Tutorial.TUTORIAL_STEP2){
Tutorial.TutorialStep2();
Tutorial.tutorialStep=Tutorial.TUTORIAL_STEP3;
}
And so on...
All the classes I use, have not to extend Activity necessarily
You can find this piece of code in several class I use.
So, first of all I need to create an instance of TutorialClass
TutorialClass Tutorial = null;
So here is the question: how can I use this instance from all the classes in which I have to show my tutorial? As you can see, the value of tutorialStep has to be visible from all classes, and all classes have to see that value or change it, in order to let the tutorial go on.
Here is the code of my tutorial class:
public class TutorialClass{
Context context;
public static int tutorialStep;
final int TUTORIAL_STEP1=1;
final int TUTORIAL_STEP2=2;
final int TUTORIAL_STEP3=3;
//...
TutorialClass(Context context){
this.context = context;
}
public void Tutorial1() { ... }
public void Tutorial2() { ... }
public void Tutorial3() { ... }
//...
}
I've read that exist a Singleton class that allows to reach my objective, but I've noticed that it's not the best solution. Do you have any solution? Thanks to all!
you need to create another class that return instance of the TutorialClass
public class TutorielInstance {
private static TutorialClass instance;
private static Context context;
public static synchronized TutorialClass getInstance(){
if(instance==null){
instance=new TutorialClass(context);
}
return instance;
}
public static void setContext(Context c){
context=c;
}
}
and then in the activity you can use
TutorielInstance.setContext(this);
TutorialClass tutorialClass=TutorielInstance.getInstance();
This main class is initialized by the Bukkit framework and cannot be initialized again.
public class Demo extends JavaPlugin {
public void onEnable() {
}
}
How do I access its unique instance from other classes?
public class CoolDown extends BukkitRunnable {
public CoolDown(Demo mainClass, int time) {
}
public void run() {
}
}
If you want to use the OOP way:
In your CoolDown class, have a field with the type of Demo (or your JavaPlugin-extending class). You may also create any other fields you will pass in the constructor here.
private final Demo plugin;
private int time;
Then instantiate the fields using the CoolDown's constructor
public CoolDown(Demo plugin, int time) {
this.plugin = plugin;
this.time = time;
}
Now you can use the plugin field for your needs. Example:
public void run() {
plugin.fooBar();
}
If you want to use the Static Programming way (not recommended, you are in a OOP language being Java!): In your Demo class, have a public, static field of type Demo, without any value (this is after the class decleration, by the way).
public static Demo instance;
In your plugin's enable method (I suggest to put this at the very first line of the method invokation):
instance = this;
Then you can use, in your CoolDown's run() method invokation:
Demo.instance.fooBar();
Once again, I do not suggest using static programming in Java. It's a lazy and bad practice in general.
Here is a full example, in your case, in OOP programming:
public class Demo extends JavaPlugin {
public void onEnable() {
Bukkit.getScheduler.scheduleMyEpicCooldown(new CoolDown(this, time), time);
}
}
public class CoolDown extends BukkitRunnable {
private final Demo plugin;
private int time;
public CoolDown(Demo plugin, int time) {
this.plugin = plugin;
this.time = time;
}
public void run() {
plugin.fooBar();
}
}
You have to re-invent the Singleton Pattern.
public class Demo extends JavaPlugin {
private static Demo instance;
public Demo() {
instance = this;
}
public static Demo getInstance() {
return instance;
}
#Override
public void onEnable() {
}
}
To access:
public class Cooldown extends BukkitRunnable {
#Override
public void run() {
Plugin main = Demo.getInstance();
main.getServer().broadcastMessage("No need to have the main instance as member variable on each class.");
}
}
I am new to java singleton, I want to make my class singleton, so that I have one instance of it in my code.
The class which I want to be singleton is extend another class which its constructor have two entry.
Below code is, what I have done! but it is not correct!
how can I write my singleton
public class Singleton extends Parent{
private Ui ui;
private Store store;
private singleton(Ui ui, Store store) {
super(ui, store);
// TODO Auto-generated constructor stub
}
private static class singletonHolder() {
// My problem is here: how to set value for super class?!
public static final singleton INSTANCE = new singleton();
}
public static singleton getInstance() {
return singletonHolder.INSTANCE;
}
protected Object readResolve() {
return getInstance();
}
public void SetStore(Store dstore){
store = dstore;
}
public void SetUi(Ui uid){
ui = uid;
}
}
In my android project, I have ImageAdapter class in which I pass app context for some further needs.
public class ImageAdapter extends BaseAdapter {
private Context c;
public ImageAdapter(Context c) {
this.c = c;
}
...
}
The problem is that I wanna make ImageAdapter as a singleton to have an easy access to the instance of this class from all of my activities. But I have no idea how to pass app context from getApplicationContext() method from one of my activities to ImageAdapter. So is there any "magic" to do that as follows?
public class ImageAdapter extends BaseAdapter {
private Context c;
private static class Holder {
public static final ImageAdapter IA = new ImageAdapter();
}
private ImageAdapter() {
this.c = /* some magic here */.getApplicationContext();
}
public static ImageAdapter getInstance() {
return Holder.IA;
}
...
}
Maybe you have some other ideas for sharing ImageAdapter for any of my activities.
I'm a newbie to android and I'm a little bit confused with the ways of passing data among activities.
I will be grateful for any help.
Update: 06-Mar-18
Use MyApplication instance instead of Context instance. Application instance is a singleton context instance itself.
public class MyApplication extends Application {
private static MyApplication mContext;
#Override
public void onCreate() {
super.onCreate();
mContext = this;
}
public static MyApplication getContext() {
return mContext;
}
}
Previous Answer
You can get the the application context like this:
public class MyApplication extends Application {
private static Context mContext;
#Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
}
public static Context getContext() {
return mContext;
}
}
Then, you can call the application context from the method MyApplication.getContext()
Don't forget to declare the application in your manifest file:
<application
android:name=".MyApplication"
android:icon="#drawable/icon"
android:label="#string/app_name" >
I'd rather pass a context instance as a parameter to every method in singleton which really needs it
APPROACH #1:
Since you specify that ImageAdapter is a singleton, one simple answer is to create that singleton from a class that has access to app context:
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
ImageAdapter.createIt(this);
}
}
public class ImageAdapter extends BaseAdapter {
private static ImageAdapter it;
// Get the singleton.
public static ImageAdapter getIt() {
return it;
}
// Call this once, to create the singleton.
public static void createIt(Context context) {
it = new ImageAdapter(context);
}
private final Context c;
private ImageAdapter(Context context) {
c = context;
}
}
APPROACH #2:
If it were not a singleton, then I would use the accepted answer. In that case, remove the local variable from ImageAdapter, because context can always be obtained from MyApplication. Expanding on the accepted answer, if you want a local method as a convenience, define ImageAdapter.getContext(). Complete solution:
public class MyApplication extends Application {
private static Context appContext;
public static Context getContext() {
return appContext;
}
#Override
public void onCreate() {
super.onCreate();
appContext = this;
}
}
public class ImageAdapter extends BaseAdapter {
public ImageAdapter() {
}
// [Optional] Call this whenever you want the app context.
private Context getContext() {
return MyApplication.getContext();
}
}
I am creating a custom class in main application class. Lets say My mainAccount.
Now, i am creating many activities. I want to mainAccount variable in every activity, how can i do that? One way is to put in intent and pass to each activity. Is there any better way, like making it global etC?
Best Regards
Look up Singleton classes. Basically, you want something like this.
public class Singleton {
private static Singleton instance = null;
protected Singleton() {
// Exists only to defeat instantiation.
}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
Then, for any class that needs access to the class, call:
Singleton var=Singleton.getInstance();
This is essentially global, without most of the negative consequences of global variables. It will ensure that only one object of that class can exist, but everyone who needs it can access it.
Have you thought about using preferences?
A great resource for more info is.
http://mobile.tutsplus.com/tutorials/android/android-application-preferences/
Or you can create a class that extends application as demostrated by
http://www.helloandroid.com/category/topics-covered/global-variables
Just define an Abstract class with those variables and methods whichever you want to access in activities.
For example:
public abstract class BaseActivity extends Activity
{
//static variables
// static methods
}
Now extends this BaseActivity class in your all activity:
public class HelloAndroid extends BaseActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
You can use "singleton" class, or "static" class (if you don't need to initialize it, instantiate or inherit or implement interfaces).
Singleton class:
public class MySingletonClass {
private static MySingletonClass instance;
public static MySingletonClass getInstance() {
if (instance == null)
instance = new MySingletonClass();
return instance;
}
private MySingletonClass() {
}
private String val;
public String getValue() {
return val;
}
public void setValue(String value) {
this.val = value;
}
}
String s = MySingletonClass.getInstance().getValue();
Static class:
public class MyStaticClass {
public static String value;
}
String s = MyStaticClass.value;