Salut dans le code ci-dessous décrit le spinner .Dans le spinner Am affichant différents types de noms de bâtiments pour appeler l'API. En fonction de la réponse, je mets le nom du bâtiment sur le spinner.
De la réponse: ID et nom
Maintenant, ma question est lorsque l'utilisateur a sélectionné un nom de bâtiment à partir du spinner. quelqu'un peut-il m'aider à le faire.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener () { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub int pos=spinner.getSelectedItemPosition (); String ids= String.valueOf (arrayList1.get (pos)); //String obj; System.out.println (ids); } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub } }); }
OnitemclickListner:
private void selectBuilding() { handler.postDelayed(new Runnable() { @Override public void run() { // Write code for your refresh logic progressDialog = new ProgressDialog (getActivity ()); progressDialog.setIndeterminate(true); progressDialog.setMessage("Communicating..."); progressDialog.setCanceledOnTouchOutside(false); progressDialog.setCancelable(false); progressDialog.show(); OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(API.URL_BASE) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .client (client) .build(); API service = retrofit.create (API.class); final Call<Managebuilding> userCall = service.getbuildinglist (); userCall.enqueue(new Callback<Managebuilding> () { @Override public void onResponse(Call <Managebuilding> call, Response <Managebuilding> response) { if (response != null && response.code ( ) == 200 && response.isSuccessful ( )) { Managebuilding building = response.body (); String Name = null,Id; String Lists=new Gson ( ).toJson (response.body ()); // JSONArray jsonArray=new JSONArray (); // JSONObject jsonObject = null; try { JSONObject jsonObject = new JSONObject (Lists); JSONArray result = jsonObject.getJSONArray ("list"); System.out.println (result); //JSONArray result = jsonArray.getJSONArray ("ID"); arrayList = new ArrayList <> ( ); arrayList1 = new ArrayList <> ( ); for (int i = 0; i <result.length(); i++) { Id=result.getJSONObject (i).getString ("ID"); Name=result.getJSONObject (i).getString ("Name"); arrayList.add (Name); arrayList1.add (Id); } ArrayAdapter <String> adapter = new ArrayAdapter <String> (getContext (),android.R.layout.simple_spinner_item, arrayList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } catch (JSONException e) { e.printStackTrace ( ); } progressDialog.dismiss ( ); } else { progressDialog.dismiss ( ); Log.d ("Response errorBody", String.valueOf (response.errorBody ( ))); } } @Override public void onFailure(Call<Managebuilding> call, Throwable t) { // lv.setAdapter (adapter); System.out.println("onFailure"); System.out.println(t.fillInStackTrace()); progressDialog.dismiss(); Toast.makeText(getActivity (), "Some error occurred -> ", Toast.LENGTH_LONG).show();; // progressDialog.dismiss(); } }); } }, 5000); return ; }
3 Réponses :
String selectedBuildingId=""; spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener () { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { selectedBuildingId=position; // or you can get your id using your pojo class array //like 'buildingList.get(position).getID();'' yourNextSpinnerArray.add(selectedBuildingId); //set yourNextSpinnerArray for your next spinner } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub } }); }
La réponse "Nice umang" semble bien.
Pour moi, je regarde au-delà de ça, j'approfondis ça.
J'ai construit une classe BaseTextSpinnerAdapter
et j'ai la méthode de remplacement getItemId
et je lui fais renvoyer ce que je veux.
@Override public long getItemId(int position) { if (mItems.get(position) != null) { return mItems.get(position).getObjectId(); } return -1; }
Commencez par créer une classe de modèle comme Building
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener () { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // here you can retrive you building info by positon Building building = buildingList.get(position) String id = building.getId(); String name = building.getName(); // Now you can use your id or name to do whatever you want. System.out.println (id); System.out.println (name); } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub } }); }
Ensuite, créez un ArrayList
Type de Building
dans votre activité
comme suit
userCall.enqueue(new Callback<Managebuilding> () { @Override public void onResponse(Call <Managebuilding> call, Response <Managebuilding> response) { if (response != null && response.code ( ) == 200 && response.isSuccessful ( )) { Managebuilding building = response.body (); String Lists=new Gson ( ).toJson (response.body ()); // JSONArray jsonArray=new JSONArray (); // JSONObject jsonObject = null; try { JSONObject jsonObject = new JSONObject (Lists); JSONArray result = jsonObject.getJSONArray ("list"); System.out.println (result); //JSONArray result = jsonArray.getJSONArray ("ID"); arrayList = new ArrayList <> (); for (int i = 0; i <result.length(); i++) { String id=result.getJSONObject (i).getString ("ID"); String name =result.getJSONObject (i).getString ("Name"); // here you have create object of building using id and name Building building = new Building(id, name) buildingList.add(building); arrayList.add(name); } ArrayAdapter <String> adapter = new ArrayAdapter <String> (getContext (),android.R.layout.simple_spinner_item, arrayList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); }catch (JSONException e) { e.printStackTrace ( ); } progressDialog.dismiss ( ); } else { progressDialog.dismiss ( ); Log.d ("Response errorBody", String.valueOf (response.errorBody ( ))); } } @Override public void onFailure(Call<Managebuilding> call, Throwable t) { // lv.setAdapter (adapter); System.out.println("onFailure"); System.out.println(t.fillInStackTrace()); progressDialog.dismiss(); Toast.makeText(getActivity (), "Some error occurred -> ", Toast.LENGTH_LONG).show();; // progressDialog.dismiss(); } }); }
Et utilisez cette arraylist
dans votre réponse API
comme ci-dessous .
// declear it in global scope ArrayList<Building> buildingList; // and initialize it in `onCreate` buildingList = new ArrayList <> ();
Vous devez maintenant modifier votre setOnItemSelectedListener
comme suit.
public class Building{ private String id; private String name: public Building(String id, String name){ this.id = id; this.name = name; } public String getId(){ return id; } public String getName(){ return name; } }
Hope cela vous aide. Codage heureux
@id je deviens nul
J'ai suivi votre approche, mais j'obtiens que l'identifiant est nul
il ne doit pas être null
si vous n'avez rien manqué.
enregistrez également le paramètre ID dans une arraylist. Ensuite, utilisez le paramètre
position
de la méthodeonItemSelected
et obtenez l'ID de la nouvelle arraylist en utilisant la position cliquée.@RahulKhurana Position de l'élément que j'obtiens. Mais n'obtient pas l'ID sélectionné du spinner
Vous obtiendrez l'ID dans la liste des ID du tableau. utilisez arrayList.get (position) pour obtenir l'ID
@RahulKhurana S'il vous plaît, regardez mon code mis à jour
utilisez
String id = arrayList1.get (position);
à l'intérieur deonItemSelected
@RahulKhurana À l'intérieur de onItemselected seulement j'ai utilisé Non?
Oui c'est vrai ......
@RahulKhurana je reçois uniquement le nom et non l'identifiant
Utilisez-vous arrayList1 ??
mettez à jour votre dernier code dans la question.
@RahulKhurana oui j'utilise arrayList1
veuillez mettre à jour votre code dans la question