Accessing same variable across multiple classes with same value - android

I have two classes where I want to access the value of a unique variable. In the first class I want to set the value of a 'isToogleflagon= true'. In the second class I want to get the value of 'IsToogleflagon'.
Here is where I set and get 'IsToogleFlagon'
public class Toogleflag{
private String _isToogleflagon;
public Toogleflag(){}
public Toogleflag(String isToogleflagon) {
this._isToogleflagon=isToogleflagon;
}
public String get_isToogleflagon(){
return _isToogleflagon;
}
public void set_isToogleflagon(String isToogleflagon) {
this._isToogleflagon = isToogleflagon;
}
I want to set the value of isToogleflagon="true" in my main class. Below is part of my main class where I do this.
public class MainActivity extends AppCompatActivity {
Toogleflag toogleflag1 = new Toogleflag();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
toogleflag1.set_isToogleflagon(GlobalVariables.TRUE);
...
Global.values(True)
public class GlobalVariables
{
public static String TRUE = "true";
public static String FALSE = "false";
}
Here's my second class where I want to get the value of isToogleflagon, in this case "true"
public class secondclass {
Toogleflag toogleflag2 = new Toogleflag();
public void test{
String test=toogleflag2.get_isToogleflagon();
}
When I run Class Secondclass the value of 'string test' does not get assigned a value. I want it to be assigned the value of "true". Any advise on how to fix this is greatly appreciated.
thanks,
Jim

This is happening because you are making a new object with default/ no argument constructor. When you make an object with default constructor, all the instance variable gets initialzes with their default values. For example,
1) int variable gets 0
2) boolean variable gets false
3) String variable gets null
That is happening in your case. As in your code it is mentioned that in main class when are you are setting value with String constructor to the variable named isToogleflagon it gets set as your constructor passed value, but when you are accessing the value of that variable again via calling no argument constructor, the variable isToogleflagon gets initiaze with defualt values as well. To get the value consistant across over all the app you need to make that class object as Singleton. It will be solving your problem. Hope you got my point. Below is the sample code for your reference to make singleton
public class Singleton {
private static Singleton singleton = new Singleton( );
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton() { }
/* Static 'instance' method */
public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
protected static void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}

Related

android passing data from class to activity

I have been looking for a long time for a simple way to pass data (string type) from class to activity.
I found some tutorials about passing data from activity to class but is it possible to do the opposite, passing data from class to activity ?
if you import the class in your activity (which is also a class by the way) you can easily access the classes attributes.
example: MyClass.java
package edu.user.yourappname;
public class MyClass {
public string infoToPass = "whatever";
}
MyActivity.java
package edu.user.yourappname;
import edu.user.yourappname.MyClass
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
String myString = MyClass.infoToPass;
}
}
i have no IDE to type this in atm it might contain some errors :S but i hope you get the idea.
if you need more specific help you have to provide a code sample.
also, what do you want to achieve exactly? maybie there's a different approach.
cheers!
Create Interface and implement that in your activity. Pass the activity instance in your class and and call that instance with interface method whenever you like.
To be more clear, create an interface and use it as following:
public interface SomeInterface{
public void passValue(String value);
}
public SomeActivity extends Activity implements SomeInterface{
// place any code you want in your activity, onCreate, onResume, etc.
private void someMethod(){
// Wherever in your activity, initialize your class with your activity.
SomeClass someClass = new SomeClass(this);
someClass.someMethod();
}
public void passValue(String value){
// do whatever you want with your value
}
}
public class SomeClass{
private SomeInterface someInterfaceInstance;
public SomeClass(SomeInterface someInterfaceInstance){
this.someInterfaceInstance = someInterfaceInstance;
}
public void someMethod(){
// Some code...
someInterfaceInstance.passValue("Hello World!");
// Some more code...
}
}
Here is a easy way of doing it -
By defining static variables
In your class, make the String whose value you want to pass public static like this -
public static String pass;
And then in you activity, you can directly access it since it's a public variable like this -
String receive = className.pass;

How to pass data from one class to another, when Bundle can't be used?

