2016-02-04 62 views
3

我的菜单选项按钮与读取HTTP数据的类不在一个类中。而且它给我“PhotoGalleryFragment不是一个封闭类”为不是封闭类

new PhotoGalleryFragment.FetchItemsTask("top-rated").execute(); 

PhotoGalleryActivity.java错误 - 在这里,我想使它所以当按下“最受好评的电影”按钮时,它通过“顶级的流行”的说法为FetchItemsTask从运行并更改API的网址,并更改返回的JSON‘’到‘顶级’

@Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.topRatedMovies) { 
      Toast.makeText(getApplicationContext(), "Top Rated Movie selected", Toast.LENGTH_LONG).show(); 

      new PhotoGalleryFragment.FetchItemsTask("top-rated").execute(); 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

PhotoGalleryFragment.java - 在这里,我想取数据。

public class FetchItemsTask extends AsyncTask<Void,Void,List<MovieItem>> { 
    private String mQuery; 
    public FetchItemsTask(String query) { 
     mQuery = query; 
    } 

    @Override 
    protected List<MovieItem> doInBackground(Void... params) { 
     return new MovieFetchr().fetchItems(mQuery); 
    } 

    @Override 
    protected void onPostExecute(List<MovieItem> items) { 
     mItems = items; 
     for (int i = 0; i < mItems.size(); i++) { 
     } 
     setupAdapter(); 
    } 

} 

我该如何解决这个问题?谢谢。

回答

3

要创建一个内部类,你需要做的是从外部类的实例,或使内部类static

因此,内PhotoGalleryFragment创建实例:

public class PhotoGalleryFragment {  
    void createTask(String query) { 
     new FetchItemsTask(query); //return it if you like, or just call execute here, doesn't matter 
    } 
} 

或者:

public static class FetchItemsTask 

但我认为你需要做的第一选择,因为setupAdapter可能是的方法0。

通过在PhotoGalleryFragment内创建,它给内部类提供了一个PhotoGalleryFragment的引用,这就是它如何能够调用它的方法。

认为它是一种无声的构造函数的参数和字段,它的作用很像这个代码,只是没有你的举手之劳:

public class FetchItemsTask extends AsyncTask<Void,Void,List<MovieItem>> { 

    private final PhotoGalleryFragment outer; 

    public FetchItemsTask(PhotoGalleryFragment outer, //a reference to the outer is passed in automatically 
     String query) { 
     this.outer = outer; //and stored in this FetchItemsTask instance 
    } 

    @Override 
    protected void onPostExecute(List<MovieItem> items) { 
     outer.setupAdapter(); //then used when outer methods are invoked 
    } 

} 
0

这不是从你包含了源代码清晰,但似乎FetchItemsTask是PhotoGalleryFragment的内部类。

要解决它,你应该让FetchItemsTask静态内部类即变化:

public class PhotoGalleryFragment extends Fragment { 
    public class FetchItemsTask extends AsyncTask<Void,Void,List<MovieItem>> { 
     ... 
    } 
} 

public class PhotoGalleryFragment extends Fragment { 
    public static class FetchItemsTask extends AsyncTask<Void,Void,List<MovieItem>> { 
     ... 
    } 
} 

更多关于内部类的细节你会发现这里 https://stackoverflow.com/questions/20252727/is-not-an-enclosing-class-java