use the selected item of a spinner - android

I am little bit stuck and need some ideas of how can I use the information that is selected from the spinner.
first the spinner is populated via Web service, by this code on the Asynctask:
#Override
protected Void doInBackground(Void... unused) {
...
...
...
HttpTransportSE transportSE = new HttpTransportSE(URL);
try{
//Web service call
transportSE.call(SOAP_ACTION_BRING_NEEDS, envelope);
//create SoapPrimitive and obtain response
resultsRequestSOAP = (SoapObject)envelope.getResponse();
int intPropertyCount = resultsRequestSOAP.getPropertyCount();
strNeeds = new String[intPropertyCount];
for(int i= 0;i< intPropertyCount; i++)
{
//Format the information from the web service
Object property = resultsRequestSOAP.getProperty(i);
if (property instanceof SoapObject) {
SoapObject needsList = (SoapObject) property;
strNeeds[i] = needsList.getProperty("Descripcion").toString();
}
}
then on the postExecute I fill the spinner calling a method spinnerNeeds():
public void spinnerNeeds() {
//Needs Spinner Control
spnNeeds = (Spinner)findViewById(R.id.spnNeeds);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, strNeeds);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnNeeds.setAdapter(adapter);
spnNeeds.setSelection(1);
spnNeeds.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Todo
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
the thing is that the spinner is populated by the strNeeds[] with the property ("Descripcion"), but the web service response have 3 properties, and I need another property call "Codigo" so that information can be sended to another activity. How can I validate after choosing a option on the spinner that be validate with the "codigo" that I also need?
I was thinking on creating another String[] strCode and save the property "Codigo" value inside the FOR() as I did with the "Descripcion" property... but if I pick an option on the spinner how can I validate that strCode??
PD: The "Codigo" property do not contain ascendance values, for example the first value is not 1,2,3,4.... they have random values...

The answer will be quite complex, but once you understand it's very simple.
First you'll need to create an object say, NEED with 3 properties(Description, Codigo..)
Next, instead of using an arrayadapter of type String, use arrayadapter of type NEED.
Next, in your custom class NEED, override the toString() method such that it returns the value of the property that needs to be displayed in the spinner.
Now, the selected item will return the NEED object, from which you get the value of the 'Codigo' property.
class Need{
String description, codigo, property3;
public Need(String desc, String codigo, String prop3)
{
this.description = desc;//similarly for other 2 properties
}
#override
private String toString()
{
return this.description;
}
}
strNeeds = new Need[intPropertyCount];
for(){
strNeeds[i] = new Need();
}
ArrayAdapter<Need> adapter = new ArrayAdapter<Need>(this,android.R.layout.simple_list_item_1, strNeeds);

Related

how to show spinner from retrofit

I have a form using spinner, the data spinner I get from database using retrofit 2 , I have a field id_fish and fish_name, I would like to show fish_name but id_fish that saved in database.
I success to show the fish_name in android spinner but when i want to save the form into database is fish_name ,
how to save id_fish while the displayed in spinner is fish_name
example as in html :
<select>
<option value="001">Tuna</option>
<option value="002">Shark</option>
<option value="003">Dolphin</option>
<select>
This is My Function:
private initSpinner()
{
List<DataFish> dataFish= response.body().getData();
List<String> idFish = new ArrayList<String>();
List<String> fishName = new ArrayList<String>();
for (int i = 0; i < dataFish.size(); i++){
idFish.add(dataFish.get(i).getId_fish());
nameFish.add(dataFish.get(i).getFish_name());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(LelangActivity.this,
android.R.layout.simple_spinner_item, nameFish);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerFish.setAdapter(adapter);
}
This is spinner SetOnclickListener :
spinnerFish.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String fishName= parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
If the fish name is unique filed you can search on dataFish to get the equal id. I mean in onItemSelected write something like this:
for (DataFish data : dataFish) {
if (data.getFish_name().equls(fishName) {
data.getId_fish(); //here is your fish id
}
}
EDIT: If your fish name filed is not unique and it's possible that two fish with the same name has the different id, you must implement custom adapter for spinner and in getDropDownView method define which fish is selected. for implement custom adapter you can see here

How to get array index of selected item from AutoCompleteTextView?

I have a user data lie names etc. coming from database which is being populated to AutoCompleteTextView but the position in ItemCLickListener is of the position as displayed in the auto complete list.
I want the array index, and getting string from the adapter won't work because the same names can be there too.
Update
eg. In the database I have 4 entries abc, xyz, abc, pqrq along with some other data in other fields. These names are stored in an array.
So when I click abc, I want the other data to be fetched as well which could be done only if I know the array index of selected item.
Help!
Solution :
Customise the auto_complete_tv_adapter for its items.
Adapter list items will be model wich will hold the name with others data.
Any selected item you will have data model with all other values handy.
sample : https://www.androidcode.ninja/android-autocompletetextview-custom-arrayadapter-sqlite/
Instead of using an array of Strings, you should create an array with custom objects in it.
First, create a new class like this:
class CustomObject {
public long id;
public String name;
public CustomObject(long id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return name;
}
}
Then, you get data from your database, which will be Strings, instead of storing only a String you can also add a unique id to the array which we will we use later.
So, for example, you can fill the array like this:
// this array should contain the items from your database, and a unique id
final CustomObject[] items = { new CustomObject(0, "test"), new CustomObject(1, "test"),
new CustomObject(2123123, "another name")};
Then make your AutoCompleteTextview click detector look like this:
textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomObject customObject = (CustomObject) parent.getItemAtPosition(position);
int index = -1;
for (int i = 0; i < items.length; i++) {
if (items[i].id == customObject.id) {
index = i;
break;
}
}
// now we have your index :)
Toast.makeText(MainActivity.this, "Your index = " + index,
Toast.LENGTH_SHORT).show();
}
});
And that's it, there is the index you need. Note that for large arrays, this method will be slow.

Pass String to Parse query from spinner

I've got a spinner with a list of states in an array that when a user selects it currently outputs which state they selected to the log, this is working as expected. The issue I'm facing now is when a user clicks a button once they have selected their state is pulling the data that pertains to that state from parse. My code is below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
// Add your initialization code here
com.parse.Parse.initialize(new com.parse.Parse.Configuration.Builder(getApplicationContext())
.applicationId("appidhere")
.clientKey("clientkeyhere")
.server("http://server.compute-1.amazonaws.com:80/parse/")
.build());
// find spinner object here
final Spinner locSpinner = (Spinner) findViewById(R.id.locSpinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.state_list, 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);
locSpinner.setAdapter(adapter);
locSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(final AdapterView<?> parent, View view,
final int position, long id) {
Log.v("item", (String) parent.getItemAtPosition(position));
final String item = locSpinner.getSelectedItem().toString();
Button search = (Button) findViewById(searchBtn);
final TextView txtState = (TextView) findViewById(R.id.txtState);
final TextView txtName = (TextView) findViewById(R.id.txtName);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ParseQuery<ParseObject> query = ParseQuery.getQuery(item);
query.whereStartsWith("Name", "Paws");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
Log.v("item", "Retrieved " + item.toString() + " state");
txtState.setText(item);
txtName.setText(item);
} else {
Log.d("item", "Error: " + e.getMessage());
}
}
});
}
});
}
I have initialized parse in onCreate but it am having trouble getting it to populate my TextView's with the fields. For right now all I'm trying to accomplish is getting the values returned and outputting it to log, but ultimate goal is to be able to have the values show up in the TextViews. Any help would be greatly appreciated!
If you haven't already, you can have parse log what it's doing like this:
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId(appId)
.clientKey("")
.server(serverUrl)
.addNetworkInterceptor(new ParseLogInterceptor())
.build()
You will also need this in your gradle file:
compile 'com.parse:parseinterceptors:0.0.2'
Most likely you're getting an HTML response, like a 404 or 500 or something like that, rather than the JSON that the parse SDK is expecting. 403 Not Authorized (off the top of my head, I might have the wrong code) is also common if the URL or application id is wrong. By logging the details you can see the URL it's using to initialize parse, and exactly what the response is in logcat.
Edit: in your state class define a method like this:
public String getName() {
return getString("name");
}
Then do this:
textView.setText(state.getName());

