I need to create an array of the last 5 call dates.
I know that I have to save the date on the array but I don't know how to reorder the other records to keep this last call date the 1st record. And always maintain only 5 records
The Goal is to save that last call string and add to the array, after that I reorder to and maintain only the 5 records, after that I use FlexJson to make a string and save on sharedpreferences. Anyone have this full process?
Here what I'm doing but is throwing errors everywhere:
SAVE
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss dd-MM-yyyy", Locale.getDefault());
Calendar calendar = Calendar.getInstance();
String currentDateTimeString = df.format(calendar.getTime());
List<String> textList = new ArrayList<>();
JSONSerializer ser = new JSONSerializer();
textList.add(currentDateTimeString);
String jsonText = ser.deepSerialize(textList);
editor.putString("lastCall", jsonText);
editor.commit();
READ:
String lastCall = callLogPreferences.getString("lastCall", null);
JSONDeserializer<List<String>> der = new JSONDeserializer<>();
List<String> textList = der.deserialize(lastCall);
I'm using FlexJson: GSON and InstanceCreator issue
It's not converting from string to Array List
First let me give you an advise - if you have 3 question create 3 topics, not one with all the questions. Based on the question title: Android array to sharedpreferences I'll give an answer just to this issue.
So from your question you want to store a List<String> myList inside SharedPreferences. To do so I advise you to use Gson because it's simple. The main idea it's to serialize your List to a String in json and then store that String:
Since you are using primitive types you don't need to specify a TypeToken so you just need to:
public static final MY_LIST = "my_list";
List<String> myList = new ArrayList<String>();
SharedPreferences.Editor editor = prefs.edit();
editor.putString(MY_LIST, new Gson().toJson(myList));
editor.commit();
And it's stored. To retrieve the list just do the opposite:
myList = new Gson().fromJson(prefs.getString(MY_LIST, null), List<String>);
And that's it!
Hope it helped.
ps: SharedPreferences it's used to store values that can be accessed in other Classes/Activities/etc.. or to persist information between app restarts. You don't need this to accomplish what you want: Create a list with 5 ordered strings.
EDIT: this lib may save you some time with the serialization ;)
Try using an ArrayList with a custom Comparator as seen here: Sort ArrayList of custom Objects by property
Then, sort the ArrayList accordingly.
Related
I am trying to retrieve the node 0's property - tag values, which is a linkedList object property I believe. as you can see it is [****,****]
I wish to retrieve the object value and store into a List<String> object
So I can get the each value out for late use, e.g
String idA = "542f74fd-bfaf-4377-854a-8e62082edc6c";
string idB = "39aab11f-243f-464c-ae6d-c1f069f17d6c";
My attampt is something like below:
List<String> tagList = new ArrayList<String>();
tagList = componentNode.getProperties(node, "tags");
also tried this:
List<String> tagList = new ArrayList<String>();
tagList = PropertyUtil.getProperty(node, "tags");
but none of them works.
Please suggest me with code sample.
Thanks
I believe they are called multi value properties in JCR and is supported via Arrays instead of Lists.
I haven't tested the code myself but I believe it'll work.
This should do the trick:
Property property = node.getProperty("tags");
Value[] tags = property.getValues();
and then you can convert/wrap it to List if you really want to.
Hope that helps,
Cheers,
can some one explain me how to get all categories value from
"categories":[{"1":1,"2":"orange","3":"mango","4":"guava","5":5,"6":6}]
result my like this 1 = 1, and 2 = orange,
what must i do i am stuck in here
public RealmList<CategoryRealm> categories;
or
p.categories = new RealmList<>();
can some one explain to me what must i do in the next method i am stuck tried searching but so damn hard to learn its diferent.
Use GSON library.
Create an object that matches your structure. I'm assuming you have a structure of
{
"categories"://the rest of the stuff here
}
class MyParentObject{
#SerializeName("categories")
ArrayList<String> myList;
}
Then use GSON to create it
MyParentObject obj = (MyParentObject)getGson().fromJson(json, classType);
and your done.
If the base is just the categories string then your json is badly formatted and you may have to do a subString call to get starting index of "[" and go from there into json management.
My App: has two activities, one to create two strings (name and message), which are saved into a hashmap, transferred into JSON and saved in a SharedPreference.
The other activity fetches this SharedPreference, transfers it into a hashmap again. Then the map is "read out" by an Iterator.
Supposed to be: My Idea is, that if I do this process several times, the iterator "reads out" all the entries to the hashmap.
Problem: However, only the last input gets displayed.
Question: Why is only the last input displayed? Am I overriding the hashmap or parts of it? And if so, how can I avoid it? Or what else am I doing wrong?
Activity 1:
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put(message, name);
Gson gson = new Gson();
String hashMapString = gson.toJson(map);
SharedPreferences prefs = getSharedPreferences("SP", MODE_PRIVATE);
prefs.edit().putString("hashString", hashMapString).apply();
Activity 2:
Gson gson = new Gson();
SharedPreferences prefs = getSharedPreferences("SP", MODE_PRIVATE);
String storedHashMapString = prefs.getString("hashString", "Error");
java.lang.reflect.Type type = new TypeToken<LinkedHashMap<String, String>>(){}.getType();
LinkedHashMap<String, String> map = gson.fromJson(storedHashMapString, type);
Iterator myIterator = map.keySet().iterator();
while(myIterator.hasNext()) {
String key=(String)myIterator.next();
String value=(String)map.get(key);
Toast.makeText(getApplicationContext(), "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show();
}
while doing this
prefs.edit().putString("hashString", hashMapString).apply();
you are just saving values of newly created hashmap but old losing values which were saved previously using hashString key
Solution: fetch the old value and save it along with new values
Option one : fetch previous string , convert it to jsonobject then add the values to map
Reference : creating Hashmap from a JSON String
Option two : if you have only string key-value pair then
remove { and } from both new and old map strings then simply combine them and add { and } boundary symbols
String allValues ="{"+((prefs.getString("hashString", "")+hashMapString)
.replace("{","").replace("}",""))+"}";
then later save it
prefs.edit().putString("hashString", allValues).apply();
you are seeing the last input because putString overwrites whatever was there in the first place
https://developer.android.com/reference/android/content/SharedPreferences.Editor.html
i have this really long JSON text where i have to locate a string of a movie title that is between following:
((((((( .","title":" AND ","type":" )))))))
i have read on other solutions like :
String mydata = json;
Pattern pattern = Pattern.compile(".\",\"title\":\"(.*?)\",\"type\":\"");
Matcher matcher = pattern.matcher(mydata);
while (matcher.find())
{
testare += (matcher.group(1));
}
and also the way messier:
List<String> strings = Arrays.asList( json.replaceAll("^.*?.\",\"title\":\"", >>"")
.split("\",\"type\":\".*?(.\",\"title\":\"|$)"));
ArrayAdapter<String> myAdapter = new
ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, strings);
final ListView myList = (ListView) findViewById(R.id.listVyn);
myList.setAdapter(myAdapter);
Json contains the entire text in the JSON as a string.
My problem is that when i search for Dirty it recommends movies that contains "Dirty" and i want to search the string and pick out all the titles. But for some reason it seems to loop the first movie name, which is "Dirty" and then ignore the rest. what should i do about this?
If I'm understanding you correctly, I might suggest a different approach. If you deserialize the json object to a java object, you'll should find the problem much easier. I.e., instead of working with json, you'd be working with a java object, containing the information from the json. You can do this in a number of ways, for instance using Gson:
Gson gson = new Gson();
MyObject myObject = gson.fromJson(jsonString, MyObject.class);
Once you've done this, you can use myObject to get text from the object. E.g., myObject.getTitle(). If you then want to use regex on that string, that's all good. But I wouldn't use regex on the json.
In order to create MyObject.class, which represents the json, you can use:
http://pojo.sodhanalibrary.com
My code here will be simplified for readability.
Methods for getting the Set and adding a password to it:
public void addPass(String pass)
{
// Get the current list.
SharedPreferences sp = getSharedPreferences("passes", 0);
SharedPreferences.Editor editor = getSharedPreferences("passes", 0).edit();
Set<String> passes = sp.getStringSet("myStrings", new HashSet<String>());
// Add the new value.
passes.add(pass);
// Save the list.
editor.putStringSet("myStrings", passes);
editor.commit();
}
public Set<String> getPasses()
{
SharedPreferences sp = getSharedPreferences("passes", 0);
return sp.getStringSet("myStrings", new HashSet<String>());
}
Reading from the Set
Set<String> x = getPasses();
String[] passes = x.toArray(new String[0]); // convert the set to array
toast(Arrays.toString(passes)); // test what the set looks like
I converted the set to an array because it was easier to test conditions with an array for me.
Adding to the Set
EditText password1 = new EditText(this);
String p1 = password1.getText().toString();
addPass(p1.trim()); // add it to the set
toast("Account successfully created.");
Problem
When I first ran this code, I added three String values: "a", "b", "c" (in that order).
All the value were added to the Set correctly and it was confirmed with this line of code from above:
toast(Arrays.toString(passes)); // test what the set looks like
It outputted [b, c, a] after the "c" was added to the set.
The problem is that when I closed the app and reopened it, the Set only contained "a".
I could add the "b" and "c" values again, but the cycle would just continue where the Set only kept the first value added to it after the activity was recreated.
I've troubleshooted for a while and cannot fix it. I can provide more detail on how and when I'm using this code if necessary. I'm hoping I don't need to and someone can point out a problem in the code as shown.
Was searching for a solution for the same issue, a solution to this would be
// Get the current list.
SharedPreferences sp = getSharedPreferences("passes", 0);
SharedPreferences.Editor editor = getSharedPreferences("passes", 0).edit();
Set<String> passes = sp.getStringSet("myStrings", new HashSet<String>());
//Make a copy, update it and save it
Set<String> newPasses = new HashSet<String>();
newPasses.add(pass);
newPasses.addAll(passes);
editor.putStringSet("myStrings", newPasses); editor.commit();
It might be that your issue stems from using getStringSet(), have a look at the docs:
public abstract Set<String> getStringSet (String key, Set<String> defValues)
Retrieve a set of String values from the preferences.
Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.
Based on this doc , and this SO Post about the exact same problem as yours, it seems you should create a new copy of the returned instance of the HashSet, and you seem to have done that, at least from what code you've pasted here. Maybe there's something else that's being missed.
However, check out the answer on this post . What the guy did was:
Add the first value to SharedPreferences as a String Set.
To add subsequent values, first read the existing pref into a new String Set.
Remove the old String Set key.
Modify the new string set to add the new values you want to store.
Add the new String Set to preferences.
While that is a long and silly way to do things, it seems like the last option. So basically, store all the values you want to store, in one go (not in instalments). If you want to add new values, remove the old key, create a new key with the old + new values, then store the new key.
Hope that helps.