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.
Related
I have an myArrayList which is to be stored and restored back in its saved sorted order. But the code does not do that. Why?
ArrayList<String> myArrayList
// save:
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor edit;
edit = prefs.edit();
edit.putStringSet("mydata", new LinkedHashSet<String>(myArrayList));
edit.commit();
// read:
myArrayList = new ArrayList<String>(PreferenceManager
.getDefaultSharedPreferences(getBaseContext()).getStringSet(
"mydata", new LinkedHashSet<String>()));
adapterAppList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
myArrayList);
Is there any better way I can store the value of myArrayList and restored back to its original saved sorted order?
HashSet is not keeping orders, it is ordering for quickest find to it. You can convert list to json and save as string.
When you need to it, you can convert it to ArrayList from json with keeped ordering.
Example:
String listAsString = new Gson().toJson(arrayList); //list to string
List<String> arrayList = Arrays.asList(new Gson().fromJson(listAsString,String[].class)) //string to list
dont forget add library to build.gradle:
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
You can serialize arrayList like string:
1 with gson
public ArrayList<String> convertToArrayList(String json) {
if (TextUtils.isEmpty(json)){
return null; // or new ArrayList<>()
}
Type type = new TypeToken<ArrayList<String>>(){}.getType();
return new Gson().fromJson(json, type);
}
public String convertFromArrayList(ArrayList<String> list) {
if (list == null){
return null;
}
return new Gson().toJson(list);
}
2 without gson
public ArrayList<String> convertToArrayList(String st) {
if (!TextUtils.isEmpty(st)){
String[] str = st.split(",");
if (str.length > 0){
return new ArrayList<>(Arrays.asList(str));
}
}
return null;
}
public String convertFromArrayList(ArrayList<String> list) {
if (list!=null && !list.isEmpty()){
return TextUtils.join(",", list);
}
return null;
}
Yes, you are right, the order is not stored in string set, coz it is a set (duh).
When I was bugged with this, I got the serializing solution where, you can serialize your string.
Read this only if you haven't read about serializing, else go down and read my hack
In order to store array items in order, we can serialize the array into a single string (by making a new class ObjectSerializer (copy the code from – www.androiddevcourse.com/objectserializer.html , replace everything except the package name))
Entering data in Shared preference :
the rest of the code on line 38 -
Put the next arg as this, so that if data is not retrieved it will return empty array(we cant put empty string coz the container/variable is an array not string)
Coming to my Hack :-
Merge contents of array into a single string by having some symbol in between each item and then split it using that symbol when retrieving it.
If you are worried about splitting just look up "splitting a string in java".
[Note: This works fine if the contents of your array is of primitive kind like string, int, float, etc. It will work for complex arrays which have its own structure, suppose a phone book, but the merging and splitting would become a bit complex. ]
PS: I am new to android, so don't know if it is a good hack, so lemme know if you find better hacks.
I am trying to save data in my firebase such that it appear like this:
I know that the way to input it manually in firebase is ["marie", "femmehacks"]
But how to I input it from android using delimiter..Note that I need to use Java 7 and String.join is not the solution in android.
Here are my codes:
StringBuilder newstring = new StringBuilder();
for (String movie: movies){
newstring.append(movie);
newstring.append(",");
}
String all = newstring.toString();
all = all.substring(0, all.length() - ",".length());
The output as per this code is now:
["marie,femmehacks"]
but I want it to appear like
["marie", "femmehacks"]
such that it is saved in firebase as per the image above. Any help?
Use this function TextUtils.join(CharSequence delimiter, Iterable tokens).
I got this from here https://developer.android.com/reference/android/text/TextUtils#join(java.lang.CharSequence,%20java.lang.Iterable)
android.text.TextUtils
public static String join(#NonNull CharSequence delimiter,
#NonNull Iterable tokens)
External annotations available:
Parameter delimiter: #android.support.annotation.NonNull
Parameter tokens: #android.support.annotation.NonNull
You may try like this. its works for me.
List<String> stringList = new ArrayList<>();
private String membersName = "";
for (UserInfo userInfo : userInfoList) {
stringList.add(userInfo.getUsername());
}
membersName = TextUtils.join(", ", stringList);
you can save like :
FirebaseDatabase.getInstance().getReference().child(“ChildName”).setValue(membersName);
You should push data as ArrayList<String>
ArrayList<String> movies = <enter code to get list>
FirebaseDatabase.getInstance().getReference().child(“yourChild”).setValue(movies);
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.
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()]);
I receive data from a server using JSON and I want to order them alphabetically with alphabet indexed section and store them in a ListView.
Maybe something that will happen in :
for(int i=0;i<jArray.length();i++){
// here
}
I read that you can order elements like that only using a cursor. In my case would be very inefficient to store the elements from the server in the database and read them again. Waste of time and memory.
So, I am asking you if there could be any solution for my problem : order alphabetically with alphabet indexed section string received from JSON .
EDIT: I want my listview to look like this http://eshyu.wordpress.com/2010/08/15/cursoradapter-with-alphabet-indexed-section-headers/ . I mean with those sections . All tutorials I found said that you need to fetch information with a cursor. My question was if I could't do this wihout a cursor, because it would be a waste of memory to store them in the local database too.
You may need to parse the JSON Array :
List<Project> list = new ArrayList<Project>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject obj = (JSONObject) jArray.get(i);
project = new Project();
project.setId( Long.parseLong(obj.get("id").toString()));
project.setKey(obj.get("key").toString());
project.setName(obj.get("name").toString());
list.add(project);
}
You can use the comparator class like this to sort them :
Collections.sort(list), new Comparator<Project>() {
public int compare(Project p1, Project p2) {
return p1.getKey().compareToIgnoreCase(p2.getKey());
}
});
You can also have Project class and implements Comparable:
public class Project implements Comparable<Project> {
private long id;
private String key;
private String name;
public int compareTo(Project p) {
if (this.key > p.key)
return -1;
else if (this.key < p.key)
return 1;
return 0;
}
}
And then sort the list by Collections.sort(list);
My suggestion is try to sort the data in the Server-side, because the memory of the phone is limited and it may make you application time consuming to show the data, but you do not have memory limitation problem in the Server-side.
use a comparator to sort the arraylist as described here . And then use an ArrayAdapter to show the items in Listview