I have two Classes. Class A is an Activity that has integer variables that need to be used in Class B (not an Activity). I have been able to use Bundles to transfer data of variables from one Activity to another Activity before. The problem is that this time, Class B is not an Activity and extends ImageView so that the draw() function can be used. Because of this, I am unable to use normal Activity functions, such as Bundle-Intents or SharedPreferences to transfer data in primitive variables from Class A to my Class B. I receive an error saying that "getIntent() is undefined for type".
So my question is, how can Class B use the variables in Class A if I am unable to bundle? Is there another way?
Someone said they did not understand my question so hopefully the below example will help demonstrate better.
public Class1 extends Activity {
//so Class1 has some primitive data, and is an Activity w/layout
int var1;
int var2;
Bitmap bitmap;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
}
}
A different class needs to draw onto canvas, but also needs to use the
information in var1 and var2 to be able to draw properly. But how to obtain that information?
public Class2 extends ImageView {
/*I am unable to use normal Activity functions, so I
*cannot onCreate, for example. I also cannot bundle,
*getIntent(), or use getSharedPreferences(). So how do I get var1
*and var2 value? */
}
Update: I was able to get this to work using getters. I attempted this before, but it was not returning the correct values. If anyone else ever gets stuck with this similar issue, remember to setup your variables with "static". I'm still learning all the differences, but without static my getter was not working. Once I added static to my variables, everything worked out. So that's one observational tip (even without fully understanding the logic as to why). Thank you to all the responders for your tips.
You can do this in different way.
First of all you can use static variable to do this. Such that you can declare a variable in class A public static String variable; and from class B you can get the value of this variable like this way ClassA.variable.
Another way you can use by passing a context of class A to B and then use SharedPreference.
Or create a new class which extends android Application. From class A you can set different variable value in application class. Now you can retreive those values from Application class. Hope this can help you.
Some code Sample using static variable
public Class1 extends Activity {
public static int var1 =20;
public static int var2 = 30;
}
Now get the variable value from class two
public Class2 extends ImageView {
Class1.var1;
Class.var2;
}
Second way using getter.
public Class1 extends Activity{
int var1 =10;
int var2 =20;
public int getVar1() {
return var1;
}
public int getVar2() {
return var2;
}
}
Now you can get the variable value in Class2
public Class2 extends ImageView {
Class1 class1= new Class1();
class1.getVar1;
class1.getVar2;
}
Also you can use SharedPreference. Hope it can help you. Thanks.
Various options exist:
The Activity can pass the information to Class B:
class B {
public void tellMeInformat(int usefulNumber) {
// Do something
}
}
Or, you can pass the Activity to the ImageView:
class A {
initiation {
B mySpecialImageView = /* Set it upo */;
B.setParentActivity(this);
}
}
class B {
private myA = null;
public void setParentActiviy {
myA = A;
}
private void doSomething {
int usefulNumber = A.getUsefulNumbner();
// Do something
}
}

Singleton in Android

