603

I am creating an application which requires login. I created the main and the login activity.

In the main activity onCreate method I added the following condition:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ...

    loadSettings();
    if(strSessionString == null)
    {
        login();
    }
    ...
}

The onActivityResult method which is executed when the login form terminates looks like this:

@Override
public void onActivityResult(int requestCode,
                             int resultCode,
                             Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode)
    {
        case(SHOW_SUBACTICITY_LOGIN):
        {
            if(resultCode == Activity.RESULT_OK)
            {

                strSessionString = data.getStringExtra(Login.SESSIONSTRING);
                connectionAvailable = true;
                strUsername = data.getStringExtra(Login.USERNAME);
            }
        }
    }

The problem is the login form sometimes appears twice (the login() method is called twice) and also when the phone keyboard slides the login form appears again and I guess the problem is the variable strSessionString.

Does anyone know how to set the variable global in order to avoid login form appearing after the user already successfully authenticates?

Willi Mentzel
  • 21,499
  • 16
  • 88
  • 101
Niko Gamulin
  • 63,517
  • 91
  • 213
  • 274
  • a good tutorial on how to handle an activity state using saved instance state bundle http://www.quicktips.in/handling-activity-state-using-saved-instance-state-bundle/ – Deepak Swami Aug 25 '15 at 02:45

17 Answers17

960

I wrote this answer back in '09 when Android was relatively new, and there were many not well established areas in Android development. I have added a long addendum at the bottom of this post, addressing some criticism, and detailing a philosophical disagreement I have with the use of Singletons rather than subclassing Application. Read it at your own risk.

ORIGINAL ANSWER:

The more general problem you are encountering is how to save state across several Activities and all parts of your application. A static variable (for instance, a singleton) is a common Java way of achieving this. I have found however, that a more elegant way in Android is to associate your state with the Application context.

As you know, each Activity is also a Context, which is information about its execution environment in the broadest sense. Your application also has a context, and Android guarantees that it will exist as a single instance across your application.

The way to do this is to create your own subclass of android.app.Application, and then specify that class in the application tag in your manifest. Now Android will automatically create an instance of that class and make it available for your entire application. You can access it from any context using the Context.getApplicationContext() method (Activity also provides a method getApplication() which has the exact same effect). Following is an extremely simplified example, with caveats to follow:

class MyApp extends Application {

  private String myState;

  public String getState(){
    return myState;
  }
  public void setState(String s){
    myState = s;
  }
}

class Blah extends Activity {

  @Override
  public void onCreate(Bundle b){
    ...
    MyApp appState = ((MyApp)getApplicationContext());
    String state = appState.getState();
    ...
  }
}

This has essentially the same effect as using a static variable or singleton, but integrates quite well into the existing Android framework. Note that this will not work across processes (should your app be one of the rare ones that has multiple processes).

Something to note from the example above; suppose we had instead done something like:

class MyApp extends Application {

  private String myState = /* complicated and slow initialization */;

  public String getState(){
    return myState;
  }
}

Now this slow initialization (such as hitting disk, hitting network, anything blocking, etc) will be performed every time Application is instantiated! You may think, well, this is only once for the process and I'll have to pay the cost anyways, right? For instance, as Dianne Hackborn mentions below, it is entirely possible for your process to be instantiated -just- to handle a background broadcast event. If your broadcast processing has no need for this state you have potentially just done a whole series of complicated and slow operations for nothing. Lazy instantiation is the name of the game here. The following is a slightly more complicated way of using Application which makes more sense for anything but the simplest of uses:

class MyApp extends Application {

  private MyStateManager myStateManager = new MyStateManager();

  public MyStateManager getStateManager(){
    return myStateManager ;
  }
}

class MyStateManager {

  MyStateManager() {
    /* this should be fast */
  }

  String getState() {
    /* if necessary, perform blocking calls here */
    /* make sure to deal with any multithreading/synchronicity issues */

    ...

    return state;
  }
}

class Blah extends Activity {

  @Override
  public void onCreate(Bundle b){
    ...
    MyStateManager stateManager = ((MyApp)getApplicationContext()).getStateManager();
    String state = stateManager.getState();
    ...
  }
}

