How to store global variables using setter and getter in Android? - android

i am new to android development and i was trying to use a global variable across two activities. So how do i do the same using setter and getter? or is there a better way?
Please do help me!
Thanks in advance!
Sidharth

For global variable :
Use can use SharedPreference, which will save the value till you uninstall the application and can be accessed from anywhere within application using context.
Extend Application class, and declare the global variable inside it and add getter and setter methods.
And in your activity :
YourApplication yourApplication = (YourApplication) getApplicationContext();
yourApplication.setGlobalValue(10);
yourApplication.getGlobalValue();
Create class :
class YourApplication extends Application {
private Integer globalValue;
public Integer getGlobalValue() {
return globalValue;
}
public void setGlobalValue(Integer value) {
globalValue = value;
}
}

The easiest way to do this would be to pass the variable to the second activity in the intent you're using to start the activity:
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("variableKEY", variable);
startActivity(intent)
Access that intent on next activity
String s = getIntent().getStringExtra("variableKEY");
The docs for Intents has more information (look at the section titled "Extras").
From here

Related

How to persist a subset of data from a larger set in Android?

A network call returns a very large json file. However, I just need to use a small portion of this through out the entire app. What is the best strategy on using a small amount of data for several fragments and activities ?
I tried to use shared preferences, but that does not store objects.
For sharing complex data structures or objects, I would extend Application by making a custom sub class. Application object (as the name implies) is accessible to all Activities, even when app transitions from one to another. Below is a very simple example, just to show you the idea. You can modify/adjust that to your needs.
public class MyApplication extends Application {
private X x;
public static void setX(X x) { ... }
public static X getX() { ... }
}
public class ActivityA extends Activity {
...
MyApplication.setX(x);
}
public class ActivityB extends Activity {
...
X x = MyApplication.getX();
}
X can be a collection, data structure, or any object for that matter.
When extending Application, you need to declare it in the manifest. You can find information on how to do that.
Extract the required data from your JSON as a String and then pass it as an extras parameter to the Activities and Fragments that need it:
Intent intent = new Intent(context, SomeActivity.class);
intent.putExtra("YOUR_DATA_KEY", yourJsonString);
startActivity(intent);
and then extract it back again at the Activities and Fragments that need it:
Intent intent = getIntent();
String yourJsonString= intent.getStringExtra("YOUR_DATA_KEY");

Sharing Variables Across Different Activities In Android Studio

I Have an Activity called Main2Activity, and it consists of a variable "double result1 " which is set equal to an expression. It looks like this:
double result1 = n1 * 2 - 29; (Where n1 is an input given by the user)
I'm trying to use this variable in another class called MainActivityEnd. I tried this:
double finalResult = Main2Activity.result1 * 4;
When I print result1 in Main2Activity using setText it prints the correct value.
But when I print finalResult in MainActivityEnd using setText It always prints 0.0
Is there a reason for this?
Thanks for the help!
If activities are in the same flow, you should use the following Android way - intents. Simply put, Intent is Android's way of changing values between activities when they are launched in sequential order.
So you should do the following in Main2Activity:
Intent intent = new Intent(Main2Activity.this, MainActivityEnd.class);
intent.putExtra("name", variable);
startActivity(intent);
where Main2Activity starts MainActivityEnd. The Intent is filled with the data MainActivityEnd needs, which in this case is "variable".
Afterwards you should catch the Intent in MainActivityEnd onCreate() method like this:
Intent intent = getIntent();
double finalResult = intent.getDoubleExtra("name", 0);
where "name" is the same name that was given in Main2Activity and 0 is a default value if there's wasn't a double value attached to Intent in Main2Activity.
That's the most common usage of this behaviour in Android.
Use Intents or SharedPreferences like other people has already mentioned here.
If however you are planning to put some global logic (like methods) then use Application class.
You can extend Application class like this:
public class YourApplication extends Application {
public double result1 = 29;
}
And then in any in your Activities:
YourApplication app = (YourApplication) this.getApplication();
System.out.printl(app.result1);
Make sure that you named your application class properly, it should be [YOUR_APP_NAME]Application. And also don't forget to put your new application class into the manifest:
<application
android:name=".YourApplication"

How to pass object from one activity to another activity without using Intent

