如何使全局对象的数据适应微调器

时间:2017-02-20 09:35:23

标签: android global-variables android-spinner

我有我的GlobalClass extends应用程序类。我想将全局对象数据绑定到微调器。这是我的GlobalClass

public class GlobalClass extends Application {

private List<ProjectType> projectTypes;

public List<ProjectType> getProjectTypes() {
    return projectTypes;
}

public void setProjectTypes(List<ProjectType> projectTypes) {
    this.projectTypes = projectTypes;
} 
}
  

Pojo课程

public class ProjectType implements Serializable {
private Integer projectTypeId;
private String typeName;
private Integer peckOrder;

//getter and setter here

我使用GSON使用volley和parse从服务器获取响应,并将响应设置为GlobalClass 这里是代码

JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, getString(R.string.TEST_projectTypeURL), null, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
            Gson gson = new Gson();
            List<ProjectType> projectTypes = gson.fromJson(String.valueOf(response),List.class);
            globalVariable.setProjectTypes(projectTypes);
        }
    }

最后在另一个活动类中使用spinner来绑定GlobalClass对象的数据

globalVariable = (GlobalClass) getApplicationContext();
    List<String> projectTypeList = new ArrayList<>();

    ArrayList<ProjectType> projectTypesCollection = new ArrayList<ProjectType>(globalVariable.getProjectTypes());

    for (ProjectType projectType: projectTypesCollection) {

        projectTypeList.add(projectType.getTypeName());
    }

    prjtTypeSpinner = (Spinner)findViewById(R.id.spn_prjt_type);
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item,projectTypeList);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    prjtTypeSpinner.setAdapter(dataAdapter);

在尝试上述代码时,我收到错误“com.google.gson.internal.LinkedTreeMap无法转换为pojo.ProjectType类”

这里是对象返回值,

[{projectTypeId=3.0, typeName=ALS, peckOrder=220.0}, {projectTypeId=2.0, typeName=ALB, peckOrder=210.0}, {projectTypeId=1.0, typeName=CL, peckOrder=200.0}, {projectTypeId=7.0, typeName=ACG, peckOrder=40.0}, {projectTypeId=6.0, typeName=ACS, peckOrder=30.0}, {projectTypeId=5.0, typeName=ACB, peckOrder=20.0}, {projectTypeId=4.0, typeName=CC, peckOrder=10.0}]

我想在微调器中使用typeName。提前致谢。

2 个答案:

答案 0 :(得分:1)

我终于解决了这个问题,

p.x

当我尝试代码时,我的错误得到解决,此代码运行良好

答案 1 :(得分:0)

我认为您对此代码有疑问

List<ProjectType> projectTypes = gson.fromJson(String.valueOf(response),List.class);

您需要更改为:

List<ProjectType> projectTypes = gson.fromJson(new Gson().toJson(response),new TypeToken<List<ProjectType>>() {
            }.getType());