How to add the json response into spinner in android using retrofit?

故事扮演 提交于 2019-12-12 07:02:09

问题


In our project we don't hard code the Label and dropdown, we assign the value to Label from JSON. I don't understand how to assign the gender array to dropdown.
Here is the response getting from URL

{
    "statusCode": "200",
    "statusMessage": "SUCCESS",
    "meetmeConfig": {
        "id": "bb52dc0f-29d0-4079-99c7-a07c8045a829",
        "moduleName": "MeetMe",
        "createdDate": 1523962430721,
        "configContent": {
            "trackingOptions": [
                {
                    "optionName": "Before the meet",
                    "isTimeRequired": true,
                    "trackingTime": [
                        5,
                        10,
                        15
                    ],
                    "isDeleted": false
                },
                {
                    "optionName": "After the meet",
                    "isTimeRequired": true,
                    "trackingTime": [
                        5,
                        10,
                        15
                    ],
                    "isDeleted": false
                },
                {
                    "optionName": "At the start",
                    "isTimeRequired": false,
                    "trackingTime": [],
                    "isDeleted": false
                },
                {
                    "optionName": "Never",
                    "isTimeRequired": false,
                    "trackingTime": [],
                    "isDeleted": false
                }
            ],
            "numberOfParticipants": 8,
            "mapResetTimeInterval": 30,
            "meetingTrackableTime": 3600,
            "addressTypes": [
                "Home",
                "Work"
            ],
            "transportModes": [
                "Walking",
                "Driving"
            ],
            "gender": [
                "Male",
                "Female",
                "Trans-Female",
                "Bi-Gender",
                "Non-Binary",
                "Gender nonconfirming",
                "Undisclosed",
                "Rather not say"
            ],
            "toastDelayTimeForPulse": 3,
            "syncToastMaxTimeInterval": 300,
            "syncToastThirdTimeInterval": 180,
            "firstTimeInterval": 1,
            "secondTimeInterval": 2,
            "meetmeSearchContactTimeInterval": 2,
            "signupToastDelayTime": 4,
            "signupToastdelatimebysix": 6,
            "signupToastDelayMedium": 5,
            "profileToastDelayTime": 4,
            "profileToastDelatimebysix": 6,
            "languages": [
                "English",
                "Spanish",
                "Marathi",
                "Hindi",
                "Bengali",
                "French",
                "Arabic",
                "German",
                "Italian",
                "Dutch",
                "Japanese",
                "Russia",
                "Korean"
            ]
        }
    }
}

I want to use gender array getting from response and added to a Spinner which is in a fragment.
Here is the code in onResponse method.

heroList =  response.body();   
data = new ArrayList<>(Arrays.asList(heroList));                                                

Log.d("Data","Datarecevied:"+heroList.getMeetmeConfig().getConfigContent().getGender());

How can we do that?


回答1:


List anyList = heroList.getMeetmeConfig().getConfigContent().getGender()

Spinner spinner = (Spinner) findViewById(R.id.msSpinnerID);

ArrayAdapter<String> adp = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, anyList);

adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spinner.setAdapter(adp);

If you want show on Dialog

AlertDialog.Builder builderSingle = new AlertDialog.Builder(DialogActivity.this);
builderSingle.setIcon(R.drawable.ic_launcher);
builderSingle.setTitle("Select One Name:-");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(DialogActivity.this, android.R.layout.select_dialog_singlechoice);
  List anyList = heroList.getMeetmeConfig().getConfigContent().getGender()
for(gender : anyList)
{
arrayAdapter.add(gender)
}
builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String strName = arrayAdapter.getItem(which);
                Log.e("My Selected Gender", strName)
       }
        });
builderSingle.show();



回答2:


Once you have your JSON Response, there is an Android Library called Ason found here https://android-arsenal.com/details/1/5313

You can use the libary to fetch the array that you would want to use on your spinner way easier. Its a wrapper of org.json in android.

So your array will be constructed as follows:

Ason ason = new Ason(urlResponse);
AsonArray genderArray = ason.getJsonArray('meetmeConfig.configContent.gender')

//then u convert the genderArray into an array or ArrayList thats spinners use
ArrayList<String> spinnerItems = new ArrayList();
for (Ason gender : genderArray){
    spinnerItems.add(gender.toString());
}

use the spinnerItems for the spinner adapter




回答3:


Just Try this code and your problem will be solved.Thank you

ArrayAdapter<String> genderAdapter;
Spinner spin_gender = findViewById(R.id.spin_gender);

heroList =  response.body();   
data = new ArrayList<>(Arrays.asList(heroList));                                                

String[] genderArray = heroList.getMeetmeConfig().getConfigContent().getGender()

genderAdapter = new ArrayAdapter<String>(this, R.layout.label, genderArray);
spin_gender.setAdapter(genderAdapter);



回答4:


 AppCompatSpinner spinner;
 spinner = (AppCompatSpinner) findViewById(R.id.spinner);
 ArrayList<String> categoryDropDownItems = new ArrayList<String>();

In Your Response

categoryDropDownItems.add("<Set Title if you want>");

 //Array Response from Server
 if (response != null) {
     if (response.length() > 0) {
         for (int i = 0; i < response.length(); i++) {
             try {
                 JSONObject jsonObject = response.getJSONObject(i);
                 String dropDownDisplayCategoryName = jsonObject.getString("<YOUR STRIN FROM JSON>");                  
                 categoryDropDownItems.add(dropDownDisplayCategoryName);
             } catch (JSONException je) {
                 return null;
             }
         }
      } else {
          return null;
      }
 }

//For Set Array Data in Spinner

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.spinner_item, categoryDropDownItems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setSelection(selection);

If you want to pass data from Activity to Fragment you can Use

Fragment fragment = new YourFragmentName();
Bundle bundle = new Bundle();
bundle.putString("RESPONSE",<Your Response as a String>);
fragment.setArguments(bundle);

And Get Data in Fragment like below

String responseData = getArguments().getString("RESPONSE");

Now you can convert your object in JSON and from JSON get Spinner data and use above code for Add data in ArrayList and set to Spinner.



来源:https://stackoverflow.com/questions/52566068/how-to-add-the-json-response-into-spinner-in-android-using-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!