ArrayList won't load when app is restarted - android

I'm quite new to android, and I am having a problem with save and load data.
I am trying to make an app with a save and a load button, these buttons should save 2 ArrayLists with x- and y-coordinates.
I've tried doing it with SharedPreferences and it works until the apps restarts or the screen rotates.
When i take look in the app files the ArrayLists files are in the SharedPreferences folder, but my app will not load those if I press the load button.
Could anyone help we why this does not work when the app is restarted?
this is my load and save code:
public void saveArrayList(ArrayList aList, String s) {
SharedPreferences sharedPrefs = getSharedPreferences(prefs, MODE_PRIVATE);
editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(aList);
editor.putString(s, json);
editor.commit();
}
public void loadFloatList(ArrayList aList, String s) {
SharedPreferences sharedPrefs = getSharedPreferences(prefs, MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPrefs.getString(s, null);
Type type = new TypeToken<ArrayList<Float>>() {
}.getType();
aList = gson.fromJson(json, type);
}

Possible error; you are re-initializing gson and sharedPrefs which then takes a new state with the same key value. you should do this in onCreate.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPrefs = getSharedPreferences(PREFS, MODE_PRIVATE);
json = sharedPrefs.getString(JSON_KEY, "");
gson = new Gson();
}
it is best to use apply() because this save the value(s) of your sharedprefs as instance but commit() do this when the app closes.
public void saveArrayList(ArrayList aList) {
String json = gson.toJson(aList);
editor = sharedPrefs.edit();
editor.putString(JSON_KEY, json);
editor.apply();
}
public void loadFloatList(ArrayList aList, String s) {
json = sharedPrefs.getString(JSON_KEY, "");
Type type = new TypeToken<ArrayList<Float>>() {
}.getType();
aList = gson.fromJson(json, type);
}
note also the PREFS and JSON_KEY are final key values
private final String PREFS = "prefs";
private final String JSON_KEY = "json";
private SharedPreferences sharedPrefs;
private SharedPreferences.Editor editor;
private String json;
private Gson gson;

Related

Saving state of custom object ArrayList

I would like to restore the state of my array after a change of orientation. But I don't see an aproprieted function for this case. What shoul I do?
public class PuzzlePiece extends android.support.v7.widget.AppCompatImageView {
public int xCoord;
public int yCoord;
public int pieceWidth;
public int pieceHeight;
public boolean canMove = true;
public PuzzlePiece(Context context) {
super(context);
}
This is my onSave method
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArray("image", pieces);
}
}
And data initalization:
ArrayList<PuzzlePiece> pieces;
Basically speaking, you need to implement two methods: saveData() and loadData(). These will use GSON library in order to transform any object into a string and then re-create them back. Then you save and restore your objects where ever you need. You may do so when onPause() method is called, or anywhere else.
Here is the code:
Firstly, add the following dependency line in your build.gradle:
implementation 'com.google.code.gson:gson:2.8.6'
Then you write those two methods
private void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences id", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(arraylistOfYourObjects);
editor.putString("data_id", json);
editor.apply();
}
private void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences id", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("data_id", null);
Type type = new TypeToken<ArrayList<YourObjectClass>>() {}.getType();
arraylistOfYourObjects = gson.fromJson(json, type);
if(arraylistOfYourObjects == null){
arraylistOfYourObjects = new ArrayList<>();
}
}
Here is a link to a complete video on how to do the whole thing with allthe details:
https://www.youtube.com/watch?v=jcliHGR3CHo

How to store Array list in shared preferences and access in another fragment