I have followed this link and successfully made singleton class in Android.
http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/
Problem is that i want a single object. like i have Activity A and Activity B. In Activity A I access the object from Singleton class. I use the object and made some changes to it.
When I move to Activity B and access the object from Singleton Class it gave me the initialized object and does not keep the changes which i have made in Activity A.
Is there any other way to save the changing?
Please help me Experts.
This is MainActivity
public class MainActivity extends Activity {
protected MyApplication app;
private OnClickListener btn2=new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this,NextActivity.class);
startActivity(intent);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get the application instance
app = (MyApplication)getApplication();
// Call a custom application method
app.customAppMethod();
// Call a custom method in MySingleton
Singleton.getInstance().customSingletonMethod();
Singleton.getInstance();
// Read the value of a variable in MySingleton
String singletonVar = Singleton.customVar;
Log.d("Test",singletonVar);
singletonVar="World";
Log.d("Test",singletonVar);
Button btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(btn2);
}
}
This is NextActivity
public class NextActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
String singletonVar = Singleton.customVar;
Log.d("Test",singletonVar);
}
}
Singleton Class
public class Singleton
{
private static Singleton instance;
public static String customVar="Hello";
public static void initInstance()
{
if (instance == null)
{
// Create the instance
instance = new Singleton();
}
}
public static Singleton getInstance()
{
// Return the instance
return instance;
}
private Singleton()
{
// Constructor hidden because this is a singleton
}
public void customSingletonMethod()
{
// Custom method
}
}
and MyApplication
public class MyApplication extends Application
{
#Override
public void onCreate()
{
super.onCreate();
// Initialize the singletons so their instances
// are bound to the application process.
initSingletons();
}
protected void initSingletons()
{
// Initialize the instance of MySingleton
Singleton.initInstance();
}
public void customAppMethod()
{
// Custom application method
}
}
When i run this code, i get Hello which i have initialized in Singleton then World which i gave it in MainActivity and again shows Hello in NextActivity in logcat.
I want it to show world again in NextActivity.
Please help me to correct this.
Tip: To create singleton class In Android Studio, right click in your project and open menu:
New -> Java Class -> Choose Singleton from dropdown menu
EDIT :
The implementation of a Singleton in Android is not "safe" (see here) and you should use a library dedicated to this kind of pattern like Dagger or other DI library to manage the lifecycle and the injection.
Could you post an example from your code ?
Take a look at this gist : https://gist.github.com/Akayh/5566992
it works but it was done very quickly :
MyActivity : set the singleton for the first time + initialize mString attribute ("Hello") in private constructor and show the value ("Hello")
Set new value to mString : "Singleton"
Launch activityB and show the mString value. "Singleton" appears...
It is simple, as a java, Android also supporting singleton. -
Singleton is a part of Gang of Four design pattern and it is categorized under creational design patterns.
-> Static member : This contains the instance of the singleton class.
-> Private constructor : This will prevent anybody else to instantiate the Singleton class.
-> Static public method : This provides the global point of access to the Singleton object and returns the instance to the client calling class.
create private instance
create private constructor
use getInstance() of Singleton class
public class Logger{
private static Logger objLogger;
private Logger(){
//ToDo here
}
public static Logger getInstance()
{
if (objLogger == null)
{
objLogger = new Logger();
}
return objLogger;
}
}
while use singleton -
Logger.getInstance();
answer suggested by rakesh is great but still with some discription
Singleton in Android is the same as Singleton in Java:
The Singleton design pattern addresses all of these concerns. With the Singleton design pattern you can:
1) Ensure that only one instance of a class is created
2) Provide a global point of access to the object
3) Allow multiple instances in the future without affecting a
singleton class's clients
A basic Singleton class example:
public class MySingleton
{
private static MySingleton _instance;
private MySingleton()
{
}
public static MySingleton getInstance()
{
if (_instance == null)
{
_instance = new MySingleton();
}
return _instance;
}
}
As #Lazy stated in this answer, you can create a singleton from a template in Android Studio. It is worth noting that there is no need to check if the instance is null because the static ourInstance variable is initialized first. As a result, the singleton class implementation created by Android Studio is as simple as following code:
public class MySingleton {
private static MySingleton ourInstance = new MySingleton();
public static MySingleton getInstance() {
return ourInstance;
}
private MySingleton() {
}
}
You are copying singleton's customVar into a singletonVar variable and changing that variable does not affect the original value in singleton.
// This does not update singleton variable
// It just assigns value of your local variable
Log.d("Test",singletonVar);
singletonVar="World";
Log.d("Test",singletonVar);
// This actually assigns value of variable in singleton
Singleton.customVar = singletonVar;
I put my version of Singleton below:
public class SingletonDemo {
private static SingletonDemo instance = null;
private static Context context;
/**
* To initialize the class. It must be called before call the method getInstance()
* #param ctx The Context used
*/
public static void initialize(Context ctx) {
context = ctx;
}
/**
* Check if the class has been initialized
* #return true if the class has been initialized
* false Otherwise
*/
public static boolean hasBeenInitialized() {
return context != null;
}
/**
* The private constructor. Here you can use the context to initialize your variables.
*/
private SingletonDemo() {
// Use context to initialize the variables.
}
/**
* The main method used to get the instance
*/
public static synchronized SingletonDemo getInstance() {
if (context == null) {
throw new IllegalArgumentException("Impossible to get the instance. This class must be initialized before");
}
if (instance == null) {
instance = new SingletonDemo();
}
return instance;
}
#Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Clone is not allowed.");
}
}
Note that the method initialize could be called in the main class(Splash) and the method getInstance could be called from other classes. This will fix the problem when the caller class requires the singleton but it does not have the context.
Finally the method hasBeenInitialized is uses to check if the class has been initialized. This will avoid that different instances have different contexts.
The most clean and modern way to use singletons in Android is just to use the Dependency Injection framework called Dagger 2. Here you have an explanation of possible scopes you can use. Singleton is one of these scopes. Dependency Injection is not that easy but you shall invest a bit of your time to understand it. It also makes testing easier.

how to pass, from a class to another, the name of a variable (NOT the value)

