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;
Related
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();
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();
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;
}
}
I have many classes which have the same static attribute (staticAttr) and i have another class which accepts the class name and accesses its staticAttr of the class name specified.
How can i do this. Please help me!
Thanks.
EDIT:
public class Group_name1 extends Activity implements View.OnClickListener,
{
public static Group_name1 staticVar;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.group_name1);
staticVar = this;
}
}
public class Group_name2 extends Activity implements View.OnClickListener,
{
public static Group_name2 staticVar;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.group_name2);
staticVar = this;
}
}
Now my problem is to have an access to the static variable of these classes in another class by just giving a class name string. Now the class should can be used to get the staticVar which contains the object.
Currently, i have created seperate classes for every class mentioned above to refer to the staticVar. But i feel its redundant and bad style of programming because every class i write for refering to the above classes does the same function. The only thing that changes is the Class name reference
Group_name1 grpActivity;
Group_name2 grpActivity;
These are my current implementations. But i want to just use the class name to refer the static variable
class GroupNameListener1 extends Thread
{
Group_name1 grpActivity;
public void run()
{
grpActivity = Group_name1.staticVar;
/*
do something
*/
}
}
class GroupNameListener2 extends Thread
{
Group_name2 grpActivity;
public void run()
{
grpActivity = Group_name2.staticVar;
/*
do something
*/
}
}
Like this :
ClassWithStaticVariable.VariableName
if you have
class A {
public static String a = "test"
}
then you can access it like this :
class B {
public void test() {
System.out.println(A.a);
}
}
If I am understanding you correctly you have something like
class A {
public static String str = "test"
}
and in you code you have a method like
void methodA (A someObj) {
in this method you can access the static variable
as
A.str
or
someObj.str
What you have is very bad design. Short of reflection there is no way to solve this generically as you designed it.
I believe what you are trying to do is attaching meta data to your classes. A very simple way to do that would be to keep a global map holding the data (and work with the class instead of its name):
public class MyClassMetaData {
private final static Map<Class<?>, String> dataMap = new HashMap<>();
static {
dataMap.put(MyClassA.class, "TestA"); // one method of initialization
dataMap.put(MyClass2.class, "Case2");
// one line per class...
}
private MyClassMetaData() {
}
public static String getMetaData(Class<?> theClass) {
return dataMap.get(theClass);
}
}
But you need to remember to add a line that puts the data into the map into the static block when you add another class.
If you need to initialize data dynamically, access to the map may need to be synchronized.
If we have class A & B, and class A's constructor is private, and we want to use an instance of A in B, how to do that ? I see an answer that says "provide a static method or variable that allows access to an instance created from within the class " but I didn't understand that.
The code pattern you seek is called the Factory Method.
The class provides a static method that returns an instance of its own class. Private constructors are visible to all methods (including static ones) of the class, so the static method can invoke the private constructor on the caller's behalf.
Here's an example of this pattern in action:
public class A {
private A() {
}
public static A create() {
return new A();
}
}
This is often employed in conjunction with the Singleton Pattern, which would change the above example to this:
public class A {
private static A INSTANCE = new A();
private A() {
}
public static A getInstance() {
return INSTANCE;
}
}
A needs to have a public method that provides an instance of the class A, eg:
class A {
/*Constructors and other methods omitted*/
public static A getInstance() {
return new A();
}
}
Alternatively, if B is an inner class of A (or vice-versa), then B can directly reference the constructor eg:
public class A {
private A() {}
public static class B {
private A instanceOfA = new A();
public B() {}
}
}
A class that only has private constructors is designed so that other classes cannot instantiate it directly. Presumably there is a sound reason for this. The class may provide a factory method for instantiating the class ... or getting an existing instance of the class.
If you need to change the design, the best way is to modify the class; e.g. by making a constructor visible, or by adding a factory method. If you can't do that, I think it is possible to use reflection to break the visibility rules and create an instance using a private constructor. However, I'd only do this as a last resort ... and not before carefully analysing the consequences for the overall application.
Private constructors are intended to make a class not to have any instance. But the content can be accessed from child class using super(). Implementation is like this:
public class ClassA {
private int val;
private ClassA(int val)
{
this.val = val;
}
public int getVal() {
return val;
}
}
public class ClassB extends ClassA {
public ClassB(int val) {
super(val); } }
...
ClassB b = new ClassB(4);
System.out.println("value of b: " + b.getVal());
As an example see class Calendar. To get an instance you must not call its constructor but use a static method:
Calendar rightNow = Calendar.getInstance();
source