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);
Related
I'm essentially looking for another way to sort a string list besides the .sort()
Using that for my purpose gives me type '_SecItem' is not a subtype of type 'Comparable<dynamic>'
I'm trying to sort a string list by the numerical numbers in front of the strings. Something like:
List<String> hi = ['05stack', '03overflow', '01cool','04is', '02uToo'];
to this:
['01cool', '02uToo', '03overflow', '04is', '05stack']
With a function to extract the number like
int extractNumber(String srt){
RegExp regex = new RegExp(r"(\d+)");
return regex.allMatches(srt).toList().map((m){
return srt.substring(m.start, m.end);
}).toList().map((v)=>int.parse(v)).first;
}
void main(){
List<String> test = ['05stack', '03overflow', '01cool','04is', '02uToo'];
test.sort((a, b)=>extractNumber(a)>extractNumber(b) ? 1 : -1);
print(test);
}
I can sort easily using sort().
var List<String> hi = ['05stack', '03overflow', '01cool', '04is', '02uToo'];
hi.sort();
hi.forEach((element) {
print(element);
});
it prints:
01cool
02uToo
03overflow
04is
05stack
I am not getting any error of
type '_SecItem' is not a subtype of type 'Comparable<dynamic>'
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 using GreenDao for Android application, with some specification, for example, I have a Contact Model with some information like name, avatar, phone number, etc...
Right now the need is to change from only one phone number to a multiphone number.
Instead of creating two tables (table for numbers, and table for contacts), I really need just one information is the number so in my backend the contact numbers is stocked on a DC2type, (a json array saved as a string).
Do we have a possibility to do that using GreenDao?
i search for a solution or a DC2type implementation , etc ... and nothing is found
so i decide to created by my self , and this is what i did :
using the #Convert annotation presented of GreenDao 3 :
#Property(nameInDb = "phoneNumbers")
#Convert(converter = PhoneNumbersConverter.class, columnType = String.class)
private List<String> phoneNumbers;
static class PhoneNumbersConverter implements PropertyConverter<List<String>, String> {
#Override
public List<String> convertToEntityProperty(String databaseValue) {
List<String> listOfStrings = new Gson().fromJson(databaseValue,List.class);
return listOfStrings;
}
#Override
public String convertToDatabaseValue(List<String> entityProperty) {
String json = new Gson().toJson(entityProperty);
return json;
}
}
short story long , i create a json to array parser
thanks to myself to helped me :D
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.
Basically I have an app that fetches some information from Facebook, and that info can be regularly updated. I want to save that information in the phone so that when the user does not have an internet connection he can still see the latest fetch.
The information is saved in a
ArrayList<HashMap<String, String>>
What should I use?
The amount of information to save is small. 7 entries in the HashMap and at most 15 in the ArrayList. I use this datatype because I display it in a ListView.
Again that info must be saved even is the app is closed.
Regards
you can write it to a json or xml file , and load that file when app started
I think the best way is to save it to SharedPreferences. An easy way is to convert this object to JSON String and store that String in the SharedPreferences, and then when needed, get JSON string back and convert it back to your object. The library that does it nicely is Google's gson library. If you are using Gradle, import it like this:
dependencies {
...
compile 'com.google.code.gson:gson:2.2.+'
...
}
then, you can use this simple class to convert objects to/from String
public class JsonHelper {
public static Gson gson = new GsonBuilder()
.setPrettyPrinting().create();
public static Object getObject(String jsonString, Type classType){
return gson.fromJson(jsonString, classType);
}
public static String getJsonString(Object object){
return gson.toJson(object);
}
}
then, you can do this:
//to get JSON string from your object
ArrayList<HashMap<String, String>> yourList = ...;
String JSONString = JsonHelper.getJsonString(yourList);
//save string to shared preference
//to get your object from JSON string
//get JSON string from shared prefs
String yourJsonString = ...;
Type t = new TypeToken<ArrayList<HashMap<String, String>>>() { }.getType();
ArrayList<HashMap<String, String>> yourList = (ArrayList<HashMap<String, String>>)JsonHelper.getObject(yourJsonString, t);
here is some info about SharedPreferences and some info on how to use SharedPreferences, its really easy.
Then, you can add these methods to your Activity
public class YourActivity extends Activity{
public static final String KEY_PREFS = "com.your_app_name";
public static final String KEY_DATA = "your_data";
...
public static void saveDataToPrefs(String json){
getSharedPreferences(KEY_PREFS, Context.MODE_PRIVATE).edit().putString(KEY_DATA, json).commit();
}
public ArrayList<HashMap<String, String>> getDataFromPrefs(){
Type t = new TypeToken<ArrayList<HashMap<String, String>>>() { }.getType();
return (ArrayList<HashMap<String, String>>)JsonHelper
.getObject(getSharedPreferences(KEY_PREFS, Context.MODE_PRIVATE)
.getString(KEY_DATA, ""), t);
}
}
Please note this is not the best way to save the info in the app persistantly, as this method can produce unexpected bugs, like in case the final JSON string needs to be larger then the String object in the Android system. The best way is to have a database.
Have you looked at serialisation before? I find it very useful for this type of thing.
What is object serialization?
You can serialise out your data into an arbitrary file on the device SD card for example, then just read it back in on startup. I've used it for storing data in games, e.g. a save file.