将列表转换为数组并在android中的微调器中显示

时间:2018-09-29 16:06:14

标签: android android-spinner

我使用retrofit2并获得类别列表。

型号类别:

public class Category implements Serializable {   
    @SerializedName("catid")
    private int catid;
    @SerializedName("title")
    private String title;
    @SerializedName("qcount")
    private String qcount;
    public int getCatid() {
        return catid;
    }
    public void setCatid(int catid) {
        this.catid = catid;
    }    
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
}

改造调用和回调:

Call<List<Category>> call =  apiInterface.getCategories();
call.enqueue(new Callback<List<Category>>() {
    @Override
    public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
        hidePDialog();
        if(response.isSuccessful()){
            List<Category> cats =  response.body();
            //codes to convert cats to array.
            // i need cats title to insert in array.
        }
    }
    @Override
    public void onFailure(Call<List<Category>> call, Throwable t) {
    }
});

旋转器:

s1= findViewById(R.id.spinner);
ArrayAdapter<String> adap=new ArrayAdapter<String>
        (this, android.R.layout.simple_spinner_item, cat_title);
s1.setAdapter(adap);

如何在微调器中显示猫的头衔?
例子:
猫:

[{    
    "catid": 1,
    "title": "windows" 
    },
    {
    "catid": 2,
    "title": "Android",
    }
]

以上所有代码均在一项活动中。
请帮帮我。
先谢谢了。 我编辑活动,但不起作用! 有什么问题:

public class NewPostActivity extends AppCompatActivity {
    private  ArrayList<String> cat_title;
    Spinner s1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_post);
        CatsRequest();
        String[] cat_title1 = (String[]) cat_title.toArray(new String[cat_title.size()]);
        s1= findViewById(R.id.spinner);
        ArrayAdapter<String> adap=new ArrayAdapter<String>
                (this, android.R.layout.simple_spinner_item, cat_title1);
        s1.setAdapter(adap);
        s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    private void CatsRequest(){

        APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
        Call<List<Category>> call =  apiInterface.getCategories();
        call.enqueue(new Callback<List<Category>>() {
            @Override
            public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
                hidePDialog();
                if(response.isSuccessful()){
                    List<Category> cats =  response.body();
                    ArrayList<String> cat_title= new ArrayList<String>();
                    for(Category cat: cats){
                        cat_title.add(cat.getTitle());
                    }
                }
            }
            @Override
            public void onFailure(Call<List<Category>> call, Throwable t) {
            }
        });
    }
}

无法运行。 错误:原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'int java.util.ArrayList.size()'

3 个答案:

答案 0 :(得分:1)

除非我误解了某些内容,否则您要做的就是:

    for(Category c: cats)
    {
        yourarray.Add(c.getTitle());
    }

答案 1 :(得分:0)

List<Category> cats =  response.body();
ArrayList<String> titles= new ArrayList<String>();
ArrayList<Integer> ids= new ArrayList<Integer>();//in case you need the ids too
for(Category cat: cats){
    titles.add(cat.getTitle());
    ids.add(cat.getId());
}

将适配器附加到微调器:

 ArrayAdapter<String> adp = new ArrayAdapter<String>(this,
                          android.R.layout.simple_list_item_1, list);
 adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 sp.setAdapter(adp1);//sp is the spinner obj

如果您需要根据标题计算id的值

   sp.setOnItemSelectedListener(new OnItemSelectedListener() {
      @Override
      public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
          int id = ids.get(position);//This will be the student id.
      }

      @Override
      public void onNothingSelected(AdapterView<?> parentView) {
        // your code here
      }

    });

快乐的编码。

答案 2 :(得分:0)

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<nav class="navbar navbar-dark sticky-top bg-dark flex-wrap2 flex-md-nowrap p-0">
      <div class="container-fluid">
        <a class="navbar-brand col-auto mr-0" href="#">Brand</a>

        <button class="navbar-toggler d-md-none mt-1 mr-2" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="input-group py-1 px-2 px-md-0">
            <input class="form-control form-control-dark" type="text" placeholder="Search here..." aria-label="Search">
            <div class="input-group-append">
                <button class="btn btn-outline-success" type="submit"><i class="fa fa-search"></i></button>
            </div>
        </div>

        <ul class="navbar-nav navbar-expand-md pl-2 pr-3">
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav mr-auto text-nowrap">
                    <li class="nav-item my-1 active">
                        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item dropdown my-1">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <i class="fa fa-folder-open" aria-hidden="true"></i>
                            Categories
                        </a>
                        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                            <a class="dropdown-item" href="#">Sports</a>
                            <a class="dropdown-item" href="#">Hot</a>
                            <div class="dropdown-divider"></div>
                            <a class="dropdown-item" href="#">Mad Science</a>
                        </div>
                    </li>
                    <li class="nav-item my-1">
                        <a href="#" class="nav-link btn btn-outline-secondary"><i class="fa fa-user"></i> My account</a>
                    </li>
                </ul>
            </div>
        </ul>
</div>
</nav>

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>