How to Disable the 2nd Spinner Item Which is selected Already in 1st Spinner in Android

I want to Convert the Languages. So i am using two Spinners one is "From Language" and Another one is for "To Language". If One Language is Selected in "From Language" Spinner, it shouldn't display (or it should be disabled) in 2nd spinner. how can i achieve it?
Ex. if i Select English in 1st Spinner, 2nd Spinner Shouldn't display English in its dropdown.
This is may not be the best way try this.
ArrayList<String> languages = new ArrayList<>();
languages.add("English");
languages.add("Hindi");
languages.add("Telugu");
languages.add("Tamil");
languages.add("Kannada");
languages.add("Malayalam");
// make a array list of languages
String option1 = null;
Spinner spinnerOption1 = (Spinner) findViewById(R.id.spinner1);
final ArrayAdapter<String> adapterOpton1 = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, languages);
spinnerOption1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOption1.setAdapter(adapterOpton1);
spinnerOption1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
option1 = adapterOpton1.getItem(position);
}
});
int selectedIndex;
for (String item : languages) {
if (item.equals(option1)) {
selectedIndex == languages.indexOf(item);
}
}
ArrayList<String> languages2 = languages;
languages2.remove(selectedIndex);
Spinner spinnerOption2 = (Spinner) findViewById(R.id.spinner2);
final ArrayAdapter<String> adapterOption2 = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, languages2);
spinnerOption2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOption2.setAdapter(adapterOption2);
Explanation:
lets create a arraylist with languages
bind it to the adapter on the spinner, on selection to the spinner one keep a track of that selection, then find the index of the selection in the arraylist.
create second arraylist with the same languages and find and remove the user selected item, create an adapter and bind the data.
Hope it helps.
Use Hashmaps it will be easier. Create an Adapter that uses Key Values for populating adapter.
This is a snippet I found from another link on how to do that, in case you are not familiar
public class HashMapAdapter extends BaseAdapter {
private HashMap<String, String> mData = new HashMap<String, String>();
private String[] mKeys;
public HashMapAdapter(HashMap<String, String> data){
mData = data;
mKeys = mData.keySet().toArray(new String[data.size()]);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int position) {
return mData.get(mKeys[position]);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
String key = mKeys[pos];
String Value = getItem(pos).toString();
//do your view stuff here
return convertView;
}
}
Credit What adapter shall I use to use HashMap in a ListView
Now for your management of the adapters.
LanguageOneMap.put (all your keys 0-whatever) value (english-whatever)
LanguageTwoMap.put (same as above)
LanguageAllMap.put (same as above)
Adapter 1 selects Language Callback(languageSelectedFromOneKey){
LanguageTwoMap.clearAll
LanguageTwoMap.put (all again)
LanguageTwoMap.remove(languageSelectedFromOneKey)
LanguageTwoAdapter.notifyDataSetChanged()
}
The above is just pseudo code meant to give the idea, not exact copy and paste. Hope that is enough to get you going. There are many ways to skin this cat, you could even use the same list for both adapters. Then when one is selected from one or the other, set a property of "selectedOtherLanguage" in the opposite adapter, then in the GetView method if data.get(pos) == selectedFromOtherListItem return, don't draw.
Many ways to do this, just a matter of how you want to do it. Goodluck.

