Problems with singleton in android

I have an Android app where there are several actions. Each activity downloads xml / json feed, analyzes it and clicks on a singleton, usually as an arraialist.

However, after going through various actions, the singleton seems to die, and most of the previously loaded array lists are now empty. Why is this so? Is singleton the recommended practice for exchanging data between activities?

+3
source share
3 answers

Please browse this Android API FAQ topic , here you will surely find the most suitable solution for your problem (do you need short time, live or long-lasting data).

.

. , / ( /). , SharedPreferences .

/ SharedPreferences:

// the name with which to store the shared preference
public static final String PERSON_LIST = "my.personlist";

// a sample data structure that will be stored
public static final class Person
{
    private String name;
    private int age;

    public String toString() 
    {
        return name + "|" + age;
    }

    // splits the passed String parameter, and retrieves the members
    public static Person loadPersonFromString(final String personString)
    {
        final Person p = new Person();
        final String[] data = personString.split("|");
        p.name = data[0];
        p.age = Integer.parseInt(data[1]);
        return p;
    }
}

/**
 * Saves the current list of Persons in SharedPreferences 
 * @param persons: the list to save
 */
public void savePersonList(final ArrayList<Person> persons) 
{
    final SharedPreferences prefs = PreferenceManager.
        getDefaultSharedPreferences(getApplicationContext());
    final Editor editor = prefs.edit();
    final StringBuilder builder = new StringBuilder();
    for (final Person person : persons)
    {
        if (builder.length() > 0)
            builder.append("-Person-");
        builder.append(person.toString());
    }
    editor.putString(PERSON_LIST, builder.toString());
    editor.commit();
}

/**
 * Loads the list of Persons from SharedPreferences
 * @return the loaded list
 */
public ArrayList<Person> loadPersonList()
{
    final SharedPreferences prefs = PreferenceManager.
        getDefaultSharedPreferences(getApplicationContext());
    final ArrayList<Person> persons = new ArrayList<Menu.Person>();
    final String[] array = prefs.getString(PERSON_LIST, "").split("-Person-");
    for (final String personString : array) 
    {
        if (personString.length() > 0)
            persons.add(Person.loadPersonFromString(personString));
    }
    return persons;
}
+2

, . AnddroidManifest.

API Android @rekaszeru

Singleton class

, . , . , getInstance(), ; . , . , A setValue (3); B getValue(), .

+3

You can initialize the Application class. This class is present in all activities. You must declare it in the manifest file and have a life cycle similar to the action.

Documentation here: Application

Hope this helps.

Jquorreia

+1
source

All Articles