-3

I am working on a project and I want to transfer data across my application. Those data are on data model classes so sending arguments with intents made code big and hard to keep up since the classes are complex in structure.

So basically I decided to create static instances of those classes on a singleton class extending Application which helps me easily to set and get data from those objects. And it works.

Question:

I'm kinda new so I dont know if this is actually a good approach. I read some stuff here about it, but storing them on a local database as suggested is not fitting for my case. Is it any danger involved besides when Android decides to kill your application, on my approach for singleton class?

All advise and suggestions are more than welcome.

Thanks in advance.

Community
  • 1
  • 1
  • No. Nothing can be danger. If you want to store huge data then use database. Data will be lost when you uninstall the application. When your app start that application class would be launched first. So no data will be lost. – Piyush May 11 '17 at 10:20
  • I don't think there is any – Denny May 11 '17 at 10:23
  • @Piyush Please see the answer below – PEHLAJ May 11 '17 at 11:06
  • @Denny Please see the answer below – PEHLAJ May 11 '17 at 11:06
  • The OP stated "any danger involved **besides** when Android decides to kill your application", so I assume the OP knows that data will be discarded when the app is killed. – Denny May 11 '17 at 11:30

1 Answers1

1

You will loose data after Force Stop or killing the app.

Just for demo, you can verify this by performing following steps.

  1. Create a static int in your application class public static int count = 0;
  2. Log value of int and increment it Log.d("COUNT", String.valueOf(count)); count++;
  3. Destroy the app (left/right swipe from recent app) or 'Force stop' from app settings
  4. Restart the app and see the log for COUNT It will be 0, not 1

    package com.test.app;
    
    import android.app.Application;
    import android.util.Log;
    
    public class MyApplication extends Application {
    
       public static int count = 0;
    
       @Override
       public void onCreate() {
    
          Log.d("COUNT", String.valueOf(count));
          count++;
      }
    }
    

It is better to persist data somewhere. Android kills processes, it just depends on RAM state and other factors described in the documentation. In real world some devices are 'overloaded' with apps, so killing a background process is a normal situation. Yes, if user then decides to get the app up into foreground - the OS restores its stack including the Application instance, however there will not be your static data you count on unless you persisted it.

Please read the Limitations & Warnings section on this link.

http://www.developerphil.com/dont-store-data-in-the-application-object/

PEHLAJ
  • 9,980
  • 9
  • 41
  • 53