Search code examples
androidretrofitandroid-spinner

Dynamically populating spinner using Retrofit?


Here what am looking for is need to populate spinner which is a json response from rest service using retrofit . After a long research i cant find any samples on this can anyone share some sample based on this this would be very useful for me thanks in advance!


Solution

  • first create theretrofitapi interface

    /**
     * reCreated by goodlife on 1/11/2016.
     */
    import java.util.List;
    
    
    import retrofit.Callback;
    import retrofit.client.Response;
    import retrofit.http.Field;
    import retrofit.http.FormUrlEncoded;
    import retrofit.http.GET;
    import retrofit.http.POST;
    
    /**
     * Created by Belal on 11/5/2015.
     */
    public interface RetrofitInternetApi {
    
        //@FormUrlEncoded, we have to write this if we want to send post data to the server.
        //@POST, because we are using an HTTP Post request we have written this.
        // Inside it we have the URL of the script that will be receiving the post request.
        // Note that the URL is excluding the root URL. And we have defined the root URL  in our MainActivity.
        //@Field(“key”) String variable inside key we have to write what we have written inside $_POST[‘key’] in our script.
        // And we have to specify it for all the values we are going to send.
    
        //Callback<Response> callback it is also inside the retrofit library. It will receive the output from the server.
    
        //But this is only an interface and the method is abstract.
        //We will define the method inside fetchDepartmentName() method that is declared inside MainActivity.java.
    
        @GET("/getDepartmentName.php")
        public void getDepartmentName(Callback<List<DepartmentNoRealm>> response);
    
    }
    

    then create the function

      private void fetchDepartmentName(){
    //Creating a rest adapter
            RestAdapter restAdapter = new RestAdapter.Builder()
                    .setEndpoint(ROOT_URL)
                    .build();
    
            //Creating an object of our api interface
            RetrofitInternetApi retrofitInternetApi = restAdapter.create(RetrofitInternetApi.class);
                //While the app fetched data we are displaying a progress dialog
                final ProgressDialog loading = ProgressDialog.show(getActivity(), "Fetching Data", "Please wait...", false, false);
    
    
    
                //Defining the method
                retrofitInternetApi.getDepartmentName(new Callback<List<DepartmentNoRealm>>() {
                    @Override
                    public void success(List<DepartmentNoRealm> list, Response response) {
                        //Dismissing the loading progressbar
                        loading.dismiss();
                        Log.d("JSON  LIST",list.toString());
                        //Storing the data in our list
                        departmentNoRealmList = list;
    
                        //Calling a method to show the list
                          showListinSpinner();            }
    
                    @Override
                    public void failure(RetrofitError error) {
                        //you can handle the errors here
                    }
                });
            }
    

    then create a class model

    package myafya.safaricom.co.ke.myafya.model.realm;
    
    /**
     * Created by 001557 on 1/13/2016.
     */
    public class DepartmentNoRealm {
        public int departmentID;
        public String departmentName;
        public String departmentURLimage;
    
        public int getDepartmentID() {
            return departmentID;
        }
    
        public void setDepartmentID(int departmentID) {
            this.departmentID = departmentID;
        }
    
        public String getDepartmentName() {
            return departmentName;
        }
    
        public void setDepartmentName(String departmentName) {
            this.departmentName = departmentName;
        }
    
        public String getDepartmentURLimage() {
            return departmentURLimage;
        }
    
        public void setDepartmentURLimage(String departmentURLimage) {
            this.departmentURLimage = departmentURLimage;
        }
    }
    

    now the code showList in Spinner

    //Our method to show list
        private void showListinSpinner(){
            //String array to store all the book names
            String[] items = new String[departmentNoRealmList.size()];
    
            //Traversing through the whole list to get all the names
            for(int i=0; i<departmentNoRealmList.size(); i++){
                //Storing names to string array
                items[i] = departmentNoRealmList.get(i).getDepartmentName();
            }
    
            //Spinner spinner = (Spinner) findViewById(R.id.spinner1);
            ArrayAdapter<String> adapter;
            adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
            //setting adapter to spinner
            spinnerDepartments.setAdapter(adapter);
            //Creating an array adapter for list view
    
        }
    

    Then SHARE IT AND MAKE IT EASY

    MY JSON WAS

    [
      {
        "departmentID": "1",
        "departmentName": "Enterprise Business Unit (EBU)",
        "departmentURLimage": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSKOZmGNAA08NbHwRJrloAouWqs6r4x7BGXY4k-ULWiHuPEobHI"
      },
      {
        "departmentID": "2",
        "departmentName": "Consumer Business Unit (CBU)",
        "departmentURLimage": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQ0IAFhZ52KiG_0ck5VbBxweZWf_MEA9eRmgHAEr6CG-rUG_a2QEQ"
      }
    ]