how to set spinner item position - android

I am creating an android app in which I want to add values in spinner i.e countries. I added them successfully, but I want to show my desire country at the top of the spinner list i.e I want to show Australia at the 0 index of the spinner. So how I can achieve this? Anyone please help me.
Here is my code:
MySpinnerAdapter adapter = new MySpinnerAdapter(SignUp.this, android.R.layout.simple_spinner_item, countryname);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_country.setAdapter(adapter);
spinner_country.setSelection(countryname.size() - 1);
spinner_country.setSelection(12);
Collections.sort(countryname);
Now I am doing this and it shows ArrayIndexOutOfBoundsException
String[] str = new String[countryname.size()-1];
str = countryname.toArray(str);
int indexTarget = 13;
String valueAtIndex = str[indexTarget];
for(int i = indexTarget; i > 0; i--){
str[i] = str[i-1];
}
str[0] = valueAtIndex;
for (int i = 0; i < str.length; i++)
{
System.out.println(str[i]);
}
List<String> stringList = new ArrayList<String>(Arrays.asList(str));
MySpinnerAdapter adapter = new MySpinnerAdapter(SignUp.this, android.R.layout.simple_spinner_item, stringList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_country.setAdapter(adapter);
spinner_country.setSelection(countryname.size() - 1);
Collections.sort(countryname);

If you want Australia to be at the first position in spinner then add it to zeroth index of your countryname.
You can start adding names to your countryname with Australia so that it will be at zeroth index and appear at first position in spinner.
spinner.setSelection(12) will select the 13th value from the array you are supplying to your adapter. It will not be at the first position.
EDIT
This is just an example, you need to modify accordingly. Here the original array is B, M, T, A, C, I want A to be first, so I need index of A. For your question you need the index of Australia
String[] str = {"B", "M", "T", "A", "C"};;
int indexTarget = 3;
String valueAtIndex = str[indexTarget];
for(int i = indexTarget; i > 0; i--){
str[i] = str[i-1];
}
str[0] = valueAtIndex;
for (int i = 0; i < str.length; i++)
System.out.println(str[i]);
Output
A
B
M
T
C
Now A is at first position.

Related

How to customize value for numbers in NumberPicker in android?

I have a number picker for setting a data limit in MB. right now, I have numberPicker, contains numeric values in sequence like [1,2,3,....., 2000 MB].
But I want a numberPicker that should contain numeric values like [100,200,300,...., 2000MB].
How can I do this?
Displayed array values for your picker
int NUMBER_OF_VALUES = 20; //num of values in the picker
int PICKER_RANGE = 100;
...
String[] displayedValues = new String[NUMBER_OF_VALUES];
//Populate the array
for(int i=0; i<NUMBER_OF_VALUES; i++)
displayedValues[i] = String.valueOf(PICKER_RANGE * (i+1));
/* OR: if the array is easy to be hard-coded, then just hard-code it:
String[] displayedValues = {"100", "200", "300", .....}; */
Set arr in your picker :
numPicker.setMinValue(0);
numPicker.setMaxValue(displayedValues.size()-1);
numPicker.setDisplayedValues(displayedValues);
get/set the value of the picker :
//To get the current value in the picker
choosenValue = displayedValues[numPicker.getValue()];
//To set a new value (let's say 150)
for( int i=0; i<displayedValues.length ; i++ )
if( displayedValues[i].equals("300") )
numPicker.setValue(i);
Try the code below
int start = 100;
String[] numbers = new String[20];
for(int i =0 ; i < 20 ; i++) {
numbers[i] = start + "";
start = start + 100;
}
NumberPicker numberPicker = (NumberPicker) findViewById(R.id.id_number_picker);
numberPicker.setMaxValue(20);
numberPicker.setMinValue(1);
numberPicker.setDisplayedValues(numbers);
final String[] nums = new String[21];
for(int i=0; i<nums.length; i++) {
nums[i] = Integer.toString((i+1)*100);
}
numberPicker.setMinValue(0);
numberPicker.setMinValue(19);
numberPicker.setDisplayedValues(nums);

Using a variable to switch to a certain spinner item

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

Array integer Android

ok so i create an array that has integers. The array displays five number from the min and max. How can i display all five numbers in a textview or edittext ? I tried:
nameofile.setText(al.get(x).toString());
but it only displays one?
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
String myString = TextUtils.join(", ", al);
lottonumbers.setText(myString);
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(0);
al.add(1);
al.add(5);
al.add(4);
al.add(3);
java.util.Collections.sort(al);//for sorting Integer values
String listString = "";
for (int s : al)
{
listString += s + " ";
}
nameofile.setText(listString);
You're currently only printing out one element (the one at index x). If you want to print them all in order, you can just join them using TextUtils.join().
Update: After seeing your edit, I think there's a better way to go about what you're trying to do. Instead of trying to pull the values one at a time, and update the list, why not just shuffle them, then use the above method?
Update 2: Okay, I think I finally understand your problem. Just a simple change, then.
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
StringBuilder text = new StringBuilder(); // Create a builder
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
if (i > 0)
text.append(", "); // Add a comma if we're not at the start
text.append(x);
}
lottonumbers.setText(text);
al.get(x).toString() will only get the value at index "x". If you want to display all values, you need to combine all of the values from the array into a single string then use setText on that string.
You are only showing one number of your array in the TextView, you must to concat the numbers to see the others results like:
for(Integer integer : al) {
nameofile.setText(nameofile.getText() + " " + al.get(x).toString());
}
Then i think you can show all number in one String.

