编程语言
首页 > 编程语言> > java-不是封闭的类

java-不是封闭的类

作者:互联网

我的菜单选项按钮与获取HTTP数据的类不在同一类中.它给我“ PhotoGalleryFragment不是封闭的类”错误

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

PhotoGalleryActivity.java-在这里,我试图这样做,因此当按下“最高评级的电影”按钮时,它将传递FetchItemsTask的“最高评级”参数,以运行并更改API网址并从从“受欢迎”到“最高评分”

    @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();
    }

}

我该如何解决这样的问题?谢谢.

解决方法:

要创建内部类,您需要从外部类的实例执行此操作或将内部类设为静态:

因此,在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可能是PhotoGalleryFragment上的一种方法.

通过在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
    }

}

标签:android-asynctask,java,android
来源: https://codeday.me/bug/20191119/2033336.html