Assuming a method of mine was passed a Bundle already filled with data to be saved, is there a way to save it to SharedPreferences without taking it apart to ints, floats, Strings, etc.?
I prefer the convenience of writing/committing it all in "one fell swoop", so if this isn't possible using SharedPreferences, what other persistent storage approach would you recommend?
SharedPreferences are serialized to XML, which is why you can only use simple types. You'll either have to do your own conversion of the bundle to individual SharePreferences properties or serialize the bundle some other way to disk.
Here's a good reference document discussing the various possibilities of storing data in Android: http://developer.android.com/guide/topics/data/data-storage.html
as far as I know, you can save only primitive data (and their wrappers) to SharedPreferences
why don't you create your own helper method which will iterate through Bundle and save all values from it to SharedPreferences?
Note: If you are using Gson in your project then I think this is a better solution.
I simply used Gson from Google to serialize the specified object into its equivalent JSON representation:
Use this dependency
implementation 'com.google.code.gson:gson:2.8.6'
Code:
Gson gson = new Gson();
String dataToJson = gson.toJson(modelObj);
Then I stored dataToJson as a string in SharedPreferences.Simple!
At the time of string extraction:
String myStoredVal = Value stored in SharedPreference.
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
Gson gson = builder.create();
MyModel modelObj = gson.fromJson(prodDataStr, MyModel.class);
Related
I am making an app, where there is a searchbox in Main Activity and bottom navigation. In searchbox, the user choose te location, then sends the query to the weather API. I want to pass the object, which is the response from the API, to all fragments in my app. What is the easiest way to do that?
You can use a ViewModel to store your data. Also, using MutableLiveData you can dynamically update your UI to the changes of the model.
Use RxJava to create an EventBus object, which can hold an BehaviorSubject with the latest published data. Again, you can subscribe to this data and update your UI automatically.
Use a Room or Realm to store data, if you need the location between multiple app sessions.
You need to send whole object through this in your application and access it anywhere you want to
Step 1:
Store your data in list you want to like:
ArrayList<FeaturedProductDataModel> featuredProductsDataModelArrayList;
///////////get data and store in ArrayList///////////////////
featuredProductsDataModelArrayList = new ArrayList<(listofhome.getFeaturedProducts());
Step 2:
Declare Shared Preference and put data in it to further use in all application
featuretopprefernce = getActivity().getSharedPreferences("homelist", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = featuretopprefernce.edit();
//Set the values
Gson gson = new Gson();
String listofbusiness = gson.toJson(featuredProductsDataModelArrayList);
prefsEditor.putString("featuredProductsDataModelArrayList", listofbusiness);
prefsEditor.apply();
Step 3:
In recieving activity or fragment create a list and put data in it
ArrayList<FeaturedProductDataModel> dataModelArrayList;
SharedPreferences featuredprefernce;
featuredprefernce = getActivity().getSharedPreferences("homelist", Context.MODE_PRIVATE);
featuredlist = featuredprefernce.getString("featuredProductsDataModelArrayList",null);
Gson gson = new Gson();
Type type = new TypeToken<List<FeaturedProductDataModel>>(){}.getType();
dataModelArrayList = gson.fromJson(featuredlist, type);
You'll get your data in dataModelArrayList now use it as you like.
Actually, you have several options:
To save received data into the local database (you can use Room from Jetpack). And then to load the data from the database to the screen you need separately.
Or you can save the data into memory: it can be something like a DI container.
Also, you can use RxJava caching or Retrofit caching.
The second solution is the simplest for you.
I am trying to use GSON in order to parse a JSON that include some classes and fields that need to be excluded. Do I have to create classes for such objects, and include such fields in classes I create?
As it take Class<object> classOfT as parameter so we have to pass parameter, but if you dont want to make your custom class you can use it by this way.
Gson gson = new Gson();
gson.fromJson("Response Json String", Object.class);
and you can play with that object in many ways.
You can use #Expose annotation for your fields with serialize and deserializeparameters to false
Just don't add the field to the class and ignore it. There is no need to use all input, even with auto-mapping. Whatever has no #SerializedName annotation will not be mapped- #Expose also controls that. But the actual beauty of GSON is parsing such nested nodes to classes of various types.
just see: #SerializedName, #Expose.
I am using a class to create a background service which runs all the time. When using the Android app the user can enter data which are stored via SharedPreferences. The storing works well and the stored data are available in the activity which stores it. I am using SharedPreferences like this:
SharedPreferences mPrefs = getSharedPreferences("Identifier",Context.MODE_PRIVATE);
In the service I am trying to access to this values that are stored in the activity. Therefore I am using the SharedPreferences the same way:
SharedPreferences mPrefs = getSharedPreferences("Identifier",Context.MODE_PRIVATE);
I am storing an object this way in the activity:
Gson gson = new Gson();
SharedPreferences.Editor prefsEditor = mPrefs.edit();
String json = gson.toJson(myObject);
prefsEditor.putString("value",json);
prefsEditor.commit();
And try to read it this way, but json returns null:
Gson gson = new Gson();
String json = mPrefs.getString("value",null);
Any idea what might be wrong? Is the context wrong? But how should it be?
Try to use a default shared preferences instance, which is shared across all your Activity and Service classes, use below method.
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this/*context*/);
This is the best way for storing primitives datatype(like booleans) or serializable objects. However, if you're capturing a lot of JSON data, you might consider using an SQLite database instead.
The problem was that the service is running in a different process. Therefore I used tray which works perfectly for multiple processes: https://github.com/grandcentrix/tray.
This question was asked many times, but I haven't found a good solution yet.
I want to store my Arraylist in the sharedpreferences in Android as a String. So how can I serialize and deserialize it?
Any solutions?
Try using Gson Library this way:
String json = new Gson().toJson(<your list>);
To add Gson library add to dependencies
compile "com.google.code.gson:gson:2.6.2"
You can supply a toString() method for your custom objects then call toString() on the ArrayList. Parsing the string to deserialize it will be more difficult.
I am new to android realm.
I am using follwing code to get product object from realm.
ProductModel prodObj = realm.where(ProductModel.class).equalTo("product_id","12").findFirst();
How can i create standalone copy of prodObj?
I want to update some field's value that should not affect in realm database. I don't want to set it manually with setters method because model class contains too many fields. Is there any easy way to create standalone copy of prodObj?
Since 0.87.0
Added Realm.copyFromRealm() for creating detached copies of Realm objects (#931).
Realm only has a copyToRealm method and not a copyFromRealm method. Currently, there is a number of restriction to model classes (see https://realm.io/docs/java/latest/#objects) but we are investigating and experimenting how to lift these.
We have an open issue about exactly what you are asking: https://github.com/realm/realm-java/issues/931. But for the time being, you will have to copy our objects manually.
In case anyone wondered like me how we can implement this copyFromRealm(), this is how it works:
ProductModel prodObj = realm.where(ProductModel.class)
.equalTo("product_id", "12")
.findFirst();
ProductModel prodObjCopy = realm.copyFromRealm(prodObj);
You can serialize an object into a JSON string and deserialize into a standalone object by Jackson like:
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(yourObject);
objectMapper.readValue(json, YourModel.class);
GSON might not work because it doesn't support getter/setter when it makes a JSON.
I know it's a horrible solution.
But it might be the only way yet.