2016-10-08 8 views
0

私は2つのスピナーと2つのそれぞれ.jsonファイルを持っています。最初のSpinnerはカテゴリを保持し、2番目のサブカテゴリはカテゴリを保持します。特定のカテゴリを選択すると、それぞれのデータを読み込む必要があります。JSONをスピナーにロードするにはどうすればいいですか?

カテゴリー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": ".." 
     }] 
    } 
} 

彼らは猫の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(); 
    } 

} 

はなるように、カテゴリの猫のIDとサブカテゴリの猫のIDを比較することですサブカテゴリは、該当するカテゴリに入力します。

+0

あなたがしている問題は何ですか顔? –

+0

サブカテゴリーのリストを、選択したカテゴリに従って更新したい(cat1の場合、cat1プロパティを持つサブキャットのみ) – user6456773

+0

すでに 'prepareSubCats'メソッドにロジック(コメント部分)があります。それは何が間違っていますか? –

答えて

1

すでにサブカテゴリースピナーでsetOnItemSelectedListenerを使用していますが、カテゴリースピナーで同じものを実装するだけで済みます。

カテゴリスピナーのOnItemSelectedListenerがトリガーされると、サブカテゴリアダプタを更新する必要があります。ここ

さらに詳しい情報:Android Spinner: Get the selected item change event

- 編集 -

あなたの問題の解決策は以下の通りです:

1-でカテゴリスピナーのOnItemSelected、カテゴリを取得サブカテゴリーを更新するには、prepareSubcategoriesスピナーを呼び出す必要があります。

2のprepareSubcategoriesでは、カテゴリのカテゴリ変数にあるカテゴリのカテゴリIDを取得する必要があります。

3 - cat_idを持たないサブカテゴリを削除するには、サブカテゴリリストをフィルタリングする必要があります。

+0

位置を定義し、OnItemSelectedListenerのロジックを移動しましたが、データを正しくロードできませんでした。サンプルコードを見せてもらえますか?ありがとうございました! – user6456773

+0

@ user6456773あなたはonItemSelectedメソッドを投稿できますか?また、アダプターの内容を変更した後でnotifyDatasetChangedを呼び出すのですか? – jonathanrz

+0

今のところコードをアップロードしました。クリックされた項目上の位置が正しく返されます。私はいくつかのシンプルなロジックを見逃していますが、まだそれを処理することはできません。 – user6456773

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

    } 
} 

カテゴリー。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; 
    } 
} 

はそれが役に立てば幸い;)

関連する問題