I want to save this array list data in sharedpreferences and access that data in another fragment .Please Give me suggestion
Array list content given bellow
public String productname;
public String productunit;
public String productquantity;
public String productprice;
public String productdiscount;
Here is solution,
Step 1: Create a class like
SharedPreference
public static final String FAVORITES = "PRODUCTS";
private SharedPreferences settings;
private Editor editor;
public SharedPreference() {
super();
}
Now code to save ArrayList
public void saveArrayList(Context context, List<String> unread_ids) {
settings = context.getSharedPreferences(AppConfig.KEY_PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(unread_ids);
editor.putString(FAVORITES, jsonFavorites);
editor.apply();
}
Now code to get saved Arraylist
public ArrayList<String> getSavedList(Context context) {
// SharedPreferences settings;
List<String> unReadId;
settings = context.getSharedPreferences(AppConfig.KEY_PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, "");
Gson gson = new Gson();
String[] favoriteItems = gson.fromJson(jsonFavorites,
String[].class);
unReadId = Arrays.asList(favoriteItems);
unReadId = new ArrayList<>(unReadId);
} else {
return new ArrayList<String>();
}
return (ArrayList<String>) unReadId;
}
Code to save list:
sharedPreferences.saveArrayList(context, <YOUR LIST NAME>);
Now code to get your Arraylist in other Fragment
<LIST NAME> = sharedPreference.getSavedList(getActivity());
Before get and save array list you have to declare "sharedPreference" and create its object.
Hope this will help you.
I did something similar to this before Please check this code
private List<String> list; /// adding checked items to list
inside your OnCreate() add this line
list = new ArrayList<>(); /// checked items list
and to get array from model and store it local please use next.
int searchListLength = items.size();
for (int i = 0; i < searchListLength; i++) {
if (items.get(i).isChecked()) {
items.get(i).getId();
Log.d("listitem", String.valueOf("id=" + items.get(i).getId()));
list.add("id=" + items.get(i).getId());
}
}
StringBuilder stringBuilder = new StringBuilder();
for (String s : list) {
stringBuilder.append(s);
stringBuilder.append("&");
}
SharedPreferences notif_array = getSharedPreferences("items_array", Context.MODE_PRIVATE);
SharedPreferences.Editor editor_notaif = notif_array.edit();
editor_notaif.putString("id", stringBuilder.toString());
editor_notaif.apply();
Intent intent = new Intent(MainActivity.this, Filtered_Activity.class);
startActivity(intent);
Inside your another activity / fragment
private String new_result;
SharedPreferences notif_array = getSharedPreferences("items_array", Context.MODE_PRIVATE);
new_result = notif_array.getString("id", null);

How to get value of SharedPreferences android

