2013-08-01 47 views
0

On * productIdList.add(p.getId()); *這行說它不能在一個不同的方法中定義的內部類中引用非最終變量productIdlist。無法引用非最終變量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

正如它所說的,productIdList必須是最後才能在匿名內部類中使用。簡單地聲明爲:

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

還要注意的是:

  • 您的名單將被填充它是由你的方法返回
  • 的ArrayList是不是線程安全後:沒有適當的同步,它調用方法的代碼很可能不會立即(或根本)看不到添加到列表中的新產品。
+0

我做到了,但它仍然說同樣的東西 – mstfdz

+0

@mstfdz它應該工作 - 也許嘗試清理和建立您的項目? – assylias

+0

它工作時,我再次感謝。 – mstfdz

相關問題