While I prefer Application subclassing to using singletons here as the more elegant solution, I would rather developers use singletons if really necessary over not thinking at all through the performance and multithreading implications of associating state with the Application subclass.

NOTE 1: Also as anticafe commented, in order to correctly tie your Application override to your application a tag is necessary in the manifest file. Again, see the Android docs for more info. An example:

<application
     android:name="my.application.MyApp" 
     android:icon="..."
     android:label="...">
</application>

NOTE 2: user608578 asks below how this works with managing native object lifecycles. I am not up to speed on using native code with Android in the slightest, and I am not qualified to answer how that would interact with my solution. If someone does have an answer to this, I am willing to credit them and put the information in this post for maximum visibility.

ADDENDUM:

As some people have noted, this is not a solution for persistent state, something I perhaps should have emphasized more in the original answer. I.e. this is not meant to be a solution for saving user or other information that is meant to be persisted across application lifetimes. Thus, I consider most criticism below related to Applications being killed at any time, etc..., moot, as anything that ever needed to be persisted to disk should not be stored through an Application subclass. It is meant to be a solution for storing temporary, easily re-creatable application state (whether a user is logged in for example) and components which are single instance (application network manager for example) (NOT singleton!) in nature.

Dayerman has been kind enough to point out an interesting conversation with Reto Meier and Dianne Hackborn in which use of Application subclasses is discouraged in favor of Singleton patterns. Somatik also pointed out something of this nature earlier, although I didn't see it at the time. Because of Reto and Dianne's roles in maintaining the Android platform, I cannot in good faith recommend ignoring their advice. What they say, goes. I do wish to disagree with the opinions, expressed with regards to preferring Singleton over Application subclasses. In my disagreement I will be making use of concepts best explained in this StackExchange explanation of the Singleton design pattern, so that I do not have to define terms in this answer. I highly encourage skimming the link before continuing. Point by point:

Dianne states, "There is no reason to subclass from Application. It is no different than making a singleton..." This first claim is incorrect. There are two main reasons for this. 1) The Application class provides a better lifetime guarantee for an application developer; it is guaranteed to have the lifetime of the application. A singleton is not EXPLICITLY tied to the lifetime of the application (although it is effectively). This may be a non-issue for your average application developer, but I would argue this is exactly the type of contract the Android API should be offering, and it provides much more flexibility to the Android system as well, by minimizing the lifetime of associated data. 2) The Application class provides the application developer with a single instance holder for state, which is very different from a Singleton holder of state. For a list of the differences, see the Singleton explanation link above.

Dianne continues, "...just likely to be something you regret in the future as you find your Application object becoming this big tangled mess of what should be independent application logic." This is certainly not incorrect, but this is not a reason for choosing Singleton over Application subclass. None of Diane's arguments provide a reason that using a Singleton is better than an Application subclass, all she attempts to establish is that using a Singleton is no worse than an Application subclass, which I believe is false.

She continues, "And this leads more naturally to how you should be managing these things -- initializing them on demand." This ignores the fact that there is no reason you cannot initialize on demand using an Application subclass as well. Again there is no difference.

Dianne ends with "The framework itself has tons and tons of singletons for all the little shared data it maintains for the app, such as caches of loaded resources, pools of objects, etc. It works great." I am not arguing that using Singletons cannot work fine or are not a legitimate alternative. I am arguing that Singletons do not provide as strong a contract with the Android system as using an Application subclass, and further that using Singletons generally points to inflexible design, which is not easily modified, and leads to many problems down the road. IMHO, the strong contract the Android API offers to developer applications is one of the most appealing and pleasing aspects of programming with Android, and helped lead to early developer adoption which drove the Android platform to the success it has today. Suggesting using Singletons is implicitly moving away from a strong API contract, and in my opinion, weakens the Android framework.

