I have an array adapter(string), and would like to convert it to a List<String>, but after a little googling and a few attempts, I am no closer to figuring out how to do this.
I have tried the following;
for(int i = 0; i < adapter./*what?*/; i++){
//get each item and add it to the list
}
but this doesn't work because there appears to be no adapter.length or adapter.size() method or variable.
I then tried this type of for loop
for (String s: adapter){
//add s to the list
}
but adapter can't be used in a foreach loop.
Then I did some googling for a method (in Arrays) that converts from an adapter to a list, but found nothing.
What is the best way to do this? Is it even possible?
for(int i = 0; i < adapter.getCount(); i++){
String str = (String)adapter.getItem(i);
}
Try this
// Note to the clown who attempted to edit this code.
// this is an input parameter to this code.
ArrayAdapter blammo;
List<String> kapow = new LinkedList<String>(); // ArrayList if you prefer.
for (int index = 0; index < blammo.getCount(); ++index)
{
String value = (String)blammo.getItem(index);
// Option 2: String value = (blammo.getItem(index)).toString();
kapow.add(value);
}
// kapow is a List<String> that contains each element in the blammo ArrayAdapter.
Use option 2 if the elements of the ArrayAdapter are not Strings.
Related
I am trying to read json array without object name, and pass it to a list.
My json looks like :
"facilites": [
"Pool",
" Air Conditioning",
" Pets Allowed",
" Fitness center",
" Kitchen",
" Internet",
" Sona"
]
I am trying to retrieve it using the following code -
for (int l = 0; l < chaletFacilities.length(); l++){
String facilities = chaletFacilities.getString(l);
list = new ArrayList<String>();
list.add(facilities);
}
Inside the main loop I put to my pojo class chalets.setList(list);
The issue is in this line list.add(facilities); it only add the last element. After looping through all, list carry sona only.
Your list should be instantiated outside the loop.
list = new ArrayList<String>();
for (int l = 0; l < chaletFacilities.length(); l++){
String facilities = chaletFacilities.getString(l);
list.add(facilities);
}
An improvement would be directly add string to list instead of capturing it into a string variable like list.add(chaletFacilities.getString(l))
Move initialization of your ArrayList outside of your loop.
Do like this
list = new ArrayList<String>();
for (int l = 0; l < chaletFacilities.length(); l++){
list.add(chaletFacilities.getString(l))
}
What you doing is initializing yourlist again and again and adding the element. So while last iteration the list is getting initialized again and only single element is being added to it.
ArrayList list = new ArrayList<String>();
for (int l = 0; l < chaletFacilities.length(); l++){
String facilities = chaletFacilities.getString(l);
list.add(facilities);
}
You are creating the new list always. So your list size will be 1 with the last value in chaletFacilities array.
Solution: Keep your list initialization outside the for loop as below, and add all the values under the array into single list you created in the top.
list = new ArrayList<String>();
for (int l = 0; l < chaletFacilities.length(); l++)
{
list.add(chaletFacilities.getString(l));
}
What I'm trying to is making a list which contains series of numbers like [1,2,3,4,5,6...100].
In Java, it is simple using 'range' so I tried to find similar class in android.
Therefore, I found that some classes like Range and Intstream, but I don't know how to use them.
I'll be appreciated if you teach me how can I get my purpose, thanks.
You could write a simple function which would look like this:
public List<Integer> buildList(int maximum) {
List<Integer> list = new ArrayList();
for (int i = 1; i <= maximum; i++) {
list.add(i);
}
return list;
}
And a call which produces your desired result would look like this:
List<Integer> list = buildList(100);
If you want an array instead of a list, do this:
int[] array = list.toArray(new int[list.size()]);
int size = 100;
ArrayList<Integer> list = new ArrayList<>(size);
for (int i = 1; i <= size; i++) {
list.add(i);
Log.i("Value is = ", i+"");
}
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
.....
You don't need to define the size because ArrayList is dynamically
while in some other language we use list[index] to get the value.
But here we use list.get(index) to do that.
I have:
a String array with an unknown length that's populated with unknown items (let's say fish, bird, cat)
an ArrayAdapter and a Spinner that displays the items
a variable that contains one unknown item from the string array (let's say cat)
I want to set the Spinner to the value from the variable (cat). What's the most elegant solution? I thought about running the string through a loop and comparing the items with the variable (until I hit cat in this example), then use that iteration's # to set the selection of the Spinner, but that seems very convoluted.
Or should I just ditch the Spinner? I looked around and found a solution that uses a button and dialog field: https://stackoverflow.com/a/5790662/1928813
//EDIT: My current code. I want to use "cow" without having to go through the loop, if possible!
final Spinner bSpinner = (Spinner) findViewById(R.id.spinner1);
String[] animals = new String[] { "cat", "bird", "cow", "dog" };
String animal = "cow";
int spinnerpos;
final ArrayAdapter<String> animaladapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, animals);
animaladapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bSpinner.setAdapter(animaladapter);
for (Integer j = 0; j < animals.length; j++) {
if (animals[j].equals(animal)) {
spinnerpos = j;
bSpinner.setSelection(spinnerpos);
} else {
};
}
(Temporarily) convert your String array to a List so you can use indexOf.
int position = Arrays.asList(array).indexOf(randomVariable);
spinner.setSelection(position);
EDIT:
I understand your problem now. If your String array contains all unique values, you can put them in a HashMap for O(1) retrieval:
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < animals.length; i++) {
map.put(animals[i], i);
}
String randomAnimal = "cow";
Integer position = map.get(randomAnimal);
if (position != null) bSpinner.setSelection(position);
String[] temp = new String[adapter.getCount()];
for(int i = 0; i < adapter.getCount(); i++)
temp[i] = adapter.getItem(i).toString();
List<String> list = Arrays.asList(temp);
Collections.sort(list);
adapter.clear();
comment = new Comment();
for(int i = 0; i < temp.length; i++)
{
comment.setComment(temp[i]);
System.out.println("comment is: " + comment.getComment());
adapter.insert(comment, i);
System.out.println("adapter is: " + adapter.getItem(i));
}
for(int i = 0; i < adapter.getCount(); i++)
System.out.println(adapter.getItem(i));
The code above performs the sorting of the ArrayAdapter which is typed ; a helper class as I am using SQLiteHelper and SQL database.
Ok so I verify, after clearing all data within the ArrayAdapter, that the data is added within a lexicographic sorted order.
However, by the time I reach the final for loop to verify this, the ArrayAdapter has replicated the last item in the list at every index. This is weird and makes no sense to me. Of course this is also reflected on the screen.
Can you provide assistance to understand what is going please?
You are using the same instance of 'Comment' throughout the ArrayAdapter. Hence, all positions of the ArrayAdapter have the exact same 'comment' object reference. This single instance has been set to the final string from the original list and so all ListView items will look the same. The solution is to move the instantiation of 'comment' into the for loop to create a unique 'comment' instance for each adapter position. I've also slightly optimized your code.
// -- Count used repeatedly, particularly in for loop - execute once here.
int orgCount = adapter.getCount();
String[] temp = new String[orgCount];
for(int i = 0; i < orgCount; i++)
temp[i] = adapter.getItem(i).toString();
List<String> list = Arrays.asList(temp);
Collections.sort(list);
// -- Prevent ListView refresh until all modifications are completed.
adapter.setNotifyOnChange(false);
adapter.clear();
for(int i = 0; i < temp.length; i++)
{
// -- Instantiation moved here - every adapter position needs a unique instance.
comment = new Comment();
comment.setComment(temp[i]);
System.out.println("comment is: " + comment.getComment());
// -- Changed from insert to add.
adapter.add(comment);
System.out.println("adapter is: " + adapter.getItem(i));
}
for(int i = 0; i < adapter.getCount(); i++)
System.out.println(adapter.getItem(i));
// -- Auto notification is disabled - must be done manually.
adapter.notifyDataSetChanged(true);
// -- All modifications completed - change notfication setting if desired.
adapter.setNotifyOnChange(true);
EDIT
Also, since you're inserting/adding one at a time, you might want to delay notifyDataSetChanged from executing until after all modifications are completed. This will prevent the ListView from refreshing on every modification. I've included it in the code above.
call adapter.notifyDataSetChanged() when all modification are done..
I am using gooleplaces API. I have a response in json, but the problem is I want to populate listview according to distance. I make the sorted distance arraylist in ascending order using collections.sort(), but how do I sort other lists based on this sorted list to populate my listview correctly?
If you are creating separate lists, then you need to your define method, and if you are using list of single collection, or data structure, you can define your comparator, then call sort on this, list.
Finally I resolve my problem using bubble sort.
if (distanceList.size()>1) // check if the number of orders is larger than 1
{
for (int i=0; i<distanceList.size()-1; i++) // bubble sort outer loop
{
for (int j=0; j < distanceList.size()-1-i; j++) {
if (distanceList.get(j)>(distanceList.get(j+1)) )
{
int temp = distanceList.get(j);
distanceList.set(j,distanceList.get(j+1) );
distanceList.set(j+1, temp);
String temp1 = nameList.get(j);
nameList.set(j,nameList.get(j+1) );
nameList.set(j+1, temp1);
String temp2 = vicinityList.get(j);
vicinityList.set(j,vicinityList.get(j+1) );
vicinityList.set(j+1, temp2);
String temp3 = latList.get(j);
latList.set(j,latList.get(j+1) );
latList.set(j+1, temp3);
String temp4 = longList.get(j);
longList.set(j,longList.get(j+1) );
longList.set(j+1, temp4);
}
}
}
}