1

I am making an app that has a list of books that the user has, and I need to access it from multiple activities and fragments. I have a two problems:

  • I need to pass this List<Book> around to each activity and its very annoying.
  • I am not sure when to save the data to a file. I don't want users to lose their data but I also don't want to save it after every change.

I would use shared preferences, but they can't hold Parcelablees. I did see a library that lets you store data as strings by converting them them to json using Gson, but i'm affraid that will be too performance intensive. So summing up, where do I put data that needs to be accessed by all activities and be stored permanently?

1
  • use a custom ContentProvider
    – pskink
    Jun 29, 2014 at 11:39

3 Answers 3

1

There are some solutions:
1. You can use a server side services to store the data there (if you have server).
2. You can store the books list in database or to use GSON and store it as JSON string in Shared Preferences.
3. you can extend the Application class.

All the solutions above sole the accessibility problem.
The performances depends on your data size. You can also try to use less Activities and more Fragment so you need less database/ network calls.

0

For managing data that can be accessed from all activities i recommend using some kind of AppResources class which holds static variables (like your books List) that can be used by any app activity, fragment (In case the Context is needed just pass the Context to static to these methods).

Converting data to strings is not expensive in terms of performance, and so does storing data in the Shared Preferences which loads the data once to a map and afterwards each get or set takes < 1ms

0

you cat use singltone something like this

public class Data {

public Boolean m_b1 = false;
public Boolean m_b2 = false;
private List<String> m_oMyList;

private static Data x;

private Data()  {   
    m_oList = new ArrayList<String>();
}

public static Data X()
{
    if(x == null)
        x = new Data();
    return x;
}

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.