Android setter of String array - android

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

Related

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.

How to cast List to String[] in Android

In my application I want use ChipView, from this Library : https://github.com/adroitandroid/ChipCloud
In this library for set lists , I should use string[].
In my application I get lists of Tag with this code :
response.body().getData().getTags()
And Tags model is :
#SerializedName("tags")
#Expose
private List<NewsDetailTag> tags = null;
...
public List<NewsDetailTag> getTags() {
return tags;
}
In above library I should add list with this codes :
chipCloud.addChips(someStringArray);
How can I convert List to string[] in android?
Please help me guys.
There is no need for a "conversion" at all! No need to waste memory :)
Take a look at the code of the library and see, what ChipCloud.addChips() does:
public void addChips(String[] labels) {
for (String label : labels) {
addChip(label);
}
}
Its just going through the elements of the array and adding each string individually with the addChip() method.
In your code, you can do this the same way with a list:
List<NewsDetailTag> tags;
String tagString;
ChipCloud chipCloud;
// Get the tags, initialize the chipCloud, etc ...
for (NewsDetailTag tag : tags) {
tagString = tag.getTheStringFromNewsDetailTag();
chipCloud.addChip(tagString);
}
You could even write your own class that extends ChipCloud and add a method that accepts a List parameter.
The only thing thats left to do is to get a String from your NewsDetailTags. But it looks like they are serializable anyways.
try this:
String[] newList = yourList.toArray(new String[]);
hope this works
List<NewsLineTag> tags = response.body().getData().getTags();
List<String> tagStrings = new ArrayList<String>();
//add some stuff
for (NewsLineTag tag : tags) {
tagStrings.add(tag.getSomeTextValueINeed());
}
chipCloud.addChips(tagStrings.toArray(new String[0]));
getSomeTextValueINeed() should be replaced with some method which will provide you with the String you want to show.
Duplicate of Converting 'ArrayList<String> to 'String[]' in Java
Java's List has a pretty convenient toArray() method you can use to convert a List to an Array of the same type.
However, since you have a List<NewsDetailTag> you will have to build the new array yourself.
It will look something like this:
String[] strings = new String[](list.size())
for(int i = 0; i < list.size(); i++) {
array[i] = list.get(i).getStringField();
}
Where getStringField() is whatever property on NewsDetailTag contains the String you want.

Convert Array list to Sparse Array

I have copied some code from a project and want to reuse a small part of it in my private app.
The class contains a Sparse Array
public class GolfResult {
String hcpAfter;
String hcpBefore;
SparseArray roundResults;
public GolfResult() {
hcpAfter = "";
hcpBefore = "";
roundResults = new SparseArray();
}
}
I have created an ArrayList for roundResults that is filled with the necessary data.
Then I am trying to fill the instance with content.
GolfResult golferRes = new GolfResult();
SparseArray<RoundResults> hu= new SparseArray<>();
hu = roundresults; // *
golferRes.setHcpAfter("33");
golferRes.setHcpBefore("kk");
golferRes.setRoundResults(hu);
But the problem is that hu = roudresults is not possible, because of the error message:
required: Android.util.SparseArray found: java.util.Array List
Any help will be welcome.
After receiving two helpful answers I got a step further, but now I am facing the problem that my SparseArray hu is empty {}.
The content of hu should be the class roundresults that has the following structure:
public class RoundResults {
boolean actualRound;
private List<HoleResult> holeResults;
Integer roundId;
Integer roundNumber;
String unfinishedReason;
The arrayList roundresults has the size of 1 and has data in the objects.
unfinishedReason =""
holeResults = ArrayLIST size= 18
roundID = "1"
roundNumber = "1"
actualRound = true
hu ={}
mValues = All elements are null
mSize = 0
Does anybody have an idea why?
SparseArray is different than ArrayList, from the documentation:
SparseArrays map integers to Objects. Unlike a normal array of
Objects, there can be gaps in the indices. It is intended to be more
memory efficient than using a HashMap to map Integers to Objects, both
because it avoids auto-boxing keys and its data structure doesn't rely
on an extra entry object for each mapping.
It's using a key value pair principle where the key is an integer and the value which the key mapping is the object. You need to use put [(int key, E value)](https://developer.android.com/reference/android/util/SparseArray.html#put(int, E)) where the E is your object. Remember that:
Adds a mapping from the specified key to the specified value,
replacing the previous mapping from the specified key if there was
one.
So you need to use a loop to add each object in your ArrayList as #valentino-s says:
SparseArray<RoundResults> hu= new SparseArray<>();
for( int i = 0; i < roundresults.size(); i++) {
// i as the key for the object.
hu.put(i, roundresults.get(i));
}
If I understand well your problem, maybe you can try with this:
for ( int i=0; i<roundresults.size(); i++ ) {
hu.put(i,roundresults.get(i));
}
After some trial and error I found a solution for the empty hu:
Instead of put I used append and it is working now.
hu.append(i, roundresults.get(i));
Time for a beer.

Java - Parse - iterate over ParseObject fields

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
}

How can I pass the Strings from an ArrayList<String> to a method that takes in multiple Strings?

I have got an ArrayList with Strings and a method that can take in any amount of strings as arguments.
ArrayList<String> list = new ArrayList<String>();
// Filling the list with strings...
public addStrings(String... args) {
// Do something with those Strings
}
Now I would like to pass those strings from my array list to that method. How can I do that? How would I call addStrings() Note that the amount of strings in the arraylist can vary.
You can do something like this:
ArrayList<String> list = new ArrayList<String>();
// Filling the list with strings...
String[] stringArray = new String[list.size()];
list.toArray(stringArray);
addStrings(stringArray);
public addStrings(String... args) {
// Do something with those Strings
}
Pass your strings in a primitive array. From the varargs documentation:
The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.
All you'd need to do is derive a String[] from your List and then pass it to the addStrings(String... args) method.
Credit to this question for the documentation link.

Categories

Resources