How to refresh/Update Serialize Java Object in sharedPreferences - android

For storing the serilaizable java object i m using below code
if(sharedpreferences.getString(ComplexObjectXMl,"")!=null) {
Serializer serializer = new Persister();
MyObject example = null;
try {
example = serializer.read(MyObject .class, sharedpreferences.getString(ComplexObjectXMl,""));
} catch (Exception e) {
e.printStackTrace();
}
Intent i1 = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(i1);
}
new MyAsyncTask().execute();
In MyAsyncTask i m storing the XmlDataOverHttp in sharedPreferences. Will it get updated everytime if i like do this

you can compare byte array of those object. one coming from shared preference and other which is latest.
byte[] array = new Gson().toJson(latestObject).getBytes(); //your lattest byte array
byte[] secondArray = new Gson().toJson(objectConvertedFromSharedPreferenceOLD).getBytes();
if (Arrays.equals(array, secondArray))
System.out.println("They are same");
else
System.out.println("Nope...");
and as you said you can use service or shared preference to check hourly update in oncreateView() but it only happens when user open your app(between hour it will call api for list items)
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences
(Dashboard.this);
long lastUpdateTime = mSettings.getLong("lastUpdateTime", 0);
/* Should Activity Check for Updates Now? */
if ((lastUpdateTime + (3600000)) < System.currentTimeMillis()) {
/* Save current timestamp for next Check*/
SharedPreferences.Editor editor = mSettings.edit();
lastUpdateTime = System.currentTimeMillis();
editor.putLong("lastUpdateTime", lastUpdateTime);
editor.commit();
/* Start Update for listview your URL to fetch data and then you can check and compare object
also you can use swipeRefreshLayout so user can also refresh data*/
//asyncRequestTime.execute(URL);
}

Related

How to send the response to new activity?

I want to pass my API response to another activity . I am using intent but getting null in the next activity .
My code is MainPage.java
public void onResponse(String response) {
System.out.println("output -- "+response);
members = response;
Intent intn = new Intent(MainPage.this,Calculation.class);
intn.putExtra("MEMBERS",members);
}
I am getting the correct response .
Calculation.java
Intent intn = new Intent();
members = intn.getStringExtra("MEMBERS");
System.out.println("dmkmdk"+members);
//no_of_members = Integer.parseInt(members);
I also want to parse it in integer form .
you should get extra like this, don't initiate an intent object
Bundle extras = getIntent().getExtras();
String value1 = extras.getString("MEMBERS");
Try to save data in SharedPreference instead Intent.
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
For Storing data:-
editor.putString("MEMBERS",members);
editor.apply();
For retriving data:-
editor.getString("MEMBERS", null); // getting String
Please try this
To Transfer data in next activity
public void onResponse(String response) {
System.out.println("output -- "+response);
members = response;
Intent intn = new Intent(MainPage.this,Calculation.class);
intn.putExtra("MEMBERS",members);
startActivity(intn)
}
In New activity where you want to get data try this line
String resFromLast = getIntent().getExtras().getString("MEMBERS");
Log.e("Response From last activity is :" ,resFromLast);
MEMBERS is that key you passed in last activity with intent.
Hope it works.

Sharedpreference byte[] value cleared after app killed via 'Force Stop' or task manager