Dianne has commented below as well, mentioning an additional downside to using Application subclasses, they may encourage or make it easier to write less performance code. This is very true, and I have edited this answer to emphasize the importance of considering perf here, and taking the correct approach if you're using Application subclassing. As Dianne states, it is important to remember that your Application class will be instantiated every time your process is loaded (could be multiple times at once if your application runs in multiple processes!) even if the process is only being loaded for a background broadcast event. It is therefore important to use the Application class more as a repository for pointers to shared components of your application rather than as a place to do any processing!

I leave you with the following list of downsides to Singletons, as stolen from the earlier StackExchange link:

  • Inability to use abstract or interface classes;
  • Inability to subclass;
  • High coupling across the application (difficult to modify);
  • Difficult to test (can't fake/mock in unit tests);
  • Difficult to parallelize in the case of mutable state (requires extensive locking);

and add my own:

  • Unclear and unmanageable lifetime contract unsuited for Android (or most other) development;
Community
  • 1
  • 1
sooniln
  • 14,333
  • 4
  • 27
  • 34
  • 98
    Thank you Soonil -- these kinds of answers are the reason why I love Stack Overflow so much. GREAT JOB! – JohnnyLambada Sep 25 '09 at 16:57
  • 5
    For anyone wondering how to "specify that class in the application tag in your manifest", there are, as of this writing, two other answers for this question that describe how to do it (use android:name), one by ebuprofen and one by Mike Brown. – Tyler Collier Nov 11 '10 at 17:09
  • 2
    @Soonil: I just added an answer, which actually should have been a comment to your answer. However it was too long to place it as a comment here. – Vit Khudenko Jan 09 '11 at 21:52
  • 9
    Soonil, your answer is right, but could you notice that we should add into Android Manifest file? – anticafe Feb 19 '11 at 23:40
  • how would one call getApplicationContext() or getApplication() inside of a typical onClickListener? ` loginButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) {}});` thanks in advance! – Cole Apr 15 '11 at 22:27
  • Hello, I have create the class wich extends Application and include in the manifest, But I get this exception:ERROR/AndroidRuntime(10404): Caused by: java.lang.ClassCastException: android.app.Application – Dayerman May 11 '11 at 08:44
  • I also got ClassCase Exception. Any thoughts ? – Chinthaka Oct 16 '11 at 17:15
  • @Soonil Thank you! Was having many of these kind of problems, this solved it. – Neeta Dec 20 '11 at 18:36
  • I'm also getting a CastException when I try to cast the context object I get from getApplicationContext() to MyApp. If I do not cast it and just insert it into a regular Context variable it works fine, but if I try to cast it, it just doesn't work. Does anybody know of a solution? – Dror Jan 06 '12 at 14:10
  • how can i get this gloabal variable in non activity class? – βhargavḯ May 19 '12 at 05:11
  • also note `class` must be `public` – Cfr Dec 04 '12 at 23:27
  • The application object is guaranteed to be created before all your activities and kept until all your activities are destroyed. You can't use it for global state though because Android can destroy all your activities AND the application object when your application is in the background. – Jared Kells Apr 19 '13 at 03:47
  • 1
    If you receive a phone call OR switch applications which could just mean launching a browser intent the OS can optionally destroy all your activities, destroy your application object and kill your hosting process. When you end the phone call a new process will start, a new application object will be created and a new activity will be created. The only state you will get back will be in the bundle passed into onCreate. All your static variables will be null and your Application object will be a brand new instance. – Jared Kells Apr 19 '13 at 03:47
  • 2
    Looks like as explained here https://plus.google.com/u/0/117230458394250799679/posts/DsfpW51Vvow by one of the core android engineers, the use of Application for storing data instead of a singleton is discouraged. – Dayerman Jul 26 '13 at 12:55
  • 2
    @Somatik From: developer.android.com/reference/android/app/Application.html "There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. ..." -- That's a really, really strange thing for Google to write. As sooniln has explained there is no compelling reason to favor singletons. One could understand it if they felt the need to indicate that singletons are an alternative, but not to claim they are better. One gets the impression someone has an obsession with singletons. – RenniePet Sep 27 '13 at 19:17
  • "Tangled mess" - I think Diane is saying that putting all globals in the Application violates the principle of locality: in many cases, the global could be defined (as a singleton) in a related module, where you can see better how it is used. If you use a singleton in a class file, then the code is more, well, _modular_ (as on developer.android.com). – Lucy Nov 08 '13 at 21:30
  • @Lucy If developers are seeking to make components globally accessible, whether through singletons or the Application pattern, it's generally because the component needs to be globally (or close to globally) accessible. For instance, a persistent network component, or login information, as in the original question needs to be available from all parts of the application. Of course, the component itself should be modular, but the question here is how to -expose- the component to other parts of the app, and I remain convinced the Application pattern is a better solution than singletons. – sooniln Jan 15 '14 at 22:12
  • @Tenfour04 Most of those bullet points are more general criticisms of singletons which have little to do with Application subclasses or Android development. I point out those general criticisms, and add my own specific criticism; that Application is an Android affordance, whereas a singleton is a Java affordance. For an Android developer there is no strong guarantee that singleton is tied to your application (though it is practice of course), and there is that guarantee for Application. – sooniln Feb 05 '14 at 00:43
  • 2
    @sooniln: Static data members have the same lifetime as does an `Application` and your `ContentProvider` instances: the lifetime of the process. After all, an `Application` is merely a static data member of a framework class. – CommonsWare Apr 02 '14 at 11:59
  • 13
    Let me repeat one more time, you should not be using Application for globals. It is of no use, gives no benefits over singletons, and can be actively harmful, such as harming the performance of launching your process. At the time Application is being created, you have no idea what your process is being created for. By lazily initializing singletons as needed, you only need to do work that is necessary. For example, if your process is being launched to handle a broadcast about some background event, there is no reason to initialize whatever global state is needed by your UI. – hackbod Apr 08 '14 at 15:18
  • 5
    On top of that, if your application is using multiple processes, an Application object means you need to do all of that global initialization (time and memory consumption) in all of them. Ouch. And there are certain situations where your Application object will not be created, in particular during a restore, that can trip you up. – hackbod Apr 08 '14 at 15:20
  • 15
    Also, let's be really clear here -- all of your arguments against singletons are perfectly valid, when we are talking about situations where you are actually choosing between a singleton and another approach that isn't a global; singletons are globals, with all the caveats about globals that apply. However, *Application is also a singleton*. You aren't escaping those problems by switching to subclassing Application, an Application is exactly the same as a singleton (but worse), it is just letting you to trick yourself that you are doing something more clean. But you aren't. – hackbod Apr 08 '14 at 15:31
  • An Application is injected in to the context, that allows you to essentially pass any implementation of Application that you desire. Dependency Injection (DI). This is the important difference as it allows us to test our Activities in isolation, and further inject implementations of modules from our custom Application. Singletons couple classes together, requiring you to always ship one class with the other. This is not modular as you can't easily supply another implementation of the singleton. DI would be the most compelling reason to avoid singletons and favour Application sub-classing. – Joony Apr 14 '14 at 10:00
  • cool ! Apart from being useful just wondering how much points you would have earned in the upvotes and accepting this as an answer :) :) ! – Raulp Apr 17 '14 at 11:22
  • @hackbod Thanks for the response, wish I'd seen it earlier! I agree with your listed problems with Application subclassing, but I would argue that these are A) design deficiencies in the Application class (not trying to assign blame, we all know how hard it is to make perfect initial choices, and then they become baked in and impossible to change...) and B) you seem to be equating lazy initialization -only- with singletons when it is perfectly possible to employ it with Application subclasses. My initial answer should have emphasized that more, but it was a very general answer at the time. – sooniln May 13 '14 at 22:20
  • @hackbod The way I've always used Application subclasses is as a central reference for various application services (UI related, network related, etc...). Where each service is self contained and not controlled by the Application subclass, and in fact lazily instantiated itself. My example in the answer unfortunately didn't include that as I was trying to simplify it down to the essentials. I've changed the example to better reflect this. For example, while an Application has a reference to say MyNetworkManager, MyNetworkManager may perform its instantiation and work lazily. – sooniln May 13 '14 at 22:27
  • @hackbod I agree lazy initialization is a very good thing, but there is no need to rely on Java singletons for this, you can lazy initialize just as well through the Application subclass, in addition to getting all the benefits of not using singletons. You'll pay a slight additional cost in object construction, but if designed correctly, I believe this should be negligible, and well worth the benefits of avoiding singletons. I've changed my original answer to emphasize this more. – sooniln May 13 '14 at 22:30
  • 1
    I always used Application for globals but thanks to your such contradictory responses, the picture is clear now. To avoid longer "(App)context.getApplicationContext()" I had static method "App.from(context)", which already suggests there is nothing special about my App class - it can be any singleton, totally unrelated to Android framework. So I stopped using Application class - it's like dumping all your constants in a class called Constants, and yes, if you're not careful, app startup will get bloated. Thanks again! Very useful post. – myself Nov 30 '14 at 10:32
  • PS Be careful sooniln – myself Nov 30 '14 at 10:36
  • so great! I also have these problems,I understand it by this responses. – zys Jan 13 '16 at 09:14
  • I have to use ```(Globals) getApplication()``` in each method of my activities that requires global data? It is not possible to use static methods? (And use ```Globals.getMyVariable()```). – JCarlosR Aug 13 '16 at 19:35
  • I cannot find any **official docs** that definitively say whether or not an application may be destroyed for automatic recreation later (à la activities and fragments). The following page seems to be the only one discussing application destruction. I wish the Android team would once and for all clarify who is right and who is wrong by explicitly saying whether or not apps destroyed in the background may later be recreated in the background. Which position is the "myth" and which is not? https://developer.android.com/guide/components/activities/process-lifecycle – Joe Lapp May 20 '19 at 22:11
