如何在Spinner中加载相应的JSON?

时间:2016-10-08 14:29:52

标签: android json spinner

我有2个Spinners和2个.json个文件。第一个Spinner包含类别,第二个包含子类别。我需要在选择特定类别时加载相应的数据。

类别JSON文件:

{
    "Categories": {
        "Category": [{
            "cat_id": 1,
            "cat_title": "..."
        }, {
            "cat_id": 2,
            "cat_title": "..."
        }, {
            "cat_id": 3,
            "cat_title": "..."
        }]
    }
}

子类别JSON文件:

{
    "Subcategories": {
        "Subcategory": [{
            "cat_id": 1,
            "subcat_id": 1,
            "subcat_title": ".."
        }]
    }
}

它们与cat id相关联。装载由相同的方法控制。

以下是该类别的方法:

private void prepareCats() {

    inputStream = getResources().openRawResource(R.raw.categories);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    try {
        ctr = inputStream.read();
        while (ctr != -1) {
            byteArrayOutputStream.write(ctr);
            ctr = inputStream.read();
        }
        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        // Parse the data into jsonobject to get original data in form of json.
        JSONObject jObject = new JSONObject(
                byteArrayOutputStream.toString());

        JSONObject jObjectResult = jObject.getJSONObject("Categories");
        JSONArray jArray = jObjectResult.getJSONArray("Category");
        String cat_title = "";

        for(int i=0;i<jArray.length();i++){


            cat.setCatname(jArray.getJSONObject(i).getString("cat_title"));
            cat.setCatId(jArray.getJSONObject(i).getString("cat_id"));

            Log.v("cat",cat.getCatname());

            categories.setOnItemSelectedListener(new OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                    System.out.println("cat position" + position);
                    catPosition = position;
                }

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

            });
            categoriesList.add(cat.getCatname());

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

            categories.setAdapter(
                    new NothingSelectedSpinnerAdapter(
                            dataAdapter,
                            R.layout.contact_spinner_cat_row_nothing_selected,
                            this));
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

加载子类别:

 private void prepareSubCats() {
    inputStream = getResources().openRawResource(R.raw.subcategories);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    try {
        ctr = inputStream.read();
        while (ctr != -1) {
            byteArrayOutputStream.write(ctr);
            ctr = inputStream.read();
        }
        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }



    try {
        // Parse the data into jsonobject to get original data in form of json.
        JSONObject jObject = new JSONObject(
                byteArrayOutputStream.toString());

        JSONObject jObjectResult = jObject.getJSONObject("Subcategories");
        JSONArray jArray = jObjectResult.getJSONArray("Subcategory");
        String subcat_title = "";

        for(int i=0;i<jArray.length();i++){
            subcat.setSubCatname(jArray.getJSONObject(i).getString("subcat_title"));
            subcat.setCatId(jArray.getJSONObject(i).getString("cat_id"));

            subcategoriesList.add(subcat.getSubCatname());

            subCategories.setOnItemSelectedListener(new OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                    subcatPosition = position;

                }

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

            });

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

            subCategories.setAdapter(
                    new NothingSelectedSpinnerAdapter(
                            dataAdapter,
                            R.layout.contact_spinner_subcat_row_nothing_selected,
                            this));
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

我需要的是比较类别的cat id和子类别的cat id,以便将子类别填充到相应的类别。

2 个答案:

答案 0 :(得分:1)

您已经在子类别微调器中使用了setOnItemSelectedListener,您只需要在类别微调器中实现相同的内容。

当触发类别微调器的OnItemSelectedListener时,您应该更新子类别适配器。

此处有更多信息:Android Spinner: Get the selected item change event

- 编辑 -

您的问题的解决方案如下:

1 - 在类别微调器的OnItemSelected中,当您获得类别位置时,需要调用prepareSubcategories微调器来更新子类别。

2 - 在prepareSubcategories中,您需要获取类别位置变量中类别的类别ID。

3 - 您需要过滤子类别列表以删除不具有cat_id的子类别。

答案 1 :(得分:0)

以下是我的建议,同时我使用GsonButterknife库对您的代码进行了一些改进,您可以更多地了解这些库。

此处是示例 MainActivity

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.category)
    Spinner categorySpinner;
    @BindView(R.id.subcategory)
    Spinner subcategorySpinner;
    private CategoriesModel categories;
    private SubcategoriesModel subcategories;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ButterKnife.bind(this);

        loadCategoriesData();

        prepareCategories();

    }

    private void loadCategoriesData() {
        // load categories using Gson
        InputStream categoriesInputStream = getResources().openRawResource(R.raw.categories);
        Reader categoriesReader = new BufferedReader(new InputStreamReader(categoriesInputStream));
        categories = new Gson().fromJson(categoriesReader, CategoriesModel.class);

        // load subcategories using Gson
        InputStream inputStream = getResources().openRawResource(R.raw.subcategories);
        Reader reader = new BufferedReader(new InputStreamReader(inputStream));
        subcategories = new Gson().fromJson(reader, SubcategoriesModel.class);
    }

    private void prepareCategories() {
        ArrayAdapter<Category> categoriesArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, categories.getCategories().getCategories());
        categorySpinner.setAdapter(categoriesArrayAdapter);

        categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // prepare subcategories using selected category
                prepareSubcategories((Category) parent.getItemAtPosition(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                subcategorySpinner.setEnabled(false);
            }
        });
    }

    private void prepareSubcategories(Category category) {
        // filter subcategories using selected category
        ArrayList filteredSubcategories = new ArrayList();
        for (Subcategory subcategory : subcategories.getSubcategories().getSubcategories()) {
            if (subcategory.getCategoryId() == category.getCatId())
                filteredSubcategories.add(subcategory);
        }

        ArrayAdapter<Subcategory> subcategoriesArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, filteredSubcategories);
        subcategorySpinner.setAdapter(subcategoriesArrayAdapter);

        subcategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // do what ever you want with the selected item :)
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
}