sort array list from second item android

i have a array list for using it in spinner ,i have first value i spinner as title and i want to sort array list from second item in the spinner but i dont know how to do this i am using below trick but it sort whole array list including first item which is title so how to statr sorting from second item...
my code is below...
// this is my title ie. "provincia"
String select2= "Provincia";
if(!estado1.contains(select2)){
estado1.add(select2);
}
for (int i = 0; i < sitesList1.getEstado().size(); i++)
{
if(!estado1.contains(sitesList1.getEstado().get(i)))
{
estado1.add(sitesList1.getEstado().get(i));
Collections.sort(estado1);
}
use below code for show it in spinner...
final ArrayList<String> estado1 = MainMenu.barrio1;
final Spinner estado11 = (Spinner) findViewById(R.id.Spinner04);
ArrayAdapter<String> adapterbarrio = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, estado1)
estado11.setAdapter(adapterbarrio);
Why not remove the title / only add the title after the list has been sorted?
How about this
List<String> list = new ArrayList<String>();
// Fill list
String title = list.get(0);
list.remove(0);
Collections.sort(list);
list.add(0, title);
One way would be to split the arraylist like
estado1.subList(1,estado1.size()-1);
This would return a sublist excluding your title.
Use bubble sort! and start at index = 1!
final ArrayList<String> estado1;
for(int i=1; i<estado1.size() ; i++) {
for(int c=i; c<estado.size() ; c++) {
if(estado1.get(i).compareTo(estado1.get(c)))
{
String temp = estado1.get(i);
estado1.remove(i);
estado1.add(i, estado1.get(c));
estado1.remove(c);
estado1.add(c, temp);
}
}
}
PS: very bad performance

How to get Selected items from Multi Select List View

