【问题标题】:Convert ArrayList of String from Retrofit response从改造响应中转换字符串的 ArrayList
【发布时间】:2017-03-20 15:42:42
【问题描述】:

我想将此 json 响应 ["tunisie","canada"] 转换为 List 以便能够在 Spinner 中使用它。 这是我的改造电话:

   List<String> list = new ArrayList<String>();
   public void populatePays(){
   pays = (Spinner) findViewById(R.id.pays_spinner);
   pays.setOnItemSelectedListener(this);
   apiService = RestService.createService(SolarAPIService.class);
   Call<ArrayList<String>> call = apiService.listPays();
   call.enqueue(new Callback<ArrayList<String>>() {
       @Override
       public void onResponse(Call<ArrayList<String>> call, Response<ArrayList<String>> response) {
          list.addAll(response.body());

       }

       @Override
       public void onFailure(Call<ArrayList<String>> call, Throwable t) {

       }
   });
   ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
           (this, R.layout.spinner_item, list);
   dataAdapter.setDropDownViewResource
           (R.layout.spinner_drop_down_item);
   pays.setAdapter(dataAdapter);

  }

执行后我得到一个空的 Spinner。所以显然我的回复没有被转换成我的ArrayList&lt;String&gt;

【问题讨论】:

    标签: android json arraylist retrofit2


    【解决方案1】:

    在主线程上设置适配器的值,但是api调用响应正在通过另一个线程,你应该调用

    dataAdapter.notifyDataSetChanged();

    就在

    之后

    list.addAll(response.body());

    【讨论】:

      【解决方案2】:

      输入以下代码:

       ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
                 (this, R.layout.spinner_item, list);
         dataAdapter.setDropDownViewResource
                 (R.layout.spinner_drop_down_item);
         pays.setAdapter(dataAdapter);
      

      里面:

             @Override
             public void onResponse(Call<ArrayList<String>> call, Response<ArrayList<String>> response) {
                list.addAll(response.body());
                // HERE
             }
      

      【讨论】:

      • 尝试记录响应
      • 我把它改成了getApplication()
      猜你喜欢
      • 2019-09-04
      • 1970-01-01
      • 2015-10-22
      • 2016-10-02
      • 1970-01-01
      • 2017-06-04
      • 1970-01-01
      • 2011-09-13
      • 2020-11-02
      相关资源
      最近更新 更多