Java - Parse - iterate over ParseObject fields - android

Having a ParseObject object how can I loop through its fields and get the name of the field along with the value of it? This would really help me minimize my code.

Hmm, ParseObject contains key-value pairs, and I think you can't iterate though it. But. I found something called .keySet() method of ParseObject. It returns ... well, the set of keys (excluding createdAt, updatedAt, authData, or objectId). I think you can convert it into an array and iterate trhough it?
Something like this:
Set<String> keySet = parseObject.keySet();
String[] parseKeys = keySet.toArray(new String[keySet.size()]);
for (String key : parseKeys) {
String parseValue = parseObject.get(key);
//do whatever you want
}

Related

Android SharedPrefences multiple values for one key

I have a probleme here.
I don't know how to read all values of a SharedPreferences for one particular key.
Actually I'm trying to write an Arraylist in preferences , then read it.
Let me explain with some code, Here is my methods for write in preferences :
fun writeArrayOnPreferences(key: String?, array: ArrayList<String>, c:Context) {
val preferences = c.getSharedPreferences(
c.getString(key), Context.MODE_PRIVATE)
with(preferences.edit()) {
for (value in array) {
putString(key, value)
}
commit()
}
}
My writing code works , it's persistent , but I don't really understand how to READ this Arraylist from preferences.
I tried a lot of things to read this but it show me only the last element wrote in preferences
I really want you to understand that I want multiple values for a specific key
This is a quick example based on Nabin Bhandari's answer
fun writeArrayOnPreferences(key: String, array: ArrayList<String>, c:Context) {
val jsonString = Gson().toJson(array)
pref.edit().putString(key, jsonString).commit()
}
fun readArrayFromPreferences(key: String, c: Context): ArrayList<String> {
val jsonString = pref.getString(key)
val array = Gson().fromJson(jsonString, ArrayList<String>()::class.java)
return array
}
ok here how it is! If you want multiple data against one key in share pref editor then SET is your solution as After API 11 the SharedPreferences Editor accept Sets. You could convert your List into a HashSet or something similar and store it like that When your read it back, convert it into an ArrayList, sort it if needed and you're good to go.
//Set the values
val yourSet = HashSet<String>()
set.addAll(listOfExistingScores)
yourPrefEditor.putStringSet("key", yourSet)
yourPrefEditor.commit()
//Retrieve the values
val yourSet = yourPref.getStringSet("key", null)
SOLUTION NUMBER 2
would be like serializing the ArrayList and passing it! but there can be a catch if any value in your array does posses any rule that can't be Parced it will crash!
For More check this Thread this is in java but it will help tell you more!
You cannot simply loop values in an ArrayList put them in the preferences using same key for all values and expect to retrieve the ArrayList back.
You can convert the 'ArrayList' in JSON format and store it in SharedPreferences. Then to parse the JSON string to get the ArrayList.
You can make this process easier with the help of a library called Gson.
Try this:
with(preferences.edit()) {
var s = ""
for (value in array) {
s = s + value + ","
}
putString(key, value)
commit()
}
your array will be saved like comma separated values which when read back in a string, by using the split function will become an array.

Firebase Database change node ID