155

Create this subclass

public class MyApp extends Application {
  String foo;
}

In the AndroidManifest.xml add android:name

Example

<application android:name=".MyApp" 
       android:icon="@drawable/icon" 
       android:label="@string/app_name">
Nikhil
  • 15,872
  • 20
  • 61
  • 80
Guillaume
  • 1,671
  • 1
  • 10
  • 7
142

The suggested by Soonil way of keeping a state for the application is good, however it has one weak point - there are cases when OS kills the entire application process. Here is the documentation on this - Processes and lifecycles.

Consider a case - your app goes into the background because somebody is calling you (Phone app is in the foreground now). In this case && under some other conditions (check the above link for what they could be) the OS may kill your application process, including the Application subclass instance. As a result the state is lost. When you later return to the application, then the OS will restore its activity stack and Application subclass instance, however the myState field will be null.

AFAIK, the only way to guarantee state safety is to use any sort of persisting the state, e.g. using a private for the application file or SharedPrefernces (it eventually uses a private for the application file in the internal filesystem).

dvd
  • 1,440
  • 1
  • 16
  • 24
Vit Khudenko
  • 27,639
  • 10
  • 56
  • 86
  • 10
    +1 for persisting with `SharedPreferences`; this is how I've seen it done. I do find it strange to abuse the preference system for saved state, but it works so well that the issue becomes just a question of terminology. – Cheezmeister Feb 22 '11 at 17:07
  • @Cheezmeister: +1. I have used SharedPreferences for saving & accessing state too. It is global & it persists. The only downside might be the extra split-second it takes to read/write. – OceanBlue Apr 15 '11 at 15:23
  • 1
    could you please post the code (or provide a link to an explanation) as to how SharedPreferences is used to solve the problem that Arhimed describes – Someone Somewhere May 04 '11 at 23:47
  • 2
    Preferences, database, file serialization, etc. Each activity can maintain state if they use the onSaveInstanceState but it won't help if the user backs out of the activity and which removes it from the history stack, force closes, or turns off their device. – Darren Hinderer Jun 23 '11 at 16:10
  • 1
    This behaviour is very annoying - it wouldn't be so bad if the onTerminate() method of your application was called so you could deal with the situation elegantly. – Dean Wild Jun 28 '12 at 14:30
  • Any examples om this please? – M.ES Dec 10 '12 at 14:57
  • 2
    This is the correct answer in my opinion. It's a bug to rely on the same application instance existing across activities. In my experience it's quite common for Android to completely tear down and recreate your entire process while you are backgrounded. Being backgrounded could just mean launching a camera intent, browser intent or receiving a phone call. – Jared Kells Apr 19 '13 at 03:51
  • 1
    You don't have to abuse the shared preferences if the data being persisted is only used in that process instance. When Android kills an Activity, it invokes onSaveInstanceState(Bundle). The data in the Bundle object is stored in System Memory, and that's one area of memory that won't go away as long as your process is in memory. The data can be later used in onCreate(Bundle) or onRestoreInstanceState(Bundle). Unless you have data that must be persisted beyond the process, you should use the bundle. Although negligible, the bundle is faster since its in main memory & not on disk. – Ryhan Aug 04 '13 at 07:35
  • Excellent. This is exactly what is happening with my App, after returning after long time in the background, it tries to restore Activities but data is null inside my Application objects which is causing NPE! – braincell Jan 07 '14 at 17:22
  • I cannot find any official docs that say an application may later be recreated after being destroyed. The only page I can find discussing the matter is this one, and it only mentions conditions under which it will destroy an app. Even so, it also does not say that it won't later attempt to recreate an app. I think we're confused because the docs are insufficient. https://developer.android.com/guide/components/activities/process-lifecycle – Joe Lapp May 20 '19 at 22:01
