I have
ArrayList<String> ids = ArrayList<String>();
What would be the cleanest way to make it Parceleable? Apparently String itself is not parcelable, so Parcel.writeList(ids) is not working.
I was thinking to either parcelize ArrayList<Uri> or put array contents into a Bundle.
Convert your list to String[] and use Parcel.writeStringArray. Example here
This isnt parcelizing, but to put it in a bundle:
ArrayList<String> ids = new ArrayList<String>();
savedInstanceState.putStringArrayList("key",ids);
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.
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()]);
This question already has answers here:
Pass ArrayList<Double> from one activity to another activity on android
(4 answers)
Closed 9 years ago.
I have a list like this,
List< Double> list_r = new ArrayList<Double>();
How can I pass this list from one activity to other ?
How can I pass this list from one activity to other ?
Then Make this list Static just like this:
public static List< Double> list_r = new ArrayList<Double>();
And Access this list in other activity like this:
private List<Double> list_my = ClassName.list_r;
Where ClassName is your Activity which consists (List< Double> list_r).
But make sure I am just showing a way of passing list. But by making List static It will consume memory even after you have finish the use of that arrayList.
You could use a double[] together with putExtra(String, double[]) and getDoubleArrayExtra(String).
Or you can use an ArrayList<Double> together with putExtra(String, Serializable) and getSerializableExtra(String) (the ArrayList part is important as it is Serializable, but the List interface is not).
You may use of bundle how to use: creating bundle and sending over to new activity or save arrayList in shared preferences: http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html
intent.putExtra("list",list_r);
now on the other activity in onCreate:
getIntent().getParcelableArrayListExtra("list");
use intent.putExtra();
intent.putExtra("array_list", list_r );
Convert double to string, and put it in ArrayList.
In the Activity providing the data, use Intent#putExtra():
double double1 = 0.05;
double double2 = 0.02;
ArrayList <String []> list = new ArrayList <String[]>();
list.add (new String [] {String.valueOf(double_1),String.valueOf(double_2)});
Intent i = new Intent (this,YourTargetActivity.class);
i.putExtra("list", list);
startActivity(i);
Then to retrieve, use Intent#getSerializableExtra() and cast to ArrayList :
ArrayList <String[]> list = (ArrayList<String[]>) getIntent().getSerializableExtra("list");
double double1 = Double.parseDouble(list.get(0)[0]) ;
double double1 = Double.parseDouble(list.get(0)[1]) ;
Hi I wanted to add new string to string array by this method but it doesn't work, because when I start new activity, then favaorites array isn't updated. Why ?
Resources res = getResources();
String[] favorites = res.getStringArray(R.array.favorites);
String[] planets = res.getStringArray(R.array.planets_array);
String[] temp = new String[favorites.length+1];
System.arraycopy(favorites,0,temp,0,favorites.length);
temp[favorites.length] = planets[mCounter];
favorites = temp;
In your case what you can do is use SharedPreferences to store the string into it. No array assigns requires and it is a much cleaner way to do it. Some links to get you started:
http://saigeethamn.blogspot.in/2009/10/shared-preferences-android-developer.html
http://saigeethamn.blogspot.in/2009/10/shared-preferences-android-developer.html
http://developer.android.com/guide/topics/data/data-storage.html
To solve your problem, you should be create an SQLite Database that houses all these properties. Then you should retrieve them from the Cursor (after you query your database) and use the results as necessary
Also another note is that you CANNOT add to the already defined R.array.* because its a precompiled resource.
I want to compare two variables the first arraylist and the second is string
How can i convert the String to arrayList to compare those values in the variables
thank you in advance
Hard to understand your question, but if your String is like this "cat,dog,elephant" then you can use String.split(",") to get a String array, and then convert that to an ArrayList like this:
ArrayList<String> arrayList = new ArrayList(Arrays.asList(myString.split(",")));