以下是处理值的POJO模型。

<强> CategoriesModel.java:

public class CategoriesModel {

    @SerializedName("Categories")
    @Expose
    private Categories categories;

    public Categories getCategories() {
        return categories;
    }

    public void setCategories(Categories categories) {
        this.categories = categories;
    }

    public class Categories {

        @SerializedName("Category")
        @Expose
        private List<Category> categories = new ArrayList<>();

        public List<Category> getCategories() {
            return categories;
        }

        public void setCategories(List<Category> categories) {
            this.categories = categories;
        }

    }
}

<强> Category.java:

public class Category {

    @SerializedName("cat_id")
    @Expose
    private Integer catId;
    @SerializedName("cat_title")
    @Expose
    private String catTitle;

    public Integer getCatId() {
        return catId;
    }

    public void setCatId(Integer catId) {
        this.catId = catId;
    }

    public String getCatTitle() {
        return catTitle;
    }

    public void setCatTitle(String catTitle) {
        this.catTitle = catTitle;
    }

    @Override
    public String toString() {
        return catTitle;
    }
}

<强> SubcategoriesModel.java:

public class SubcategoriesModel {

    @SerializedName("Subcategories")
    @Expose
    private Subcategories subcategories;

    public Subcategories getSubcategories() {
        return subcategories;
    }

    public void setSubcategories(Subcategories subcategories) {
        this.subcategories = subcategories;
    }

    public class Subcategories {

        @SerializedName("Subcategory")
        @Expose
        private List<Subcategory> subcategories = new ArrayList<Subcategory>();

        public List<Subcategory> getSubcategories() {
            return subcategories;
        }

        public void setSubcategories(List<Subcategory> subcategories) {
            this.subcategories = subcategories;
        }
    }
}

<强> Subcategory.java:

public class Subcategory {

    @SerializedName("cat_id")
    @Expose
    private Integer categoryId;
    @SerializedName("subcat_id")
    @Expose
    private Integer subcategoryId;
    @SerializedName("subcat_title")
    @Expose
    private String subcategoryTitle;

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }

    public Integer getSubcategoryId() {
        return subcategoryId;
    }

    public void setSubcategoryId(Integer subcategoryId) {
        this.subcategoryId = subcategoryId;
    }

    public String getSubcategoryTitle() {
        return subcategoryTitle;
    }

    public void setSubcategoryTitle(String subcategoryTitle) {
        this.subcategoryTitle = subcategoryTitle;
    }

    @Override
    public String toString() {
        return subcategoryTitle;
    }
}

希望它有所帮助;)