Problem
I'm saving a byte[] in my shared preferences. I am able to close the app and reopen it with the value persisting in the Shared Preferences. When running the app and closing it via the 'Task Manager' or 'Force Close', the Shared Preference value for the byte[] is cleared. I don't understand this because other values persist fine.
This lead me to believe that this was due to some gson or Shared Preference issue with the byte[] so I converted it to a String and I still have the issue.
Edit:
I save the data during normal activity usage... after onCreate(), for example. It's not during onPuse() or onDestroy() I forgot to mention this. It would make sense if I did call it here and one or both of those weren't being called on the 'Force Close' scenario.
Shared Preference Code
Slightly modified to remove app specific implementation and data
private static final String SHARED_PREFERENCES_FILE_NAME = "SharedPreferenceName";
public static void setSharedPreferenceObjectBase64Encoded(Context context, String key, Object object) throws Exception {
// Need an editor to update shared preference values
SharedPreferences.Editor editor = context.getSharedPreferences(SHARED_PREFERENCES_FILE_NAME, Context.MODE_PRIVATE).edit();
Gson gson = new GsonBuilder().serializeNulls().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create();
String encodedKey = Base64.encodeToString(key.getBytes(), 0, key.getBytes().length, Base64.DEFAULT);
String stringObject = gson.toJson(object);
String encodedObject = Base64.encodeToString(stringObject.getBytes(), 0, stringObject.getBytes().length, Base64.DEFAULT);
editor.putString(encodedKey, encodedObject);
editor.apply();
}
public static Object getSharedPreferenceObjectBase64Encoded(Context context, String key, Class<? extends Serializable> objectClass) throws Exception {
// Need an editor to update shared preference values
SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_FILE_NAME, Context.MODE_PRIVATE);
Gson gson = new GsonBuilder().serializeNulls().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create();
String encodedKey = Base64.encodeToString(key.getBytes(), 0, key.getBytes().length, Base64.DEFAULT);
String encodedObject = prefs.getString(encodedKey, null);
if (encodedObject == null) {
throw new NullPointerException("encodedObject is null : No shared preference exists for key.");
}
String decodedObject = new String(Base64.decode(encodedObject, Base64.DEFAULT));
if(decodedObject == null){
throw new NullPointerException("decodedObject is null : Json decoding error.");
}
Object resultObject = gson.fromJson(decodedObject, objectClass);
if (resultObject == null) {
throw new NullPointerException("resultObject is null : Json decoding error.");
}
return resultObject;
}
`byte[]` Code
public static final String VALUE_KEY= "value.key";
public static void saveTheValue(Context context, byte[] encryptedPin) {
try {
USharedPreferenceManager.setSharedPreferenceObjectBase64Encoded(context, VALUE_KEY, encryptedPin);
} catch (Exception e) {
}
}
public static byte[] getTheValue(Context context) {
try {
return (byte[]) USharedPreferenceManager.getSharedPreferenceObjectBase64Encoded(context, VALUE_KEY, byte[].class);
} catch (Exception e) {
return null;
}
}
Any input would be greatly appreciated..
Sadly, I haven't been able to make any progress here. Any thoughts?
Update:
As per Super-califragilistic recommendation, I iterated through the key/value pairs in the SharedPreferences immediately before retrieving the value. I was Base64 encoding my key and value values; in order to read the key to ensure the value was in the SharedPreferences I had to use the keys in plain text. This solved the issue for me as the byte[] value was now being retrieved properly.
This seems strange to me but I can use it as a solution. I would still like to Base64 encode the keys, but it's not incredibly important.
Current Solution:
Removed the Base64 encoding of the SharedPreference Key for storage and retrieval and the value is now persisting in all cases.
This line of code String encodedObject = prefs.getString(encodedKey, null); means if the key does not exist it should return null, hence your key that you are checking does not exist.
To validate if your key/value exist use this code
for(Entry<String, ?> en : sharedPref.getAll().entrySet()){
en.getKey();//key
en.getValue();//value
}
you could stop that from happening override onPause() in the Activity or Fragment and call saveTheValue(Context context, byte[] encryptedPin) if you detect you need to save data or have already tried saving data eg.
private boolean forceSaveInOnPause= false;//global variable
//in your saving method
....//after you save
forceSaveInOnPause = true;
//in your onPause of Activity
if(forceSaveInOnPause){
//re-save
forceSaveInOnPause = false;
but since you already have a solution scratch all that :)
Try once with editor.commit() instead of apply(), see if that works
I think using Base64.NO_PADDING instead of Base64.DEFAULT both while reading and writing may solve the problem.

Change from cloud JSON to local JSON

