2015-06-08 23 views
0

我有這樣的方法:Android - 如何使用內部類聲明的變量?

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     AnimalWebService animalWebService = restAdapter.create(AnimalWebService.class); 

     Callback<List<Animal>> callback = new Callback<List<Animal>>() { 
      @Override 
      public void success(List<Animal> animals, Response response) { 
       if (animals == null) { 
        Context context = getApplicationContext(); 
        CharSequence text = "No animals available!"; 
        int duration = Toast.LENGTH_SHORT; 

        Toast toast = Toast.makeText(context, text, duration); 
        toast.show(); 
       } 
       else { 
        ListAdapter theAdapter = new MyAdapter(getApplicationContext(), animals); 
       } 
      } 
      @Override 
      public void failure(RetrofitError retrofitError) { 
       return; 
      } 
     }; 

     animalWebService.get(callback); 
     theListView.setAdapter(theAdapter); 
    } 

我到底有theListView.setAdapter(theAdapter);theAdapter因爲它是在一個內部類中聲明不承認這裏。

我該如何解決這個問題?在Android中進行編程時,這種情況的最佳做法是什麼?

+0

我剛剛發佈您的答案請採取食物吧。 – AnixPasBesoin

回答

4

如果您不需要在Activity類的其他部分theAdapter參考,我只想從回調更新:

Callback<List<Animal>> callback = new Callback<List<Animal>>() { 
     @Override 
     public void success(List<Animal> animals, Response response) { 
      if (animals == null) { 
      } 
      else { 
       ListAdapter theAdapter = new MyAdapter(getApplicationContext(), animals); 
       theListView.setAdapter(theAdapter); 
      } 
     } 
     @Override 
     public void failure(RetrofitError retrofitError) { 
      return; 
     } 
    }; 

這可以確保你永遠不會在列表視圖調用setAdapter(null) ,這很好。您應該根據回調的結果觸發事件:您的呼叫可能失敗(然後調用failure),或者它可能返回空列表。在這些情況下,我們不希望將ListView附加到適配器。

+0

它不能識別成功方法中的'theListView'。 –

+0

您可能需要將ListView聲明爲「final」(當然,在實例化回調之前)。 – natario