2015-06-08 26 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