I need to pass name of a variable created in Class A to the Class B, so I can put a value in that variable (in Class B).
But, in Class B I do not know the name of that variable.
The code is something like this:
Class A
public class A {
int valore; // this is the variable, in Class b, I don't know this name!
public void callClassB(){
ClassB.Method(what shoudld i put here?)
}
}
This is the Class B
public class B {
public void Method(the_Name_Of_TheVariable_I_get){
the_Name_Of_TheVariable_I_get = 5; // i need to do this
}
}
Why do you need the variable name? Simply pass the variable itself. In class B create a method
public int getValore(){
return valore;
}
Then in Class A use modify the code as
public void callClassB(){
ClassB.Method(getValore())
}
I do not really understand what you are trying to achieve here?
You can also use the following appraoch:
interface ValueSetter {
void setValue(int value);
}
Class A
public class A implements ValueSetter{
int valore;
public void callClassB(){
ClassB.Method(this)
}
void setValue(int value){
valore = value;
}
}
This is the class B
public class B{
public void Method(ValueSetter valueSetter){
ValueSetter.setValue(5);
}
}
This is more inline with OOPS..
You will need to use reflection for this.
Here is a tutorial from Oracle: http://docs.oracle.com/javase/tutorial/reflect/index.html
You cant get the name of variable at runtime though. But assuming you have the name of the field the code would look something like this:
this.getClass().getDeclaredField(the_Name_Of_TheVariable_I_get).set(this, 5);
you can pass the name of the variable "valore", then you need reflection to assign it in your method :
a = new A();
Field f = a.getClass().getDeclaredField(varName);
f.set(a, 5);
a can be a parameter too. (it is necessary to give the instance that possesses the member).
However, this is not a recommended way of treating your issue, as it is unreliable in the sense that the compiler will not be able to check you are accessing items that actually exist.
It would be better to use an interface, for instance :
public interface Settable {
public void set(int value);
}
and then:
public class A implements Settable {
private int valore;
public void set(int value) {
valore = value;
}
public void callClassB(){
ClassB.Method(this);
}
}
and in B:
public class B{
public void Method(Settable settable){
settable.set(5);
}
}

Creating an Object accessible by all Activities in Android

I'm trying to create an ArrayList of Data containing Objects (Like a list of Addresses and properties (pretty complex)) and am wondering: How can I make an Object accessible (and editable) by all Activities and not just the one it was instanciated in?
Basically this:
Create Array in Activity 1
Access same Array in Activity 2 and 3
???
Profit.
The easiest way to do this is by creating an Singleton. It's a kind of object that only can be created once, and if you try to access it again it will return the existing instance of the object.
Inside this you can hold your array.
public class Singleton {
private static final Singleton instance = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
Read more about singleton:
http://en.wikipedia.org/wiki/Singleton_pattern
You can extend the application class. And add your arrays there.
You can access the instance of the class by using this command
MyApplication appContext = (MyApplication)getApplicationContext();
Well you can create a Constant class and declare you ArrayList as a static variable.
1.)
Class ConstantCodes{
public static ArrayList<MyClass> list = new ArrayList<MyClass>;
}
This will be accessible from everywhere you want by just ConstantCodes.list
2.) You can extend your class by Application class like this
class Globalclass extends Application {
private String myState;
public String getState(){
return myState;
}
public void setState(String s){
myState = s;
}
}
class TempActivity extends Activity {
#Override
public void onCreate(Bundle b){
...
Globalclass appState = ((Globalclass)getApplicationContext());
String state = appState.getState();
...
}
}
you should make it static and access it from any other activity.....
how about use a static keyword ?
public static SomeClass someObject
in your activity class that initiate your object
1- In your Activity1, déclare your array in public static
public static ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String, String>>();
2- In your Activity2, Activity3, etc. access to your ArrayList
Activity1.myArray
You can create a java file x beside other java files.
x file contains static method which used to access the class method without instantiate it.
Now make a method called createVariable() and declare variable which you want to make it Global.
Now make a method called getVariable() which returns the Global variable.
At which point you want to create global variable, call className.createVariable().
And to get access to that variable call className.getVariable().
Here is my example for Database class.
public class GlobalDatabaseHelper{
static DatabaseHelper mydb;
public static DatabaseHelper createDatabase(Context context)
{
mydb = new DatabaseHelper(context);
return mydb;
}
public static DatabaseHelper returnDatabase()
{
return mydb;
}
}

Categories

Resources