0

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;

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

4

1 回答 1

1

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

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

另请注意:

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