Load every objects saved as json - android

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();
}

Related

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);

Removing object from SharedPreferences in android

I am trying when press favorite button saving Object to SharedPreferences I have done it but When I press again favorite button to Remove Object to SharedPreferences I can't do this, I got old Objects without removed Objects I shared below used code for this process.How can I do this?
Saving and Removing to Favorite Object
String tag = holder.order.getTag().toString();
if (tag.equalsIgnoreCase("deactive")) {
//order_models.add(new RetroPhoto(1,dataList.get(position).getSurname(),dataList.get(position).getName()));
sharedPreference.addFavorite(context, dataList.get(position));
//dataList.get(position).getName();
holder.order.setTag("active");
holder.order.setImageResource(R.drawable.ic_favorite);
} else {
sharedPreference.removeFavorite(context, dataList.get(position));
//dataList.get(position).getName();
//dataList.remove(dataList.get(position));
holder.order.setTag("deactive");
holder.order.setImageResource(R.drawable.ic_favorite_outline);
}
public class SharedPreference {
public static final String PREFS_NAME = "NKDROID_APP";
public static final String FAVORITES = "Favorite";
public SharedPreference() {
super();
}
public void storeFavorites(Context context, List<RetroPhoto> favorites){
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public ArrayList<RetroPhoto> loadFavorites(Context context) {
SharedPreferences settings;
List<RetroPhoto> favorites;
settings =
context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
RetroPhoto[] favoriteItems =
gson.fromJson(jsonFavorites,RetroPhoto[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<RetroPhoto>(favorites);
} else
return null;
return (ArrayList<RetroPhoto>) favorites;
}
public void addFavorite(Context context, RetroPhoto beanSampleList) {
List<RetroPhoto> favorites = loadFavorites(context);
if (favorites == null){
favorites = new ArrayList<RetroPhoto>();
}
favorites.add(beanSampleList);
storeFavorites(context, favorites);
}
public void removeFavorite(Context context, RetroPhoto beanSampleList) {
ArrayList<RetroPhoto> favorites = loadFavorites(context);
if (favorites != null) {
favorites.remove(beanSampleList);
storeFavorites(context, favorites);
}
}
}
Getting Update LoadSharedPreferences
#Override
protected void onResume() {
super.onResume();
Log.e("onResume", "onResume Called");
if(order_models != null ) {
try {order_models = sharedPreference.loadFavorites(getApplicationContext());
order_adapter = new OrderAdapter(getApplicationContext(), order_models);
recycle.setAdapter(order_adapter);
} catch (NullPointerException e) {
e.printStackTrace();
}
order_adapter.notifyDataSetChanged();
}
}
you actually just add item in SharedPreference and remove item just from your array.
for removing item from SharedPreference you should use this code
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.edit().remove("key").apply();

shared preferences data that should save weather, not showing in the bookmarked activity

/// i have tried to make an weather app, its fully functional, however, i have implemented the code and the data does save as there are no errors in the logcat, however, when i look in the bookmarked activity the saved weather location is not there. is there that any can help me
public class SaveData {
private static final String TAG ="SaveData";
SharedPreferences preferences;
SharedPreferences.Editor editor;
Context context;
private static String prefName = "Pref";
public static ArrayList<HistoryObj> weatherHistoryList = new ArrayList<>();
//KEYS to store
public static String WEATHER_LIST_KEY= "WeatherIds";
public SaveData(Context context){
int PRIVATE_MODE = 0;
this.context = context;
preferences = context.getSharedPreferences(prefName,PRIVATE_MODE);
editor = preferences.edit();
// TinyDb is class to simplify storage of ArrayList in Shared Preferences
// getting book marked list from storage
weatherHistoryList = getWeatherList();
}
public ArrayList<HistoryObj> getWeatherList(){
Gson gson = new Gson();
ArrayList<String> objStrings = getListString(WEATHER_LIST_KEY);
ArrayList<HistoryObj> objects = new ArrayList<HistoryObj>();
for(String jObjString : objStrings){
HistoryObj value = gson.fromJson(jObjString, HistoryObj.class);
objects.add(value);
}
return objects;
}
public void saveWeatherList(ArrayList<HistoryObj> objArray){
checkForNullKey(WEATHER_LIST_KEY);
Gson gson = new Gson();
ArrayList<String> objStrings = new ArrayList<String>();
for(HistoryObj obj : objArray){
objStrings.add(gson.toJson(obj));
}
putListString(WEATHER_LIST_KEY, objStrings);
}
public ArrayList<String> getListString(String key) {
return new ArrayList<String>(Arrays.asList(TextUtils.split(preferences.getString(key, ""), "‚‗‚")));
}
public void putListString(String key, ArrayList<String> stringList) {
checkForNullKey(key);
String[] myStringList = stringList.toArray(new String[stringList.size()]);
preferences.edit().putString(key, TextUtils.join("‚‗‚", myStringList)).apply();
}
public void checkForNullKey(String key){
if (key == null){
throw new NullPointerException();
}
}
}

I have parsed the JSON Data in a Gridview and now I want to make it available offline

Is there a way to save the JSON data at the phone so that you can see the data if your phone is offline?
And what would be the best option to cache data ? SharedPreferences or SQLite database
Here is my code, which i am using to Parse JSON:
if (InternetConnection.checkConnection(getApplicationContext()))
new GetDataTask().execute();
class GetDataTask extends AsyncTask<Void, Void, Void> {
private static final String KEY_ICONURL ="http://droid.hol.es/images/"; ;
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Exit_View_Activity.this);
dialog.show();
}
#Nullable
#Override
protected Void doInBackground(Void... params) {
jsonObject = JSONParser.getDataFromWeb();
try {
if (jsonObject != null) {
if(jsonObject.length() > 0) {
JSONArray array = jsonObject.getJSONArray(Keys.KEY_INFO);
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
MyDataModel model = new MyDataModel();
JSONObject innerObject = array.getJSONObject(jIndex);
String name = innerObject.getString(Keys.KEY_NAME);
String viewtype = innerObject.getString(Keys.KEY_VIEWTYPE);
String image = innerObject.getString(Keys.KEY_ICON);
String Constantfilter = cat_id.replaceAll("[^0-9,]","");
Log.i("CONSTANT :",Constantfilter);
String[] numbers = Constantfilter.split(",");
for (int i=0;i<numbers.length;i++) {
Log.i("Number: ", numbers[i]);
if(numbers[i].equals(Keys.CONSTANT_CAT)) {
if (innerObject.getString(Keys.KEY_VIEWTYPE).equals("exit") || innerObject.getString(Keys.KEY_VIEWTYPE).equals("grid,exit")) {
model.setName(name);
model.setView_type(viewtype);
model.setId(id);
model.setImage(KEY_ICONURL + image);
model.setCat_id(cat_id);
model.setGrid_order_id(grid_order_id);
list.add(model);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
if (list.size() > 0) {
try {
adapter.notifyDataSetChanged();
dataPath = objectToFile(list);
editor.putString("key_name5",dataPath); // Saving string
// Save the changes in SharedPreferences
editor.commit(); // commit changes
// pref.getString("key_name5", null);
// list = (ArrayList<MyDataModel>)objectFromFile(dataPath);
Snackbar.make(findViewById(R.id.parentLayout), pref.getString("key_name5", null), Snackbar.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
If your data is structured and you want to access it in parts, you should better use SQLite.
If you just want to cache this data and you will use it completely in future better use SharedPref as you won't create schema for it hence SQLite will be a waste of resource and time both.
Hi You can create a class with any name for example I have created "LocalSharedPrefrences"
public class LocalSharedPrefrences {
private static final String strSharedPrefName = "AppPrefrence";
private static final String homePageJosn = "homePageJosn";
public static void saveHomePageJosnData(Context context, String JsonData) {
SharedPreferences pref = context.getSharedPreferences(strSharedPrefName, context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(homePageJosn, JsonData);
editor.commit();
}
public static String getHomePageJosnData(Context context) {
SharedPreferences pref = context.getSharedPreferences(strSharedPrefName, context.MODE_PRIVATE);
String JsonData = pref.getString(homePageJosn, "");
return JsonData;
}
}
And then you can use these functions to save and get json data as below:
LocalSharedPrefrences.saveHomePageJosnData(Context,JsonDataToSave);
String getJsonData = LocalSharedPrefrences.getHomePageJosnData(Context)
Yes, You can save your json data and and you can use it in offline by using SharedPreferences in android.
First you need to java class i.e. pojo class using Json, Convert that json into above class object.
To save that json -->
private SharedPreferences preferences;
preferences = context.getSharedPreferences("Name", Context.MODE_PRIVATE);
editor = preferences.edit();
editor.putString("your Key String", gson.toJson(here will be your json class object));
editor.commit();
To retrieve That Json-->
gson.fromJson(preferences.getString("your same Key String", null), your json class.class);
In this you will get object of that pojo class i.e. converted json class object.

ArrayList won't load when app is restarted

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;

Categories

Resources