displaying objects in a spinner rather than just strings

I'm building a dialog with a spinner. When the dialog is done, it calls a method of the parent activity with a string argument - the argument being the string value that was selected.
My current approach:
I'm setting up the spinner's array adapter like so:
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,
categoryNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);
categoryNames is a string array. When the dialog is done, the selected categoryName is used as the parameter to the method call on the parent activity.
What I really want to do:
What I actually want is to display a list of Category objects. The Category class has 2 properties - categoryId and categoryName. The spinner should still display the categoryNames in the drop-down view, but when the dialog is done, it should be able to unambiguously tell which Category was selected, and call the parent activity's callback method with the categoryId of the category that was selected.
There can be multiple Categoryies with the same categoryName.
Question: How to do the above?
There are a couple different way to do what you want:
Store the extra data in the adapter, like a SimpleAdapter, SimpleCursorAdapter, or custom one.
Use a Collection of custom objects instead of Strings, simply override the toString() method to present user readable Strings in the Spinner.
You seem to want to do the second option, so here's a generic example:
class Category {
int id;
String name;
public Category(int id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return name;
}
}
Your ArrayAdapter is almost the same:
List<Category> categories = new ArrayList<Category>();
// Add new items with: categories.add(new Category(0, "Stack");
ArrayAdapter<Category> adapter =
new ArrayAdapter<Category>(getActivity(), android.R.layout.simple_spinner_item,
categories);
...
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Category category = parent.getItemAtPosition(position);
Log.v("Example", "Item Selected id: " + category.id + ", name: " + category.name);
}
public void onNothingSelected(AdapterView<?> parent) {}
});

Categories

Resources