I am using an array adapter and to this am adding an array list of string s , the list is multi select , How can i get the values of list items clicked ?
my_contacts_list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice,conts_list);
my_contacts_list.setAdapter(adapter);
I was trying to do this ,
SparseBooleanArray positions = my_contacts_list.getCheckedItemPositions();
int size=positions.size();
int i=0;
while(i <= size){
conts_list.get(positions.get(i));
i++;
}
But position.get(i) is an array list , how to retrieve the selected items then ?
SparseBooleanArray.get returns a boolean, but I believe you need to check it for each position in your list, e.g.
int len = listView.getCount();
SparseBooleanArray checked = listView.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)) {
String item = cont_list.get(i);
/* do whatever you want with the checked item */
}
This API is a mess. Here is what works for me.
SparseBooleanArray checked = tags.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
if(checked.valueAt(i)) {
Tag tag = (Tag) tags.getItemAtPosition(checked.keyAt(i));
Log.i("xxxx", i + " " + tag);
}
}
I believe the fastest way to get the info out of this SparseArray is to iterate over the keys (actually I'm fairly sure that the solutions above won't work in all cases). The ListView will enter a pair (index, true) into the SparseBooleanArray for every selected index.
So the code might look like this:
SparseBooleanArray checked = lv.getCheckedItemPositions();
int size = checked.size(); // number of name-value pairs in the array
for (int i = 0; i < size; i++) {
int key = checked.keyAt(i);
boolean value = checked.get(key);
if (value)
doSomethingWithSelectedIndex(key);
}
I think the Answer from Daren Robbins is Wrong, here is my answer:
ArrayList<String> ids = extras.getStringArrayList("commonids");
SparseBooleanArray checked = lv.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
if(checked.get(i))
Log.i("CheckedItem", ids.get(checked.indexOfKey(i)));
}
Assume ids is an arraylist with the same size of the listview containing the ids of the items in the list view
The thing is you must iterate all the list view items but not checkedPositions.
Define the variables:
listView (The instance of you ListView)
names (the ArrayList you are )
saveCheckedName (save all checked name to this Arraylist)
SparseBooleanArray checkedPositions = listView.getCheckedItemPositions();
for (int i = 0; i < subjectListView.getCount(); i++) {
if (checkedPositions.get(i) == true) {
saveCheckedName.add(names.get(i));
}
}
Like so many other things, multi-select ListViews are a real problem in Android.
Instead of simply requesting the selected items as a List of Objects (dear Google, this is what we expect):
List selected_items = my_list_view.getSelectedItems();
we are forced to use this stupendously ridiculous API:
SparseBooleanArray checked = my_list_view.getCheckedItemPositions();
int num_selected = 0;
for(int i = 0; i < checked.size(); i++) {
if(checked.valueAt(i)) {
num_selected++;
int key = checked.keyAt(i);
boolean value = checked.get(key);
if (value) {
//
}
}
}
The horribly named SparseBooleanArray is populated by calling the even more horribly named getCheckedItemPositions() on the ListView. But instead of returning the positions of each selected/checked item in the list, it returns the position of every item in the list that WAS EVER touched, whether it is currently actually selected or not! Unbelievable, but true.
To calculate whether the item is ACTUALLY CURRENTLY checked, we are forced to test valueAt(i) for truthiness while looping through the 'was ever touched' array of items.
In addition to this madness, if we want to calculate the number of selected items, we appear to be forced to increment our own counter (e.g. num_selected).
With APIs like this one, it's little wonder developers are an angry lot!
I think another option is to just keep track of all of this yourself.
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View selectedItem,
int position, long itemId) {
//Keep a reference here, and toggle a global variable.
HOW I SOLVED THE ISSUE with a second ArrayList :
Created a second ArrayList instance
Updated that ArrayList instance with the UNCHECKED items
added it to the my listadapter
public void removeSelectedItems(){
updatedList = new ArrayList<String>(); //initialize the second ArrayList
int count = lv.getCount(); //number of my ListView items
SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
for (int i=0;i < count;i++){
if(!checkedItemPositions.get(i))
updatedList.add(liveNames.get(i)); //liveNames is the current ArrayList
Log.e("TEST", liveNames.get(i));
}
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, updatedList);
setListAdapter(adapter);}
Hope it will be helpfull :)
Foo objectAtCheckedRow = null;
for (int i = 0; i < positions.size(); i++) { //positions.size() == 2
objectAtCheckedRow = adapter.getItem(positions.keyAt(i));
//Do something significant with object here
}
A couple things to understand
It's a key-value pair list.
The key is the index of a row, get it with positions.keyAt(i)
The value is whether the row at that index is checked or not(true or false), get it with positions.valueAt(i)
positions.get(i) returns the same boolean as .valueAt(i)
Careful not to get indexes mixed up. You do not need to(and should not) iterate over your whole list. Use int i to iterate over positions, but don't use i to get objects from your list
But in this specific case(listView.getCheckedPositions()) it only fills in true(checked rows), so you don't actually need to verify using .get(i) nor .valueAt(i)
Example:
Let's say you've checked the 5th and 8th items in the list(index 4 and 7), then positions.size() == 2 and i will be 0 and then 1
So when:
i == 0 then keyAt(i) == 4
i == 1 then keyAt(i) == 7
i == 0 OR i == 1 then valueAt(i) == true AND get(i) == true
FYI, Here is how Google did it:
Excerpted from http://mytracks.googlecode.com/hg/MyTracks/src/com/google/android/apps/mytracks/util/Api11Adapter.java
/**
* Gets the checked positions in a list view.
*
* #param list the list view
*/
private int[] getCheckedPositions(ListView list) {
SparseBooleanArray positions = list.getCheckedItemPositions();
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for (int i = 0; i < positions.size(); i++) {
int key = positions.keyAt(i);
if (positions.valueAt(i)) {
arrayList.add(key);
}
}
int[] result = new int[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
result[i] = arrayList.get(i);
}
return result;
}
and here is my adapted version:
public static List<Integer> getAbsListViewCheckedItemPositions(AbsListView absListView) {
SparseBooleanArray checked = absListView.getCheckedItemPositions();
List<Integer> positions = new ArrayList<>();
int checkedSize = checked.size();
for (int i = 0; i < checkedSize; i++) {
if (checked.valueAt(i)) {
positions.add(checked.keyAt(i));
}
}
return positions;
}
We use this in our Android utility class. The generics help prevent compiler warnings, but you can remove them if your adapter returns multiple types.
public static <T> Collection<T> getCheckedItems(ListView listView) {
Collection<T> ret = new ArrayList();
SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions();
for (int i = 0; i < checkedItemPositions.size(); i++) {
if (checkedItemPositions.valueAt(i)) {
T item = (T) listView.getAdapter().getItem(checkedItemPositions.keyAt(i));
ret.add(item);
}
}
return ret;
}
Very simple, use below code
listViewRequests.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
AppCompatCheckedTextView checkBox = (AppCompatCheckedTextView) view;
if (checkBox.isChecked() == true){
Log.i("CHECK",checkBox.isChecked()+""+checkBox.getText().toString());
}
}
});
for(int i =0; i< listView.getAdapter().getCount(); i++){
if(listView.isItemChecked(i)){
listView.getAdapter().getItem(i); // item
}
}
should be used after setAdapter() method

Categories

Resources