0

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

            }
        });
Zoe
  • 27,060
  • 21
  • 118
  • 148
Gusti
  • 69
  • 3
  • 11

1 Answers1

0

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

SamiAzar
  • 1,260
  • 13
  • 29