Combobox in Android - android

I need something like a combobox in access in android, i want to choose the customer per name, but in the background the id should be chosen. how to do?

In android comboboxes are called spinner. Nevertheless, gnugu has posted in his blog his own implementation of a combobox. http://www.gnugu.com/node/57
A simple example of an spinner would be the following.
First, edit your XML code with something like this
Spinner android:id="#+id/Spinner01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Your java code should include something like this, the options are very intuitive. If you are using eclipse it will suggest you some options
public class SpinnerExample extends Activity {
private String array_spinner[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Here come all the options that you wish to show depending on the
// size of the array.
array_spinner=new String[5];
array_spinner[0]="option 1";
array_spinner[1]="option 2";
array_spinner[2]="option 3";
array_spinner[3]="option 4";
array_spinner[4]="option 5";
Spinner s = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, array_spinner);
s.setAdapter(adapter);
}
}

An alternate solution to the need to link Customer ID to the selected Item.
To have a simple selector with text you cause make use of the array resources
Setup the Spinner in XML
<Spinner android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/colors"/>
If you need more data linked with the spinner you can use Objects to populate the spinner.
The default functionality of an ArrayAdapter is to call toString() on any object and pass that to the view.
if (item instanceof CharSequence) {
text.setText((CharSequence)item);
} else {
text.setText(item.toString());
}
You can implement toString() in your object and it will display correctly in the spinner. Then to get the data back from the array you can add a handler onto ItemSelected and get the object back from the seed array or the ArrayAdapter.
ArrayAdapter adapter = new ArrayAdapter(activity, android.R.layout.simple_spinner_item, arrayOfObjects);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
Log.d(arrayOfObjects[position]._id);
}
});

Related

My spinner does not display the selected item and doesn't call onItemSelected

I have an android spinner that allows the user to select a translation. I can tap the spinner and it will reveal a list with available translations, but when I select an item in the list it will not appear in the spinner and neither does the onItemSelected method get called.
Here is the xml code for the spinner:
<Spinner
android:id="#+id/trans_list"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/chap_list"
android:layout_weight="1" />
Here is the relevant code for initiating the spinner. (edit) This code is ran from inside a Fragment class and not from my MainActivity class:
trans_spinner = v.findViewById(R.id.trans_list);
ArrayAdapter<String> adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_spinner_dropdown_item, translations);
trans_spinner.setAdapter(adapter);
trans_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String translation = trans_spinner.getItemAtPosition(trans_spinner.getSelectedItemPosition()).toString();
Log.d("trans", translation);
Toast.makeText(view.getContext(), translation, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Log.d("test", "1");
}
});
trans_spinner.setSelection(1);
Neither the onItemSelected() or onNothingSelected() method gets called when I select an item. I found this page describing an issue very similar to mine:
Android Spinner will not launch OnItemSelected and current selected item is not displayed in Spinner
However the user did not present a clear solution to their problem so it doesn't help me much.
I am not sure if it is relevant, but the items in the spinner are taken from an online webpage that provides JSON data to fill the spinner. This seems to work, as the options do appear in the spinner list. The issue is that upon selecting one of them, the spinner appears empty and the listener doesn't do anything.
So I found out that the issue was actually because of how I obtained the list of strings to put inside the spinner. As mentioned in the original post, I am loading the string values from a webpage in JSON format. I'm using the Retrofit2 API for this.
The problem was caused by the fact that I was downloading this data and then initializing the spinner both in the onCreateView() method of my fragment. What I did to fix it is I created a new method that initializes the spinner, and then I would call it from the onResponse() method used by the Retrofit API. This means that it doesn't initialize the spinner until after it has finished downloading/populating the list of strings.
<Spinner
android:id="#+id/planets_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
f the available choices for your spinner are pre-determined, you can provide them with a string array defined in a string resource file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>
With an array such as this one, you can use the following code in your Activity or Fragment to supply the spinner with the array using an instance of ArrayAdapter:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
When the user selects an item from the drop-down, the Spinner object receives an on-item-selected event.
To define the selection event handler for a spinner, implement the AdapterView.OnItemSelectedListener interface and the corresponding onItemSelected() callback method. For example, here's an implementation of the interface in an Activity:
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
...
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
The AdapterView.OnItemSelectedListener requires the onItemSelected() and onNothingSelected() callback methods.
Then you need to specify the interface implementation by calling setOnItemSelectedListener():
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
If you implement the AdapterView.OnItemSelectedListener interface with your Activity or Fragment (such as in the example above), you can pass this as the interface instance.
Java Code
public class MainActivity extends AppCompatActivity {
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = findViewById(R.id.spinner);
List<String> translations = new ArrayList<>();
translations.add("string1");
translations.add("string2");
translations.add("string3");
translations.add("string4");
translations.add("string5");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, translations);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object getPosition = parent.getItemAtPosition(position);
String value = getPosition.toString();
Toast.makeText(getActivity(), value, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
XML Code
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner">
</Spinner>
Add this code after init adapter
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
And to get the selected item inside onItemSelected
translations.get(position)

2 dependent spinner

if i have 2 spinner the second depend in the first
i will retriever the info of the second spinner from MySQL database depend in the choose of first spinner i succuflly get the id of the first spinner but i do not
how to send it to the other cause it not work with me
i have class MainActivity that have:
new LoadAllCourses().execute(); //first spinner generation
new LoadAllSection().execute(); //second spinner
in class LoadAllCourses extends AsyncTask<String, String, String>
adapter1 = new MyCustomAdapter(MainActivity.this,
android.R.layout.simple_spinner_item,
coursesList);
spinner1.setAdapter(adapter1); // Set the custom adapter to the spinner
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
HashMap<String, String> map12 = coursesList.get(position);
String id3 = map12.get("CourseID");
// Do something
Log.d("All coursesdddddddddddddddddddddddddddddddddddd: ", id3);
// Do something
}
#Override
public void onNothingSelected(AdapterView<?> adapter) {
}
});
now i want to get the id3 and send it to
class LoadAllSection extends AsyncTask<String, String, String>
but it is not work
how can i solve it if i have as i said
If I have understood your question, you require the selection on the first spinner to for the basis of a search from a database to populate the second spinner.
If in adapter 1 (adapter1 = new MyCustomAdapter(MainActivity.this,
android.R.layout.simple_spinner_item,
coursesList);) courseList is an array, one can get the selected item from the spinner in the setOnItemSelectedListeneras follows courseList [position].
Having obtained the selected item, you then require a function to perform the query in the database, say load_all_selection(courseList [position]) which should return an array of results from your database.
Since it returns an array you can define adapter 2 as follows
adapter2 = new MyCustomAdapter(MainActivity.this,
android.R.layout.simple_spinner_item,
load_all_selection(courseList [position]));
and assign it to the second spinner spinner2.setAdapter(adapter2);
All this can be done from within the setOnItemSelectedListener part, except maybe for the definition of the load_all_selection(...) function.
I hope I understood you question and this helps. If it doesn't you can still look around for a different solution.