25

Just a note ..

add:

android:name=".Globals"

or whatever you named your subclass to the existing <application> tag. I kept trying to add another <application> tag to the manifest and would get an exception.

Gimbl
  • 1,420
  • 1
  • 13
  • 22
  • Hi, Gimbl. I had the same problem. I also had my own tag and, when I try to add another tag I had the same problem as you (exception message). But I did what you mentioned, and it didn't work. I add android:name=".GlobalClass" to my tag but it doesn't work. Can you fully explain how you solved it?? – Sonhja Sep 23 '11 at 10:35
  • 3
    **Good** . **Bad** – Gimbl Sep 26 '11 at 15:16
13

What about ensuring the collection of native memory with such global structures?

Activities have an onPause/onDestroy() method that's called upon destruction, but the Application class has no equivalents. What mechanism are recommended to ensure that global structures (especially those containing references to native memory) are garbage collected appropriately when the application is either killed or the task stack is put in the background?

Nikhil
  • 15,872
  • 20
  • 61
  • 80
user608578
  • 191
  • 1
  • 5
  • 1
    The obvious solution is to implement the [Closeable](http://docs.oracle.com/javase/7/docs/api/java/io/Closeable.html) interface for your objects responsible for native resources and ensure they are managed by a try-with-resources statement or something else. Worst case you can always use an object finalizer. – sooniln May 14 '14 at 03:30
12

I couldn't find how to specify the application tag either, but after a lot of Googling, it became obvious from the manifest file docs: use android:name, in addition to the default icon and label in the application stanza.

android:name The fully qualified name of an Application subclass implemented for the application. When the application process is started, this class is instantiated before any of the application's components.

The subclass is optional; most applications won't need one. In the absence of a subclass, Android uses an instance of the base Application class.

Mike Brown
  • 121
  • 1
  • 2
5

Just you need to define an application name like below which will work:

<application
  android:name="ApplicationName" android:icon="@drawable/icon">
</application>
kenju
  • 5,248
  • 1
  • 36
  • 40
Anand
  • 1,275
  • 1
  • 12
  • 17
4

Like there was discussed above OS could kill the APPLICATION without any notification (there is no onDestroy event) so there is no way to save these global variables.

SharedPreferences could be a solution EXCEPT you have COMPLEX STRUCTURED variables (in my case I had integer array to store the IDs that the user has already handled). The problem with the SharedPreferences is that it is hard to store and retrieve these structures each time the values needed.

In my case I had a background SERVICE so I could move this variables to there and because the service has onDestroy event, I could save those values easily.

Adorjan Princz
  • 11,208
  • 3
  • 32
  • 25
4

If some variables are stored in sqlite and you must use them in most activities in your app. then Application maybe the best way to achieve it. Query the variables from database when application started and store them in a field. Then you can use these variables in your activities.

So find the right way, and there is no best way.

kenju
  • 5,248
  • 1
  • 36
  • 40
user716653
  • 41
  • 2
3

You can have a static field to store this kind of state. Or put it to the resource Bundle and restore from there on onCreate(Bundle savedInstanceState). Just make sure you entirely understand Android app managed lifecycle (e.g. why login() gets called on keyboard orientation change).

yanchenko
  • 53,981
  • 33
  • 142
  • 163
2

DO N'T Use another <application> tag in manifest file.Just do one change in existing <application> tag , add this line android:name=".ApplicationName" where, ApplicationName will be name of your subclass(use to store global) that, you is about to create.

so, finally your ONE AND ONLY <application> tag in manifest file should look like this :-

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat.NoActionBar"
        android:name=".ApplicationName"
        >
kumar kundan
  • 1,857
  • 1
  • 23
  • 36
1

you can use Intents , Sqlite , or Shared Preferences . When it comes to the media storage, like documents , photos , and videos, you may create the new files instead.

Raju yourPepe
  • 2,588
  • 12
  • 60
  • 124
1

You can do this using two approaches:

  1. Using Application class
  2. Using Shared Preferences

  3. Using Application class

Example:

class SessionManager extends Application{

  String sessionKey;

  setSessionKey(String key){
    this.sessionKey=key;
  }

  String getSessisonKey(){
    return this.sessionKey;
  }
}

You can use above class to implement login in your MainActivity as below. Code will look something like this:

@override 
public void onCreate (Bundle savedInstanceState){
  // you will this key when first time login is successful.
  SessionManager session= (SessionManager)getApplicationContext();
  String key=getSessisonKey.getKey();
  //Use this key to identify whether session is alive or not.
}

This method will work for temporary storage. You really do not any idea when operating system is gonna kill the application, because of low memory. When your application is in background and user is navigating through other application which demands more memory to run, then your application will be killed since operating system given more priority to foreground processes than background. Hence your application object will be null before user logs out. Hence for this I recommend to use second method Specified above.

  1. Using shared preferences.

    String MYPREF="com.your.application.session"
    
    SharedPreferences pref= context.getSharedPreferences(MyPREF,MODE_PRIVATE);
    
    //Insert key as below:
    
    Editot editor= pref.edit();
    
    editor.putString("key","value");
    
    editor.commit();
    
    //Get key as below.
    
    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    
    String key= getResources().getString("key");
    
bg17aw
  • 2,353
  • 1
  • 17
  • 25
Krishna
  • 2,103
  • 14
  • 22
0
class GlobaleVariableDemo extends Application {

    private String myGlobalState;

    public String getGlobalState(){
     return myGlobalState;
    }
    public void setGlobalState(String s){
     myGlobalState = s;
    }
}

class Demo extends Activity {

@Override
public void onCreate(Bundle b){
    ...
    GlobaleVariableDemo appState = ((GlobaleVariableDemo)getApplicationContext());
    String state = appState.getGlobalState();
    ...
    }
}
kenju
  • 5,248
  • 1
  • 36
  • 40
Vaishali Sutariya
  • 4,834
  • 28
  • 32
0

On activity result is called before on resume. So move you login check to on resume and your second login can be blocked once the secomd activity has returned a positive result. On resume is called every time so there is not worries of it not being called the first time.

user3044482
  • 388
  • 3
  • 11
0

The approach of subclassing has also been used by the BARACUS framework. From my point of view subclassing Application was intended to work with the lifecycles of Android; this is what any Application Container does. Instead of having globals then, I register beans to this context an let them beeing injected into any class manageable by the context. Every injected bean instance actually is a singleton.

See this example for details

Why do manual work if you can have so much more?

gorefest
  • 739
  • 6
  • 19
0

You could create a class that extends Application class and then declare your variable as a field of that class and providing getter method for it.

public class MyApplication extends Application {
    private String str = "My String";

    synchronized public String getMyString {
        return str;
    }
}

And then to access that variable in your Activity, use this:

MyApplication application = (MyApplication) getApplication();
String myVar = application.getMyString();
Amit Tiwari
  • 3,478
  • 6
  • 26
  • 69