I'm looking at making a change in an app I'm working on (it's based off of this: http://goo.gl/rDBXVl) from loading a cloud based resource to a local based resource. I'm not particularly sure how I would go about doing this. I want to go from pulling a JSON file off the internet to pulling the JSON from my Assets folder.
I located the area in the app where it pulls the URL and loads the JSON but am unsure of what changes to make at this point.
public void loadData (Bundle savedInstanceState) {
// Check Network State
if (!NetworkUtil.getNetworkState(this)) {
final RetryFragment fragment = RetryFragment.getFragmentWithMessage("No connection");
this.addFragment(fragment, RetryFragment.TAG, true);
return;
}
if (savedInstanceState == null || savedInstanceState.get(KEY_LIST_DATA) == null) {
final String url = super.getResources().getString(R.string.config_wallpaper_manifest_url);
if (url != null && URLUtil.isValidUrl(url)) {
// Add Loading Fragment
final LoadingFragment fragment = new LoadingFragment();
this.addFragment(fragment, LoadingFragment.TAG, true);
// Load Data
final RestClientHandler handler = new RestClientHandler(this);
RestClient.get(this, url, handler);
}
} else {
Log.i(TAG, "Restored Instance");
this.mData = (ArrayList<NodeCategory>) savedInstanceState.get(KEY_LIST_DATA);
this.mPosition = savedInstanceState.getInt(KEY_LIST_POSITION);
if (this.mPosition != -1) {
mIgnoreSelection = true;
}
this.configureActionBar();
}
}
You have another option,
just save json in sharedpreferences. so easily read and write it.
Save sharedpreferences code bellow.
/**
* write SharedPreferences
* #param context
* #param name, name of preferences
* #param value, value of preferences
*/
public static void writePreferences(Context context,String name,String value)
{
SharedPreferences setting= context.getSharedPreferences("Give_your_filename", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=setting.edit();
editor.putString(name, value);
editor.commit();
}

How to perform two operations on one activity in android

I want to implement a search in my Android application.
In this page, first I am displaying a user list and then performing a search on the user list. Both are in the same activity. In the following manner, I am getting intent and some values from the previous page. When I display the user list, all the values are coming. But while performing search, spaceId gets lost and becomes null. I need this value.
Intent intent = this.getIntent();
Bundle receiveBundle = intent.getExtras();
spaceId = receiveBundle.getString("spaceId");
What should I do to get this value?
Edit:
String spaceId;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
Bundle receiveBundle = intent.getExtras();
spaceId = receiveBundle.getString("spaceId");
String URLTicketList = String.format(getString(R.string.URLTicketList, spaceId));
RestClient client = new RestClient(URLTicketList,
this.getApplicationContext());
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
TabSettings ts = new TabSettings();
ts.setSelTab(0);
String response = client.getResponse();
tickets = parseTicketList(response);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
searchResult=getMatchingStrings(tickets,query);
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row,searchResult);
setListAdapter(this.ticket_adapter);
}
else {
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row, tickets);
setListAdapter(this.ticket_adapter);
}
}
getMatchingstrings()
ArrayList<Ticket> getMatchingStrings(ArrayList<Ticket> list, String regex1) {
ArrayList <Ticket> listClone = new ArrayList<Ticket>();
for (Ticket string : list) {
if(string.getAssignedTo().equals(regex1)){
listClone.add(string);
}
}
return listClone;
}
Try it
getIntent().getExtras().getString("spaceId");
You said your activity is recreating. So you are not getting the value of spaceID after recreation. Then do this thing as below.
public String PREFS_NAME = "Shared_Pref";
Bundle receiveBundle = this.getIntent().getExtras();
String spaceId_value = receiveBundle.getString("spaceId");
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if(spaceId_value == null) {
spaceId_value = settings.getString("spaceId", "");
}
else {
SharedPreferences.Editor editor = settings.edit();
editor.putString("spaceId", spaceId_value);
}
I hope this will help you out.
edit :
I am editing your code.
Which part i have edited, i have mentioned that part as edited. Carefully see what i have changed and do that thing in your code. Then let me know.
String spaceId;
public String PREFS_NAME = "Shared_Pref"; //edited part
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//editing start
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
Bundle receiveBundle = this.getIntent().getExtras();
if(receiveBundle != null) {
spaceId = receiveBundle.getString("spaceId");
if(spaceId == null) {
spaceId = settings.getString("spaceId", "");
}
else {
SharedPreferences.Editor editor = settings.edit();
editor.putString("spaceId", spaceId);
}
}
//editing end
String URLTicketList = String.format(getString(R.string.URLTicketList, spaceId));
RestClient client = new RestClient(URLTicketList,
this.getApplicationContext());
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
TabSettings ts = new TabSettings();
ts.setSelTab(0);
String response = client.getResponse();
tickets = parseTicketList(response);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
searchResult=getMatchingStrings(tickets,query);
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row,searchResult);
setListAdapter(this.ticket_adapter);
}
else {
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row, tickets);
setListAdapter(this.ticket_adapter);
}
}
When you are firstly loading your list in activity,you have to save that spaceId in some SharedPreference variable for further use.And while reloading activity with search result,you can find that Id from SharedPreference variable previously saved.
Be sure,you overwrite that variable as and when you firstly load list in your activity to meet your needs cleanly.
Also you have to get spaceId from intent like:
int spaceId=0;
if(getIntent().hasExtra())
spaceId=getIntent().getStringExtra("spaceId");
Doing this wont give you excpetion when you reload the same activity with no extras to your intent.
Or,you will have to pass this spaceId along with intent you are using to reload the same activity for showing search result.
Hope,you get the point!
If u relaunching the same activity while performing search,u will lost that value. If u r doing so,while relaunching also pass that spaceId to the relaunching activity also using intent.putextra() method
as in your question and comments i guess you are getting problem if your activity is recreated
add following code in manifest file under your activity tag
android:configChanges="keyboardHidden|orientation"
your activity will not be created again
and then use the value of spaceID where you need

