如何使用翻新将JSON响应添加到Android中的Spinner?

时间:2018-09-29 07:13:09

标签: android retrofit2

在我们的项目中,我们不对Label和dropdown进行硬编码,而是将值从JSON分配给Label。我不知道如何将性别array分配给dropdown
这是从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"
            ]
        }
    }
}

我想使用性别数组从响应中获取并添加到片段中的Spinner中。
这是onResponse方法中的代码。

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

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

我们该怎么做?

4 个答案:

答案 0 :(得分:0)

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

如果要在对话框上显示

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();

答案 1 :(得分:0)

一旦您有了JSON响应,就会在https://android-arsenal.com/details/1/5313

中找到一个名为Ason的Android库

您可以使用库来更轻松地获取要在微调器上使用的数组。它是Android中# your code..... ptm.tf <- DocumentTermMatrix(apapers) # using col_sums since it is a document term matrix. If it is a term document matrix use row_sums frequency <- slam::col_sums(ptm.tf) # Filtering like findFreqTerms. Find words that occur 10 times or more. frequency <- frequency[frequency >= 10] # turn into data.frame if needed: frequency_df <- data.frame(words = names(frequency ), freq = frequency , row.names = NULL) 的包装。

因此您的数组将按以下方式构造:

org.json

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()); } 用于微调适配器

答案 2 :(得分:0)

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

您的回复

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;
      }
 }

//对于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);

如果要将数据从“活动”传递到“片段”,则可以使用

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

然后像下面那样在Fragment中获取数据

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

现在,您可以在JSON中转换对象,并从JSON获得Spinner数据,并使用上述代码在ArrayList中添加数据并将其设置为Spinner

答案 3 :(得分:0)

只需尝试以下代码,问题便会解决。谢谢

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