Returning a String from ArrayAdapter

I have created a Spinner and ArrayAdapter as follows:
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
final ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
this, R.array.units_array1, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
The units_array1 is a string array declared in a xml file like this:
<string-array name="units_array1">
<item>Centimeters</item>
<item>Meters</item>
<item>Kilometers</item>
<item>Inches</item>
<item>Foots</item>
<item>Miles</item>
</string-array>
Now I want to implement some If-ELSE conditions that are based on the elements in string-array. I Have researched a lot on the internet for this but haven't found out any solution that works. Please help me in implementing a function that returns the individual elements from the string-array using the adapter.
ArrayAdapter.getItem(position), where position is the index into the array. If you want to get the currently selected item in your Spinner, use Spinner.getSelectedItemPosition() as the parameter to getItem().
This will return a CharSequence because of you your adapter is typed. If you want that values to return as Strings, redefined your adapter as ArrayAdapter<String>
HTH!
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id3) {
final String scale = adapter1.getItem(position);
// scale is gonna be "Centimeters" or "Meters", etc...
if (scale.equals("Centimeters")) {
// do something
} else if (scale.equals("Meters")) {
// do something else
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
ArrayAdapter has getItem(int position), which (if you know the position) will get you the String. ArrayAdapter also has getCount(), so you can write a simple for loop to get each element if you don't know its position.
You need to set a OnItemSelectedListener to your spinner. Then in the listener you'll be notified about the selection event. Check the official sample on this: Spinner.

How to dynamically change the Spinner's items

I have two spinners. Country and City.
I want to dynamically change the City's values upon Country selection.
I know how to create and initialize the values of Country but don't know how to set and change the City's values.
Any guidance is appreciated.
UPDATES1
The problem is, I don't have idea on how to update the content of City Spinner. I know listener and other basics on how to create a fixed spinner.
For the second spinner, use an Adapter over a List<String> (or whatever your City representation is). After changing the contents of the list, call notifyDataSetChanged on the adapter, and that will do.
You need to get a programmatic reference to the spinner, something like this:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Then to update your city's values, use an OnItemSelectedListener, like this:
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
//update content of your city spinner using the value at index,
// id, or the view of the selected country.
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
Finally, you need to bind the listener to the country spinner like this:
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
see here for reference: http://developer.android.com/resources/tutorials/views/hello-spinner.html

android spinner performClick onItemSelected

I have a little problem with a spinner.
I create a Spinner the user click a Button. The Spinner is shown as it should be, but when onItemSelected should be called nothing happens.
Here is the code
public void setUpSpinner(){
spinner = new Spinner(this);
CustomArrayAdapter<String> adapter = new CustomArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getAsStrings());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
public void onClick(View view) {
spinner.performClick();
}
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String getName = (String) spinner.getSelectedItem();
getListFromName(getName);
}
Anyone knows what is wrong here?
Thank you guys.
Solved the problem by adding a Spinner in my xml with height and width set to zero.
This looks enough like the turorial, so refer back to that. See below:
I don't see this, but does the main class implement OnItemSelectedListener? Also, You'll want to instantiate the Spinner inside the onCreate() within the main class body.
This line needs to be within the onCreate();
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
why do you have spinner = new Spinner(this) in the set-up ?
surely you already have a Spinner in the XML of your layout, then you simply do spinner = (Spinner) findViewById(R.id.WHATEVER_THE_ID_IS_IN_THE_XML); so you don't need a new
P.S. this is how I define a Spinner in an XML layout
<Spinner
android:id="#+id/SPINNER_ID"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_horizontal" />

Categories

Resources