不能引用非最终变量productIdList

时间:2013-08-01 09:24:40

标签: android multithreading arraylist

On * productIdList.add(p.getId()); *这一行说明不能在另一个方法中定义的内部类中引用非最终变量productIdlist。

这是代码:

public ArrayList<String> getProductData() {


    ArrayList<String> productIdList = new ArrayList<String>();

    new Thread(new Runnable() {

        public void run() {
            HttpClient httpclient= new DefaultHttpClient();
            GeneralConstans GC = new GeneralConstans();
            // Products will be stated in memory
            HttpPost httpget = new HttpPost(GC.UrlConstants);
            HttpResponse response;
            String result = null;
            try {

                HttpContext ctx = new BasicHttpContext();

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                        2);
                httpget.setEntity(new UrlEncodedFormEntity(nameValuePairs,
                        "UTF-8"));

                response = httpclient.execute(httpget, ctx);
                HttpEntity resEntity = response.getEntity();

                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity);
                    JSONArray arr = new JSONArray(result);
                    Gson gson = new Gson();
                    if (arr.length() > 0) {
                        for (int j = 0; j < arr.length(); j++) {
                            Product p = gson.fromJson(arr.getString(j),
                                    Product.class);
                            productIdList.add(p.getId());
                        }                       

                    }

                }

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (SocketException e) {
                /*if (checkAbortStatus(e.getMessage()) == true) {
                    handler.sendEmptyMessage(0);
                }*/
            } catch (IOException e) {
                /*if (checkAbortStatus(e.getMessage()) == true) {
                    handler.sendEmptyMessage(0);
                }*/
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }

        private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {

                super.handleMessage(msg);
            }
        }; 

    }).start();
    return productIdList;

问题是什么我该如何解决? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

正如它所说,productIdList必须是最终才能在匿名内部类中使用。只需将其声明为:

final ArrayList<String> productIdList = new ArrayList<String>();

另请注意:

  • 您的列表将在您的方法
  • 之后填充
  • ArrayList不是线程安全的:如果没有适当的同步,调用方法的代码很可能不会立即(或根本)看到新产品添加到列表中。