0

Hi I am new to spinner use, never used it before and also populating it with the json data. I am trying to find some solution or atleast learn few things on how to do that, but not able to get any understandable solution. Would appreciate if someone can guide me on a proper path.

My JSON data looks something like below,

{ 
 "Devices": [
 {
  "type": "alarm",
  "displayType": "Alarm",
  "imageId": "alarm"
 },
 {
  "type": "audio_bridge",
  "displayType": "Audio Bridge",
  "imageId": "audio"
 },
 {
  "type": "av_receiver",
  "displayType": "Av Receiver",
  "imageId": "default"
 },
 {
  "type": "baby_monitor",
  "displayType": "Baby Monitor",
  "imageId": "mobile"
 },
 {
  "type": "baseport",
  "displayType": "Baseport",
  "imageId": "default"
 },
 {
  "type": "camera",
  "displayType": "Camera",
  "imageId": "camera"
 },
 {
  "type": "console",
  "displayType": "Console",
  "imageId": "console"
 }
 ]
}

I need to just pull displayType from this JSON. And I have a model class to follow through and fetch whatever data needed as below,

@SerializedName("type")
@Expose
private String type;
@SerializedName("displayType")
@Expose
private String displayType;
@SerializedName("imageId")
@Expose
private String imageId;

protected Devices(Parcel in) {
    type = in.readString();
    displayType = in.readString();
    imageId = in.readString();
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeValue(type);
    parcel.writeValue(displayType);
    parcel.writeValue(imageId);

}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public String getDisplayType() {
    return displayType;
}

public void setDisplayType(String displayType) {
    this.displayType = displayType;
}

public String getImageId() {
    return imageId;
}

public void setImageId(String imageId) {
    this.imageId = imageId;
}

the thing is I wanted to list all the displayType dynamically based on json into spinner in my activity.

Darpal
  • 352
  • 5
  • 20
  • What do you want to show in your `spinner`? – OhhhThatVarun Apr 08 '20 at 19:36
  • 2
    The elements a spinner displays are passed into it through an ArrayAdapter (`Spinner.setAdapter()`). The adapter takes in an array/List of items when it's constructed, just pass in a list containing all the displayTypes after they're loaded. – Husayn Hakeem Apr 08 '20 at 19:36
  • @OhhhThatVarun **displayType** field from JSON – Darpal Apr 08 '20 at 19:38
  • @HusaynHakeem so I dont need to create a CustomAdapter? i heard to get the click event i need a separate adapter? – Darpal Apr 08 '20 at 19:39
  • Read this https://stackoverflow.com/a/2784312/7436566 – OhhhThatVarun Apr 08 '20 at 19:39
  • 1
    @DarpalDhyani The click event is handled by the spinner's `OnItemSelectedListener`. The [official documentation](https://developer.android.com/guide/topics/ui/controls/spinner) on using a spinner should help you. – Husayn Hakeem Apr 08 '20 at 19:42
  • @HusaynHakeem thank you for the documentation much needed. Appreciate your help – Darpal Apr 08 '20 at 20:17

2 Answers2

1

Use Custom adapter to pass the list of data you want to show in spinner something like this, depending on the UI you want to show.

public class CustomAdapter extends ArrayAdapter<String>{     

private Activity activity;
private ArrayList data;
public Resources res;
SpinnerModel tempValues=null;
LayoutInflater inflater;

/*************  CustomAdapter Constructor *****************/
public CustomAdapter(
                      CustomSpinner activitySpinner, 
                      int textViewResourceId,   
                      ArrayList objects,
                      Resources resLocal
                     ) 
 {
    super(activitySpinner, textViewResourceId, objects);

    /********** Take passed values **********/
    activity = activitySpinner;
    data     = objects;
    res      = resLocal;

    /***********  Layout inflator to call external xml layout () **********************/
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

  }

@Override
public View getDropDownView(int position, View convertView,ViewGroup parent) {
    return getCustomView(position, convertView, parent);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    return getCustomView(position, convertView, parent);
}

// This funtion called for each row ( Called data.size() times )
public View getCustomView(int position, View convertView, ViewGroup parent) {

    /********** Inflate spinner_rows.xml file for each row ( Defined below ) ************/
    View row = inflater.inflate(R.layout.spinner_rows, parent, false);

    /***** Get each Model object from Arraylist ********/
    tempValues = null;
    tempValues = (SpinnerModel) data.get(position);

    TextView label        = (TextView)row.findViewById(R.id.company);
    TextView sub          = (TextView)row.findViewById(R.id.sub);
    ImageView companyLogo = (ImageView)row.findViewById(R.id.image);

    if(position==0){

        // Default selected Spinner item 
        label.setText("Please select company");
        sub.setText("");
    }
    else
    {
        // Set values for spinner each row 
        label.setText(tempValues.getCompanyName());
        sub.setText(tempValues.getUrl());
        companyLogo.setImageResource(res.getIdentifier
                                     ("com.androidexample.customspinner:drawable/"
                                      + tempValues.getImage(),null,null));

    }   

    return row;
  }

}

Ravi
  • 2,277
  • 3
  • 22
  • 37
  • 1
    this is definitely the best solution. but, textViewResourceId unnecessary at contructor, if you even pass 0 doesn't matter, my constructor like this, super(activity, 0, warehouseItems); – Mucahid Uslu Jan 13 '21 at 07:37
0

You have to create a String Arraylist and put it in your spinner adapter.

ArrayList<String> deviceTypeList = new ArrayList<String>();

for (device : Devices ){
     deviceTypeList.add (device.getDisplayType())
}

ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, deviceTypeList);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

yourSpinnerName.setAdapter (adapter)
  • Also you can check here https://stackoverflow.com/questions/2784081/android-create-spinner-programmatically-from-array/2784312#2784312 Your arrayList should be in my post – Okan Serdaroğlu Apr 08 '20 at 19:42
  • So, just to understand .... from where you getting **Devices** in for loop? – Darpal Apr 08 '20 at 19:46
  • when you get your data you can prepare your deviceList with a for loop, after that create your adapter, after that set your adapter into your spinner. – Okan Serdaroğlu Apr 08 '20 at 19:57
  • do you think i have to create a custom adapter for this spinner? to get onclick of item its value? – Darpal Apr 08 '20 at 20:29