How to create a global variable in android? [duplicate] - java

This question already has answers here:
Android global variable
(14 answers)
Closed 8 years ago.
In my android application I need a place for putting the variable member id .
The problem is , it is getting from the online API and I need to find a way to store / retrieve it
I have tried to put it in a custom class , but the problem is , it will lose if I kill the activity, I have also know that there is a way to extends the application.
So I would like to know what is the best way to store global variable?
I have to implment:
Save the variable on onSaveState
Save it on sharepref
Save it manually
Retrieve it manually
Thanks
Update:
Thanks for reply. If I have just 3 variable (simple data e.g. a boolean , a phrase ), and I need it after app restart , should I simply use share pref to store it? What is the drawback of it? e.g. Will it harmful to the performance? thanks

You can create the global variable in android by declaring them in the class which extend the Application class.
Something like this.
class MyAppApplication extends Application {
private String mGlobalVarValue;
public String getGlobalVarValue() {
return mGlobalVarValue;
}
public void setGlobalVarValue(String str) {
mGlobalVarValue = str;
}
}
MainActivity.java
class MainActivity extends Activity {
#Override
public void onCreate(Bundle b){
...
MyAppApplication mApp = ((MyAppApplication)getApplicationContext());
String globalVarValue = mApp.getGlobalVarValue();
...
}
}
Update
This hold the value until your application is not destroyed. If you want to keep your values save even after your application instance destroy
then you can use the SharedPreferences best way to do this.
Learn about the SharedPrefernces from here : http://developer.android.com/reference/android/content/SharedPreferences.html

If you need a global variable, which is shared between multiple activities and survives their lifecycle changes, but is otherwise not persisted and would not survive an application restart, the method suggested in the first answer (extending Application and putting it there) is ok.
If you need a persisted global setting, which should also survive an application restart, then you should use one of the other methods suggested. SharedPreferences is probably the easiest to use.
See also this Stack Overflow question: What's the best way to share data between activities?

You can store it in a SharedPreferences, and create a sharedpreferenceHelper class to retrieve/store it.

Its always better to store values which you want to use multiple times in one of the following ways:-
Shared Preferences
Singleton classes
Write it to a file
SQLite Database
Store on the web-server

Related

Prevent class from unload, java

In my Android App I have a static class to share some variables and functions within the whole application.
some variables from this class are initiated in other Activities (once, for example, user select something from the grid view, then I store its selection in this static class to use it later in another activity)
Everything was fine, but it looks like that after some period of inactivity of the App (once it stays in the Background), this static class is destroyed and then re-initialized with default values, which are "wrong", let's say.
Or, probably, the whole app is disloaded, and after I call it back, it restores the last activity which is trying to access some variables but they are re-initiaed
It there any way to prevent class from re-initialization or keep the static values or to keep these values somehow else and restore them once activity is re-created?..
Thanks a lot!
Instead of looking for ways (or rather hacks) to stop re-initialisation of your classes or storing the variables in a static class I would rather suggest you to store the state of your app in local storages like Shared Preferences or the SQLite DB.
The advantage of this would be you can access this variables in any part of your app and secondly you will get rid of those static classes and variables which are the main culprit of Memory leaks and ANRs.
I think sharedPreference is the perfect alternative for you. It helps to store your data locally.

Passing references to Activity Intent

