【问题标题】:A variable in for loop is not identifiable rather than it is declared and initialize in loopfor循环中的变量是不可识别的,而不是在循环中声明和初始化的
【发布时间】:2019-06-28 09:24:07
【问题描述】:

当我声明一个变量并初始化时,我从房间数据库和 for 循环中获取列表,但它在 for 循环中无法识别。

code image is here

我在 for 循环之外声明了变量,这个错误消失了。但微调器只显示列表的最后一项。

【问题讨论】:

    标签: android android-spinner android-room observers


    【解决方案1】:

    您是 stackoverflow 初学者,所以您可能不知道这一点,但是,下次请将您的代码粘贴到问题中。不要截图代码。

    要回答您的问题,请多加一个分号。 改为

    for (int position = 0; position < products.size() - 1; position++)
    {
        // Etc
    }
    

    【讨论】:

      【解决方案2】:

      删除for循环行末尾的“;

      在顶部定义ArrayAdatper

      ArrayAdatper<String> aa; 
      

      onChanged方法循环后添加以下行:

      if(aa != null) {
         aa.notifyDataSetChanged();
      }
      

      【讨论】:

        【解决方案3】:

        感谢您的回答,但我通过使用迭代器解决了这个问题。

            list = new ArrayList<Product>();
            product = new ArrayList<String>();
        
            //Views
            Spinner mSpinner = (Spinner) findViewById(R.id.add_sale_spinner);
        
        
            viewModel = ViewModelProviders.of(this).get(ProductViewModel.class);
            viewModel.getAllProduct().observe(this, new Observer<List<Product>>() {
                @Override
                public void onChanged(@Nullable List<Product> products) {
                    //Creating the ArrayAdapter instance having the bank name list
                    Log.d(TAG, "onChanged: "+products.size()+ "Fdsfsdfds");
                    Iterator<Product> iterator = products.iterator();
                    while(iterator.hasNext()){
                        Product obj = iterator.next();
                        list.add(obj);
                        product.add(obj.getProductName().toString());
                    }
                }
            });
            ArrayAdapter<String> aa = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, product);
            aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            mSpinner.setAdapter(aa);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-21
          • 2017-07-20
          • 1970-01-01
          • 2016-06-07
          • 2012-01-28
          • 2012-01-02
          相关资源
          最近更新 更多