I am new at developing Android .I have a question. How to pass object from one activity to another activity without using Intent.Can I do it by Interface ,if so how Could you please how can I hanle that
I think you have 2 options
In memory, save it to somewhere that all activities can reach, or make it static. This is not good idea though
Save it to disk, and use it, such as shared preferences
You can store it in SharedPreferences and then in another Activity
restore it.
You can store it in SQLite and then in another Activity restore it.
You can use static links
You can use service
save data in a singleton class model and get the same object from another activity
Create a class like this
public class SingletonModel {
private static SingletonModel instance;
public String textData = ""
public synchronized static SingletonModel getSingletonModel() {
if (instance == null) {
instance = new SingletonModel();
}
return instance;
}
private void SingletonModel(){}
}
From first activity do like this
SingletonModel.getSingletonModel().textData ="Your data goes here";
From second activity do like this
textView.setText(SingletonModel.getSingletonModel().textData);
If the data should persist, use a file. If not, use a singleton.

passing variable status between classes

I am making a boolean variable value in one class and accessing the status of that variable in another class , on the basis of the boolean variable status my list view shows items,
So my question is
how to create a global boolean varible
how to pass it to another class
how the second class check it
1. Variable in class A
public class A{
public String aClassVar="hello";
}
Using it in Class B
A obj=new A();
String inBClass=obj.aClassVar;
2. To pass data from one Activity to Another Activity you can use Intent remember your Class should extends Activity only than you will be able to pass data by using Intent
Example
Send Data From First Activity using :
Intent i = new Intent(this, SecondClassName.class);
i.putExtra("key", "Value");// key is used to get value in Second Activiyt
startActivity(i);
Receive Data on Second Activity using:
Intent intent = getIntent();
String temp = intent.getStringExtra("key");// usr getStringExtra() If your extra data is represented as strings:
And you Must set Activity Name inside AndroidManifest.xml
like:
<activity android:name="yourPackageName.SecondClassName" />
Let me suggest 3 options.
Do you want to pass a boolean variable between Android Activities? If so, You may want to use a Bundle. Yes, those little things given to Activities on onCreate(). You can pass variables of your own into these, in your case a boolean, with putBoolean() and getBoolean()
Would you prefer using Android's SharedPref? It's an interface for sharing small preferences, like boolean flags, between parts of your app and storing it for later.
Or, you could just implement a singleton class that has the boolean variable and other variables you need to store and check by different classes within your app.
If you just want to access the value of an object or variable in another class, make it Static and then when you need its value, do like
public class tempClass {
public void tempMethod() {
boolean status = myClass.myVariable ; // where myVariable is static boolean varaible of myClass
}
}
But make sure to access the variable after some value is stored in it.
If you want to send the value to another activity then send the value by using intent.
Eg.
Bundle myBund = new Bundle();
myBund.putBoolean(myBool);
Intent intent = new Intent(myClass.this, tempClass.class);
intent.putExtras("myKey",myBund);
startActivity(myBund);

is it possible to fetch the object value without calling a new activity?

I know that stuff of calling the new activity and pass the object value from one activity to another by using putExtra and getExtra function. but i want to pass the value without calling and start the new activity. Is it possible ?
If yes then let me know how i can do it ?
You can also use the Application class for declaring global variables
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){
...
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
...
}
}
UPDATED :
Checkout this nice Tutorial about how to do that.
Application Class Using as Global
for this you can use static variable or SharedPreferences or if you heavy data then you can use SQlite.
You can take the help of database like SQLite or you may go for Constant class concept where you can make a public static variable and store your data in one activity and access in other activity.Hope this will help you.
There're a lot of ways to pass a value to an activity:
You can use an Intent with FLAG_ACTIVITY_REORDER_TO_FRONT. In this case onNewIntent() method will be called for already started activity.
You can use static fields or static methods to pass new data to your activity. But it's not a good method really because sometimes application is terminated even if it's foreground and all static data is lost.
You can send new data to an activity using broadcast messages. In this case the activity must register a BroadcastReceiver.
I think it's not very difficult to make up a few more ways to pass arguments.
You may want to use handler's handleMessage() and pass the object in a message .
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
}
};
You can then call handler.handleMessage(msg), you can assign any object to msg.onj

Categories

Resources