无法引用android中的非最终局部变量错误

时间:2015-11-21 08:28:11

标签: android

我有一个包含Product(productid,productname)的列表视图。为此,我在下面填写ArrayList。

ArrayList<Product> products = new ArrayList<Product>();
String strJson = Utility.loadJSONFromAsset("products.json");

JSONObject  jsonRootObject = new JSONObject(strJson);
JSONArray jsonArray = jsonRootObject.optJSONArray("products");
for(int i=0; i < jsonArray.length(); ++i){
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    Product p = new Product (Integer.parseInt(jsonObject.optString("id")), jsonObject.optString("name").toString());
    products.add(p);
}

ProductAdapter adapter = new ProductAdapter(getApplicationContext(), products);
productListView.setAdapter(adapter);
productListView.setVisibility(View.VISIBLE);

现在setOnItemClickListener我想打开一个带有产品名称的新活动。

productListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
       Toast.makeText(getApplicationContext(), "haha" + position, Toast.LENGTH_SHORT).show();
       Context context = getApplicationContext();
       Intent intent = new Intent(context, com.example.testbot.ProductDetailActivity.class );
       intent.putExtra("productname", products.get(position).getName());
       intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       context.startActivity(intent);
   }
});

但它给出了错误。不能引用封闭范围中定义的非最终局部变量产品。

如何解决这个问题?

0 个答案:

没有答案
相关问题