How to store hashmap so that it can be retained it value after a device reboot?

I want to store the hashmap object in global class so that it will store value even after the mobile restart. Any idea how to go about this concept.
serialize your hashmap object before restarting and deserialize it after restart...
here is sample code for serialization..
public void serializeMap(HashMap<String,String> hm) {
try {
FileOutputStream fStream = openFileOutput(namefile.bin, Context.MODE_PRIVATE) ;
ObjectOutputStream oStream = new ObjectOutputStream(fStream);
oStream.writeObject(hm);
oStream.flush();
oStream.close();
Log.v("Serialization success", "Success");
} catch (Exception e) {
Log.v("IO Exception", e.getMessage());
}
}
you can similarly read it by deserializing it....
Thanks....
Thanks very much but same thing can be done using the shared Preferences technique.
Below is the code to add data into shared preferences and check if already exists.
SharedPreferences preferences = getSharedPreferences(
PREF_FILE_NAME, MODE_PRIVATE);
if (value.equals("")) {
boolean storedPreference = preferences.contains(key);
if (storedPreference) {
SharedPreferences.Editor editor = preferences.edit();
editor.remove(key); // value to store
Log.d("KEY",key);
editor.commit();
}
}else{
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value); // value to store
Log.d("KEY",key);
editor.commit();
}
then we can access using the
SharedPreferences preferences = getSharedPreferences(
PREF_FILE_NAME, MODE_PRIVATE);
Map<String, String> map = (Map<String, String>) preferences.getAll();
if(!map.isEmpty()){
Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry pairs = (Map.Entry)iterator.next();
pairs.getKey()+pairs.getValue();
//write code here
}
}
Serialize it and save it in shared preferences or in a file. Whether you can do this, of course, depends on the data types being mapped from and to. (This won't work, for instance, if you try to serialize a View.)

Categories

Resources