For quite some time I've had troubles passing variables from one Activity to another, and I've usually had to resolve to some pretty ugly Static-class-hacks to make it work.
Generally something along the lines of a static method that I call with the type of the Activity, along with the variables the Activity requires. These gets stored in a static variable, and retrieved in the constructor of said activity.
Like I said, pretty ugly. And there's no such thing as "myActivity.StartActivity(new Activity);". All of the overloads for StartActivity takes either an Intent, or a typeof(MyOtherActivity).
So my question is, have I completely misunderstood the concept of Activities, or am I simply missing a completely obvious way to pass arguments to them?
#Edit: The reason I want to pass an actual reference to an object, instead of simply a copy of the object, is because I'm trying to pass a View Model from an overlying Activity, down to the new Activity. And of course any changes made to this view model, should be reflected on the parent activity, which will only be possible if the the two activy's viewmodels points to the same instance.
I'm writing the app using Xamarin.Android, but the code is nearly identical between C# and Java, so answers in either those languages is fine.
The problem is that Android can kill the process hosting your app at any time (if it is in the background). When the user then returns to your app, Android will create a new process to host your app and will recreate the Activity at the top of the stack. In order to do this, Android keeps a "serialized" version of the Intent so that it can recreate the Intent to pass it to the Activity. This is why all "extras" in an Intent need to be Parcelable or Serializable.
This is also why you cannot pass a reference to an object. When Android recreates the process, none of these objects will exist anymore.
Another point to consider is that different activities may run in different processes. Even activities from the same application may be in different processes (if the manifest specifies this). Since object references don't work across process boundaries, this is another reason why you cannot pass a reference to an object in an Intent.
You can also use The Application class to store objects globally and retrieve them:
using Android.Runtime;
namespace SomeName
{
[Application]
public class App : Application
{
public string Name { get; set;}
public App (IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public override void OnCreate ()
{
base.OnCreate ();
Name = "";
}
}
}
And you can access the data with:
App application = (App)Application.Context;
application.Name = "something";
I choose to do this on the Application calss because this class is called on the App startup so you don't have to initiate it manually.
Keep in mind that variables which are scoped to the Application have their lifetime scoped to the application by extension.
This class will be Garbage Collected if the Android feels it is necessary so you have to modify the code to include this case also.
You can use SharedPreferences or a Database to save your variables in case they get deleted and retrieve them from the App class for faster results.
Don't be overly wasteful in how you use this approach though, as attaching too much information on this class it can lead to a degradation in performance. Only add information that you know will be needed by different parts of the application, and where the cost of retrieving that information exceeds the cost of storing it as an application variable.
Investigate which information you need to hold as application wide state, and what information can simply be retrieved straight from your database. There are cost implications for both and you need to ensure you get the balance right.
And don't forget to release resources as needed on OnStop and OnDestroy
I rarely use intents, i find this way better.

how to use a Class to let different activites read data from it?

everybody. I want know if I can use a Class to store data which input from Activity A, and read the same data from Activity B.
There are some variables in my android program I want to share between all activities in it.
Thank you!
I want know if I can use a Class to store data which input from Activity A, and read the same data from Activity B.
Yes but it depends on what you are doing if its a good idea or not.
There are some variables in my android program I want to share between all activities in it.
If these are simple variables and few then you will probably best using SharedPreferences.
If there are a lot of variables then you may want to use a SQLite DB to store and access these variables. Or possibly save them on the filesystem.
Of course you can also use putExtra() in your Intent to send data but it doesn't sound like this is what you want
To decide what fits you best, read Storage Options
Simplest way to do this is to store these variables in some static member of some class, or create a singleton class which can store all this data.
More complex ways would be to user the shared preferences or sqlite db as #codeMagic sugggested.
Another option is to pass the data between the activities when you start them view intent.putExtra
Yes you can.
See the mockup class below
public class myVariables
{
public String myVariable1;
public int myVariable2;
public boolean myVariable3;
//it is not advisable to use public methods, but for the sake of proofing that you can use variables
//this example uses this method. Ideally, you need to set get / set methods.
}
Now, anywhere inside you app classes you can call
myVariables.myVariable1 = "Hakuna Matata";
Then
Log.i("tag", myVariables.myVariable1); //this will show "Hakuna Matata"

Is putExtra the only way of passing data to a new Activity?

I have created a SettingsActivity for my app. In this Activity I am using the SharedPreferences class to do handle the user editable preferences.
While setting up the SharedPreferences, I have to load them in the onCreate of my main activity and then again in the SettingsActivity. The probably was that both calls to the getXXXX() methods require defaults and I figured that it would not be good to hard-code the default values into both places because I would imagine it would be problematic in the future if I ever changed them.
Which is the best/most popular (or accepted standard) of doing this?
Create a global variables class in which I import into each activity and define my default constants in there?
Use putExtra and getExtra to pass the data from the main activity to the settings activity?
Any other suggestions?
I think Squonk has a good answer, but if you're looking for an alternative, consider creating a Settings class with all of your settings as members. It could have a static method like loadFromPreferences(Context) that would return a Settings object constructed from SharedPreferences, using whatever defaults you need. It could also have a saveSettings(Context) method to save your edits. Hope that helps.
Personally, in this situation, I'd put the default values in a resource file. In that way there's no need to use a global variables class or a helper class. Android resources already do that for you.
See:
Providing resources
More resource types
Instead of using a class with static values why dont you extend the Application class which will always live when the application's process lives. you can keep shared methods and variables in it
I would highly recommend opening the SharedPreference in the onCreate of both activities. Every time I've tried to use global variables, the values disappear in a way that's difficult to detect and fix. Activities are destroyed when they are closed. Services can be removed from memory at any time. The application context will be destroyed if your services are sleeping and don't have activities in memory.
That being said, putting a variable in the application context is probably the best place. Create a class that extends Application and set AndroidManifest.xml to use this. Just don't expect the value to be there if you try to use it from services or broadcast receivers.
Also, unless you're having problems with the activities loading too slowly, you're better off spending time on features than optimization.
You can declare objects as public static and reference them from another class. ActivityA:
public static int testIntegerA = 42;
Intent intentInteger = new Intent(getActivityContext(), ActivityB.class);
intentInteger.putExtra("INTENT_EXTRA", testIntegerA);
startActivity(intentInteger);
ActivityB:
public static int intentInt, staticInt;
staticInt = ActivityA.testIntegerA;
intentInt = getIntent().getExtras().getInt("INTENT_EXTRA");
Now both intentInt and staticInt equal 42;

Global Objects accessible throughout Android application [duplicate]

This question already has answers here:
How to declare global variables in Android?
(17 answers)
Closed 2 years ago.
I have an application that uses a custom class. When the app is started I populate an instance of this class in the main activity with all the data it will hold.
Basic data is then shown in a ListView from which you can select a ListView item to see further information displayed in another Activity.
Currently, I am having to pass the data that is relevant to the new Activity to it by using:
intent.putExtra("NAME", value);
I want to implement a ViewPager so the user can easily switch between ListView items. Therefore the currently use method isn't very good as I only have the data for one entry at a time and would need to get back to the original Activity to get all the data again.
Is there a way to have my class objects globally available ANYWHERE in my application? I feel my applications code is getting bloated as I am overcoming these issues in bad code methods.
I've just looked into using:
MyApp myapp = ((MyApp)context.getApplication());
but this won't work unless I can pass the context around, which I'm not sure how to do??
In C# you'd create a static class that could handle this....
Thanks
Neil
You could have:
a static class holding your data (available until the process is killed)
a local service offering access to your data
the application class holding your data
a database mechanism to persist your data (in that case you'd simply pass IDs as intent extra)
All those options are more or less valid, it also depends on what you do with your data, where it comes from, ...
I think you are looking for a Singleton object. Create the custom class that holds all the data as a singleton object and access its data from anywhere in the code. Also, as this data may not be directly related to the UI, you should not be associating it with an Activity.
HTH,
Akshay

Categories