3

I know about singleton, but I can't use it in an Android project. I am a beginner in Android.

How and where can we use singleton in an Android project for large data? I have used it for simple values.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Deepanker Chaudhary
  • 1,694
  • 3
  • 15
  • 35
  • 1
    Questions asked on SO need to be about specific problems. Post some code or more information about the project you are working on. For more informtion refer to the [FAQ](http://stackoverflow.com/faq#questions) – MarioDS Sep 25 '12 at 15:03
  • 1
    First of all, Singleton is a pattern, not a method. Secondly, here on StackOverflow you usually post problems you encountered while developing something. In your case, you should first try to implement the Singleton pattern, and if you bump into problems just post code snippets and ask for help. – Raul Rene Sep 25 '12 at 15:04
  • As the others have said you need to post a specific question. Otherwie I'd recommend Google. – RossC Sep 25 '12 at 15:23

2 Answers2

41

Singleton in Android is the same as singleton in Java:

A basic singleton class example:

public class AppManager
{
    private static AppManager    _instance;

    private AppManager()
    {

    }

    public synchronized static AppManager getInstance()
    {
        if (_instance == null)
        {
            _instance = new AppManager();
        }
        return _instance;
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Givi
  • 3,283
  • 4
  • 20
  • 23
  • 7
    Actually, it is a lazy singleton and it needs to be stated, that it is _not_ Threadsafe! – Fildor Aug 29 '13 at 08:34
  • 1
    @Fildor it would make sense if you can also post a solution were you explain how to make a Singleton class in Java which is also thread safe, like this your comment doesn't help at all – Raffaeu Jan 06 '16 at 13:19
  • @Raffaeu Already 6 people think it is. I just wanted to add the info. The answer is still valid and correct. So no need to give one myself. – Fildor Jan 06 '16 at 20:14
4
  1. For "large data" use a database. Android gives you SQLite.
  2. Of course you can use singletons in Android. What makes you think you cannot?

For more information on the singleton pattern, read Singleton pattern.

For more information on SQLite in Android, read: Data and file storage overview.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fildor
  • 14,510
  • 4
  • 35
  • 67
  • 1
    The example in the answer is wrong. It is not thread-safe. There is no synchronization. You can search for singletons using enums for the most threat-safe implementations of singletons. – Matt Quigley Aug 28 '13 at 18:42
  • I did not give an example myself @MattQuigley ? Did you comment the wrong answer or are you talking about the wikipedia article on singleton? – Fildor Aug 29 '13 at 08:33
  • Umm sorry wrong answer! :/ – Matt Quigley Sep 01 '13 at 09:30