I'm trying to use SharedPreferences here is what i do
public void StoreToshared(Object userData){
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(userData);
Log.d("data", " Setup --> "+json);
prefsEditor.putString("userinfo", json);
prefsEditor.commit();
}
Log.d result is like this
Setup --> {"nameValuePairs":{"userData":{"nameValuePairs":{"phone":"089688xxxxxxx",
"username":"username of User","flag":1,"Email":"mymail#mail.com",
"tipe":"TP001","Deskripsi":"Ini tentang gua","user_id":"USER001",
"password":"c83e4046a7c5d3c4bf4c292e1e6ec681","fullname":My fullname"}},"status":"true"}}
then i'm trying to retrieve it, in other activity here is what i do
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
String data = mPrefs.getString("userinfo", null);
Log.i("Text", "Here is the retrieve");
Log.i("data", " retrieve --> "+data);
}
and here how i open my other activity
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
With my script above, the result from my logcat , i only see like Log.d above. So my question is, how can i retrieve it ?
Try to add a key on your SharedPreferences:
public void StoreToshared(Object userData){
SharedPreferences mPrefs = getSharedPreferences("your_sp_key", MODE_PRIVATE); //add key
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(userData);
Log.d("data", " Setup --> "+json);
prefsEditor.putString("userinfo", json);
prefsEditor.commit();
}
Retrieval:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPrefs = getSharedPreferences("your_sp_key", MODE_PRIVATE); //add key
SharedPreferences.Editor prefsEditor = mPrefs.edit();
String data = mPrefs.getString("userinfo", null);
Log.i("Text", "Here is the retrieve");
Log.i("data", " retrieve --> "+data);
}
You can create 2 method:
// put value
public static void putPref(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
and
// get value
public static String getPref(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
then you can put value
putPref("userinfo", "/** user data json */", getApplicationContext());
and get value
String data = getPref("userinfo", getApplicationContext());
I hope it can help your problem!
You need to convert the string data from SharedPreferences back to a PoJo using Gson. Simply do this:
Object userData = new Gson().fromJson(data, Object.class);
I guess that should solve it.
The api: getPreferences will use the activity name to create an xml file if not exists. For example, assume StoreToshared method is put in activity: LoginActivity.java, it will create a file: LoginActivity.xml to store your pref data. Hence, when you go into other activity, let say its name is: MainActivity.java, getPreferences will look into file "MainActivity.xml" instead of "LoginActivity.xml", that is why you cannot retrieve your data.
The solution is to use: getSharedPreferences.
Hence your code can be modified as follow:
public void StoreToshared(Object userData) {
SharedPreferences mPrefs = getSharedPreferences("FILE_NAME",MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(userData);
Log.d("data", " Setup --> "+json);
prefsEditor.putString("userinfo", json);
prefsEditor.commit();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPrefs = getSharedPreferences("FILE_NAME",MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
String data = mPrefs.getString("userinfo", null);
Log.i("Text", "Here is the retrieve");
Log.i("data", " retrieve --> "+data);
}
Hope this help.
In year 2020,
Google has been released new data storage that is repleced of Shared Preference...
It' is developed with "Kotlin"
Source

Load every objects saved as json

I'm saving my playlists as json file, but oncreate I want to load every playlist already saved.
This is my save function;
void Kaydet(PLAYLIST liste_mp3)
{
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(liste_mp3);
prefsEditor.putString(liste_mp3.ad, json);
prefsEditor.commit();
}
And this is PLAYLIST class,
public class PLAYLIST
{
public String ad;
public ArrayList<MP3> liste;
public PLAYLIST(String ad1,ArrayList<MP3> liste1)
{
ad = ad1;
liste = liste1;
}
public String toString()
{
return ad;
}
public ArrayList<MP3> LISTE()
{
return liste;
}
}
This where I load specific one;
if(Yukle("A liste") != null) {
playlist.add(Yukle("A liste"));
} else { playlist.add(new PLAYLIST("A liste",a_liste)); }
and this is Load function,
PLAYLIST Yukle(String playlist_name)
{
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
Gson gson = new Gson();
String json = appSharedPrefs.getString(playlist_name, "");
PLAYLIST p = gson.fromJson(json, PLAYLIST.class);
return p;
}
I fixed my problem with that idea, I created a new function that saves names of all playlists as string arraylist, and load string arraylist of playlists' names then make a for-loop and load per playlist with name.
This is in onCreate()
ArrayList<String> yukleniyor = YukleHepsi();
if(yukleniyor != null) {
for (String isimler : yukleniyor) {
playlist.add(Yukle(isimler));
}
}
This function loads names:
ArrayList<String> YukleHepsi()
{
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
Gson gson = new Gson();
String json = appSharedPrefs.getString("isimler", "");
ArrayList<String> p = gson.fromJson(json, ArrayList.class);
return p;
}
And this function saves the names of all playlits,
void KaydetHepsi()
{
ArrayList<String> isimler = new ArrayList<String>();
for(PLAYLIST p: playlist)
{
if(p.ad != "None") {
isimler.add(p.ad);
}
}
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(isimler);
prefsEditor.putString("isimler", json);
prefsEditor.commit();
}

Put and get String array from shared preferences

I need to save on shared preferences some array of Strings and after that to get them.
I tried this :
prefsEditor.putString(PLAYLISTS, playlists.toString()); where playlists is a String[]
and to get :
playlist= myPrefs.getString(PLAYLISTS, "playlists"); where playlist is a String but it is not working.
How can I do this?
You can create your own String representation of the array like this:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < playlists.length; i++) {
sb.append(playlists[i]).append(",");
}
prefsEditor.putString(PLAYLISTS, sb.toString());
Then when you get the String from SharedPreferences simply parse it like this:
String[] playlists = playlist.split(",");
This should do the job.
From API level 11 you can use the putStringSet and getStringSet to store/retrieve string sets:
SharedPreferences pref = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putStringSet(SOME_KEY, someStringSet);
editor.commit();
SharedPreferences pref = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
Set<String> someStringSet = pref.getStringSet(SOME_KEY);
You can use JSON to serialize your array as a string and store it in the preferences. See my answer and sample code for a similar question here:
How can write code to make sharedpreferences for array in android?
HashSet<String> mSet = new HashSet<>();
mSet.add("data1");
mSet.add("data2");
saveStringSet(context, mSet);
where
public static void saveStringSet(Context context, HashSet<String> mSet) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sp.edit();
editor.putStringSet(PREF_STRING_SET_KEY, mSet);
editor.apply();
}
and
public static Set<String> getSavedStringSets(Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getStringSet(PREF_STRING_SET_KEY, null);
}
private static final String PREF_STRING_SET_KEY = "string_set_key";
Store array list in prefrence using this easy function, if you want more info Click here
public static void storeSerializeArraylist(SharedPreferences sharedPreferences, String key, ArrayList tempAppArraylist){
SharedPreferences.Editor editor = sharedPreferences.edit();
try {
editor.putString(key, ObjectSerializer.serialize(tempAppArraylist));
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
And how to get stored array list from prefrence
public static ArrayList getSerializeArraylist(SharedPreferences sharedPreferences, String key){
ArrayList tempArrayList = new ArrayList();
try {
tempArrayList = (ArrayList) ObjectSerializer.deserialize(sharedPreferences.getString(key, ObjectSerializer.serialize(new ArrayList())));
} catch (IOException e) {
e.printStackTrace();
}
return tempArrayList;
}

Categories

Resources