0

I have an arraylist and I want to save the data, when the app is closed / terminated / destroyed.

//Class SimpleBookManager.java is a singleton

private ArrayList<Book> allBooks = new ArrayList<Book>();

public Book getBook(int index){
    return allBooks.get(index);
}
public void saveChanges(){
    //Save the allBooks into memory
}
public void loadBooks(){
    //Load the allBooks into memory to the variable allBooks;
}

It is reached by writing SimpleBookManager.getSimpleBookManager().saveChanges(); in all the other classes in the package.

What is the best way to implement the method saveChanges() and loadBooks()? Could you give a brief example perhaps? I have read something about shared preferences in android but unfortunately I don't quite get it =)

David Hammen
  • 32,454
  • 9
  • 60
  • 108
anders
  • 1,535
  • 5
  • 19
  • 43

3 Answers3

0

Here is a SO question that has the code that you are looking for in it

To store an array in shared preferences look here -

However, if your app has a lot of books, or a lot of information about each book it would be better to use an SQLite database

Community
  • 1
  • 1
jcw
  • 5,132
  • 7
  • 45
  • 54
  • This is better as a comment since you have only linked to another question and not provider an answer yourself. – Sam Nov 17 '12 at 18:00
0

You can get an instance of SharedPreferences from any context within your app.

The following code saves a preferences with key "some_pref_key, and value "some_pref_value" into a file named "your_preference_file_name"

    SharedPreferences prefs = context.getSharedPreferences( "your_preference_file_name", MODE_APPEND );
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString( "some_pref_key", "some_pref_value" );
    editor.commit();

If you need to save other type of data, check the SharedPreferences.editor documentation

Robert Estivill
  • 12,369
  • 8
  • 43
  • 64
0

If you are going to store a single Data not more than 10,You can use shared preferences. Example : If you are going to store bookid, then shared preferences is enough.

But If you are trying to store Array of Objects / data, you should store it in Database only. It is convenient for dealing with large amount of data

RajeshVijayakumar
  • 10,281
  • 11
  • 57
  • 84