Java – not a closed class
My menu option button is not in the same class as the class that gets HTTP data. It gives me the error that "photogalleryfragment is not a closed class"
new PhotoGalleryFragment.FetchItemsTask("top-rated").execute();
Photogalleryactivity.java - here, I try to do this, so when I press the "highest rated movie" button, it will pass the "highest rated" parameter of fetchitemstask to run and change the API URL from "popular" to "highest rated"
@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 - here, I try to get the data
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();
}
}
How can I solve such a problem? thank you.
resolvent:
To create an inner class, you need to do this from an instance of the outer class or make the inner class static:
Therefore, create an instance in photogalleryfragment:
public class PhotoGalleryFragment {
void createTask(String query) {
new FetchItemsTask(query); //return it if you like, or just call execute here, doesn't matter
}
}
or
public static class FetchItemsTask
But I think you will need to make the first choice, because setupadapter may be a method on photogallery fragment
By creating in the photogalleryfragment, the internal class can be provided with a reference to the photogalleryfragment, which is the way it can call methods on it
You can think of it as a silent constructor parameter and field, which behaves like this code, but without effort:
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
}
}