1

I have a list view that contains Product (productid, productname). For that I am filling ArrayList below.

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

Now setOnItemClickListener I want to open a new activity, with product name.

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

But it is giving error. Cannot refer to the non-final local variable products defined in an enclosing scope.

How to fix this?

Devesh Agrawal
  • 8,982
  • 16
  • 82
  • 131
  • 3
    Declare `products` as class level variable instead of inside any method or make it `final` – ρяσѕρєя K Nov 21 '15 at 08:29
  • Possible duplicate of [Why a non-final "local" variable cannot be used inside an inner class, and instead a non-final field of the enclosing class can?](http://stackoverflow.com/questions/5801829/why-a-non-final-local-variable-cannot-be-used-inside-an-inner-class-and-inste) – Nir Alfasi Nov 21 '15 at 08:35
  • @ρяσѕρєяK, Thanks It works. You you can answer this. i will accept. – Devesh Agrawal Nov 21 '15 at 09:27

0 Answers0