How can I change the naming of the nodes of my children in the image below?
questions_stats is a List<Integer>, I'm aware that I get integers as nodes Id because this is a List. I create each of the children randomly with a number between 0 and 1000. I set this ID as part of the object and to find it I loop trough the list. What I want is to set the "0671" as the Key of the Object at the moment I create it.
How should I define my object in order to access each child with an Id that I define as a String.
Each of the questions_stats is an object.
This is my UserProfile Class definition.
public class UserProfile implements Parcelable {
private List<Integer> questions_list;
private List<QuestionsStats> questions_stats;
private String country_name, share_code, user_name;
private int token_count;
private Boolean is_guest;
public UserProfile() {
}
public UserProfile(List<Integer> questions_list, List<QuestionsStats> questions_stats, String country_name, String share_code, String user_name, int token_count, Boolean is_guest) {
this.questions_list = questions_list;
this.questions_stats = questions_stats;
this.country_name = country_name;
this.share_code = share_code;
this.user_name = user_name;
this.token_count = token_count;
this.is_guest = is_guest;
}
}
I know I can set them using the child("0159").setValue(QuestionStats) individually.
But for my purpose I need to retrieve the data of the "user" as a whole and then iterate whithin questions_stats like it is a List.
How should I define my UserProfile class in order to achieve what I want?
Anybody could give me a hint?
How can I change the node names of my children in the image below?
Answer: There is no way in which you can change the names of the nodes from your Firebase database. There is no API for doing that. What can you do instead is to attach a listener on that node and get the dataSnapshot object. Having that data, you can write it in another place using other names. You cannot simply rename them from 0 to 0000, 1 to 0001 and so on.
Perhaps I should have asked for How to "Set" the node Id instead of "Change"
What I have is an List<QuestionsStats>, but when using an List<QuestionsStats> you get indexes as Keys, What I want is to have the same List<QuestionsStats> but instead of indexes, String Keys for each of my items.
So I changed my List for a Map<String, QuestionsStats>. Now the tricky part is when parceling the Object. You can use readMap() or writeMap() to parcel as shown here in this answer by #David Wasser, but it gives a warning:
Please use writeBundle(Bundle) instead. Flattens a Map into the parcel
at the current dataPosition(), growing dataCapacity() if needed. The
Map keys must be String objects. The Map values are written using
writeValue(Object) and must follow the specification there. It is
strongly recommended to use writeBundle(Bundle) instead of this
method, since the Bundle class provides a type-safe API that allows
you to avoid mysterious type errors at the point of marshalling.
So with the help of the comments in This Question I parceled using this code, note that I'm leaving the "easy" way commented in case somebody find it useful or have any comment on that :
protected UserProfile(Parcel in) {
// in.readMap(myMap, Object.class.getClassLoader());
myMap = new HashMap<>();
String[] array = in.createStringArray();
Bundle bundle = in.readBundle(Object.class.getClassLoader());
for (String s : array) {
myMap.put(s, (Object) bundle.getParcelable(s));
}
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// dest.writeMap(myMap);
Bundle bundle = new Bundle();
for (Map.Entry<String, Object> entry : myMap.entrySet()) {
bundle.putParcelable(entry.getKey(), entry.getValue());
}
Set<String> keySet = myMap.keySet();
String[] array = keySet.toArray(new String[keySet.size()]);
dest.writeStringArray(array);
dest.writeBundle(bundle);
}
Why I want this, well at the moment my list contains less than 100 items but it could grow up to a 1000, I'm no Pro, but I believe that if I already know the key of the item I'm interested in will be always better than having to iterate over the list to find it. In the end my main problem was the usage of a Map, I did not know howto.

Android - Is it possible to have a lookup array?

I know there's an answer to this, but i'm not sure what to search and cannot remember the right phrasing.
Essentially what i mean, i'm being passed an integer. I want to search through an array using this integer to return a string value.
E.g.
I'm given the number 2. My lookup array looks like so:
array.add(1, "Auckland")
array.add(2, "Wellington")
array.add(3, "Bay of Plenty")
When i iterate through the array, i want to return "Wellington".
Can someone point me in the right direction please? :)
Hi you should declare a HashMap of Integer String:
HashMap<Integer, String> map= new HashMap<Integer, String>();
map.put(1, "Auckland");
map.put(2, "Wellington");
map.put(3, "Bay of Plenty");
And then to get the String you should call the HashMap using the key:
String yourString = map.get(1);

Android setter of String array

now i've got simple setter and getter of string array. I want to use setter to put some retrevied json info + same text to array. When i use belowe code:
met.setPlacepic(new String[]{"http://dfsdfsdfsf/" + json.getString("source")});
it looks like setter put only one string to array, despite there is many more data.
Declaration is simple
public String[] placepic
and the setter is also simple:
public void setPlacepic(String[] placepic) {
this.placepic = placepic;
}
Anybody knows reason of this?
If the number of strings is fixed (you know exactly how many element you would have in the array), then you could use String Arrays:
String[] placepic = new String[20]; //20 strings
//Then, in your loop:
placepic[i] = yourData;
If you do NOT know how many strings in your data, You should use List:
List<String> placepicList= new ArrayList<String>();
//Then, in your loop:
placepicList.add(yourData);
//Then after the loop, you get the array
String[] placepic = placepicList.toArray(new String[placepicList.size()]);

Retrieve an array from parse.com and add the values to a local array (Android)

I have an array column called "Roots" in a user class from parse.com and I want to retrieve the array object from the column and then extract the values (strings) to an array in my application.
ParseUser.logInInBackground(user, password, new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// Hooray! The user is logged in.
startMenu();
String[] testStringArray = (String[])user.get("Roots");
I'm not sure if the last line even works. Even if it does, I'm not sure how to extract the individual elements and set them to a local array that I can call on using an index e.g.
String myString = testStringArray[1]
Or some such. I have tried a few variations of the above code and I think I am missing something fundamental. Does anyone have an example of how I can accomplish this?
Thanks in advance!
Use an ArrayList<String> instead of String[], then you can access it as you would any other ArrayList object.
ArrayList<String> testStringArrayList = (ArrayList<String>)user.get("Roots");
String myString = testStringArrayList.get(1);

Categories

Resources