Android 无法从api调用填充gridview
我已经梳理了stackoverflow以寻找解决方案,我尝试了大量的代码片段,但还没有找到问题所在 因此,我正在学习android Udacity课程,他们要求我在gridview中填充电影海报,这些海报来自对电影数据库的api调用。 我在stackoverflow上看到许多其他人在做同样的项目,但是我的主要区别(可能还有他们的解决方案对我不起作用的原因)是,我试图在单独的文件中处理所有主要类,而不是将所有内容都放在主活动或类似的内容中 我已经尝试了所有适用于它们的解决方案,例如将gridview适配器声明和setadapter移动到asynctask中onPostExecute的末尾,并反复修改了ImageAdapter类,但我无法让它工作 我的应用程序可以很好地调用API,记录收到的JSON和所有海报链接,并将链接正确地复制到arraylist中;但gridview不会填充 这是我的密码: MainActivity.javaAndroid 无法从api调用填充gridview,android,gridview,picasso,Android,Gridview,Picasso,我已经梳理了stackoverflow以寻找解决方案,我尝试了大量的代码片段,但还没有找到问题所在 因此,我正在学习android Udacity课程,他们要求我在gridview中填充电影海报,这些海报来自对电影数据库的api调用。 我在stackoverflow上看到许多其他人在做同样的项目,但是我的主要区别(可能还有他们的解决方案对我不起作用的原因)是,我试图在单独的文件中处理所有主要类,而不是将所有内容都放在主活动或类似的内容中 我已经尝试了所有适用于它们的解决方案,例如将gridvie
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new GalleryFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
public class ImageAdapter extends BaseAdapter {
private final String LOG_TAG = ImageAdapter.class.getSimpleName();
private List<?> mImageList = new ArrayList<>();
private LayoutInflater inflater;
public ImageAdapter(LayoutInflater i, List<?> images) {
this.mImageList = images;
this.inflater = i;
}
@Override
public Object getItem(int position) {
return mImageList.get(position);
}
@Override
public int getCount() {
return mImageList.size();
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null){
imageView = new ImageView(inflater.getContext());
} else {
imageView = (ImageView) convertView;
}
Log.v(LOG_TAG,"New one: " + mImageList.get(position).toString());
Picasso
.with(inflater.getContext())
.load(mImageList.get(position).toString())
.into(imageView);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setAdjustViewBounds(true);
return imageView;
}
}
public class GalleryFragment extends Fragment {
public static GridView gridView;
public static ImageAdapter imageAdapter;
public GalleryFragment() {
// Required empty public constructor
}
@Override
public void onStart() {
super.onStart();
FetchMovies data = new FetchMovies(getActivity());
data.execute();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
gridView = (GridView) rootView.findViewById(R.id.gridview);
return rootView;
}
}
public class FetchMovies extends AsyncTask <Void, Void, String[]> {
private final String LOG_TAG = FetchMovies.class.getSimpleName();
private Context context;
List<Uri> posterURLs = new ArrayList<>();
String[] title, overview, popularity, rating, releaseDate;
public FetchMovies(Context c){
this.context = c;
}
/**
* Prepare image URL for presentation.
*/
private String formatURL(String relativeURL) {
String imageBaseURL = "http://image.tmdb.org/t/p/";
String size = "w185";
relativeURL = relativeURL.substring(1);
Uri uri = Uri.parse(imageBaseURL).buildUpon()
.appendPath(size)
.appendPath(relativeURL).build();
return uri.toString();
}
private String[] getMovieDataFromJson(String movieJsonStr)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String RESULT_LIST = "results";
final String TITLE = "original_title";
final String POSTER_URL = "poster_path";
final String OVERVIEW = "overview";
final String POPULARITY = "popularity";
final String RATING = "vote_average";
final String RELEASE_DATE = "release_date";
JSONObject allMovieData = new JSONObject(movieJsonStr);
JSONArray resultsArray = allMovieData.getJSONArray(RESULT_LIST);
String[] posterPaths = new String[resultsArray.length()];
title = new String[resultsArray.length()];
overview = new String[resultsArray.length()];
popularity = new String[resultsArray.length()];
rating = new String[resultsArray.length()];
releaseDate = new String[resultsArray.length()];
for(int i = 0; i < resultsArray.length(); i++) {
// Get the JSON object representing one movie's details
JSONObject eachMovie = resultsArray.getJSONObject(i);
title[i] = eachMovie.getString(TITLE);
String relativeURL = eachMovie.getString(POSTER_URL);
posterPaths[i] = formatURL(relativeURL);
overview[i] = eachMovie.getString(OVERVIEW);
popularity[i] = eachMovie.getString(POPULARITY);
rating[i] = eachMovie.getString(RATING);
releaseDate[i] = eachMovie.getString(RELEASE_DATE);
Log.v("poster path", posterPaths[i]);
}
return posterPaths;
}
@Override
protected String[] doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
//For building the URL for the weather query from OpenWeatherMap
final String BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
final String SORT_PARAM = "sort_by";
final String API_PARAM = "api_key";
String sort_by = "popularity.desc",
apiKey = "MY API KEY IS PLACED HERE";
// Will contain the raw JSON response as a string.
String movieJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are available at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
Uri queryUri = Uri.parse(BASE_URL).buildUpon()
//.appendQueryParameter(SORT_PARAM,params[0])
.appendQueryParameter(SORT_PARAM, sort_by)
.appendQueryParameter(API_PARAM,apiKey).build();
URL queryUrl = new URL(queryUri.toString());
// Create the request to TheMovieDB, and open the connection
urlConnection = (HttpURLConnection) queryUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
Log.v(LOG_TAG, "Couldn't open input stream.");
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
Log.v(LOG_TAG, "Input stream was empty.");
// Stream was empty. No point in parsing.
return null;
}
//if all's well, parse the required data and return it to the system
//(which then calls the onPostExecute() method with this data).
movieJsonStr = buffer.toString();
Log.v(LOG_TAG,movieJsonStr);
return getMovieDataFromJson(movieJsonStr);
//return getWeatherDataFromJson(forecastJsonStr, numDays);
} catch (IOException e) {
Log.e(LOG_TAG, "Error: Couldn't get movie data. ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
return null;
} catch (JSONException e) {
Log.e(LOG_TAG, "Error in parsing: ", e);
//If there is an error in parsing the JSON data, there's nothing to display.
return null;
}
finally
{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
}
@Override
protected void onPostExecute(String[] strings) {
super.onPostExecute(strings);
for (int i=0; i<strings.length;i++){
Uri uri = Uri.parse(strings[i]);
posterURLs.add(uri);
}
LayoutInflater inflater = LayoutInflater.from(context);
GalleryFragment.imageAdapter = new ImageAdapter(inflater,posterURLs);
GalleryFragment.gridView.setAdapter(GalleryFragment.imageAdapter);
}
}
ImageAdapter.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new GalleryFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
public class ImageAdapter extends BaseAdapter {
private final String LOG_TAG = ImageAdapter.class.getSimpleName();
private List<?> mImageList = new ArrayList<>();
private LayoutInflater inflater;
public ImageAdapter(LayoutInflater i, List<?> images) {
this.mImageList = images;
this.inflater = i;
}
@Override
public Object getItem(int position) {
return mImageList.get(position);
}
@Override
public int getCount() {
return mImageList.size();
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null){
imageView = new ImageView(inflater.getContext());
} else {
imageView = (ImageView) convertView;
}
Log.v(LOG_TAG,"New one: " + mImageList.get(position).toString());
Picasso
.with(inflater.getContext())
.load(mImageList.get(position).toString())
.into(imageView);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setAdjustViewBounds(true);
return imageView;
}
}
public class GalleryFragment extends Fragment {
public static GridView gridView;
public static ImageAdapter imageAdapter;
public GalleryFragment() {
// Required empty public constructor
}
@Override
public void onStart() {
super.onStart();
FetchMovies data = new FetchMovies(getActivity());
data.execute();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
gridView = (GridView) rootView.findViewById(R.id.gridview);
return rootView;
}
}
public class FetchMovies extends AsyncTask <Void, Void, String[]> {
private final String LOG_TAG = FetchMovies.class.getSimpleName();
private Context context;
List<Uri> posterURLs = new ArrayList<>();
String[] title, overview, popularity, rating, releaseDate;
public FetchMovies(Context c){
this.context = c;
}
/**
* Prepare image URL for presentation.
*/
private String formatURL(String relativeURL) {
String imageBaseURL = "http://image.tmdb.org/t/p/";
String size = "w185";
relativeURL = relativeURL.substring(1);
Uri uri = Uri.parse(imageBaseURL).buildUpon()
.appendPath(size)
.appendPath(relativeURL).build();
return uri.toString();
}
private String[] getMovieDataFromJson(String movieJsonStr)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String RESULT_LIST = "results";
final String TITLE = "original_title";
final String POSTER_URL = "poster_path";
final String OVERVIEW = "overview";
final String POPULARITY = "popularity";
final String RATING = "vote_average";
final String RELEASE_DATE = "release_date";
JSONObject allMovieData = new JSONObject(movieJsonStr);
JSONArray resultsArray = allMovieData.getJSONArray(RESULT_LIST);
String[] posterPaths = new String[resultsArray.length()];
title = new String[resultsArray.length()];
overview = new String[resultsArray.length()];
popularity = new String[resultsArray.length()];
rating = new String[resultsArray.length()];
releaseDate = new String[resultsArray.length()];
for(int i = 0; i < resultsArray.length(); i++) {
// Get the JSON object representing one movie's details
JSONObject eachMovie = resultsArray.getJSONObject(i);
title[i] = eachMovie.getString(TITLE);
String relativeURL = eachMovie.getString(POSTER_URL);
posterPaths[i] = formatURL(relativeURL);
overview[i] = eachMovie.getString(OVERVIEW);
popularity[i] = eachMovie.getString(POPULARITY);
rating[i] = eachMovie.getString(RATING);
releaseDate[i] = eachMovie.getString(RELEASE_DATE);
Log.v("poster path", posterPaths[i]);
}
return posterPaths;
}
@Override
protected String[] doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
//For building the URL for the weather query from OpenWeatherMap
final String BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
final String SORT_PARAM = "sort_by";
final String API_PARAM = "api_key";
String sort_by = "popularity.desc",
apiKey = "MY API KEY IS PLACED HERE";
// Will contain the raw JSON response as a string.
String movieJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are available at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
Uri queryUri = Uri.parse(BASE_URL).buildUpon()
//.appendQueryParameter(SORT_PARAM,params[0])
.appendQueryParameter(SORT_PARAM, sort_by)
.appendQueryParameter(API_PARAM,apiKey).build();
URL queryUrl = new URL(queryUri.toString());
// Create the request to TheMovieDB, and open the connection
urlConnection = (HttpURLConnection) queryUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
Log.v(LOG_TAG, "Couldn't open input stream.");
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
Log.v(LOG_TAG, "Input stream was empty.");
// Stream was empty. No point in parsing.
return null;
}
//if all's well, parse the required data and return it to the system
//(which then calls the onPostExecute() method with this data).
movieJsonStr = buffer.toString();
Log.v(LOG_TAG,movieJsonStr);
return getMovieDataFromJson(movieJsonStr);
//return getWeatherDataFromJson(forecastJsonStr, numDays);
} catch (IOException e) {
Log.e(LOG_TAG, "Error: Couldn't get movie data. ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
return null;
} catch (JSONException e) {
Log.e(LOG_TAG, "Error in parsing: ", e);
//If there is an error in parsing the JSON data, there's nothing to display.
return null;
}
finally
{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
}
@Override
protected void onPostExecute(String[] strings) {
super.onPostExecute(strings);
for (int i=0; i<strings.length;i++){
Uri uri = Uri.parse(strings[i]);
posterURLs.add(uri);
}
LayoutInflater inflater = LayoutInflater.from(context);
GalleryFragment.imageAdapter = new ImageAdapter(inflater,posterURLs);
GalleryFragment.gridView.setAdapter(GalleryFragment.imageAdapter);
}
}
FetchMovies.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new GalleryFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
public class ImageAdapter extends BaseAdapter {
private final String LOG_TAG = ImageAdapter.class.getSimpleName();
private List<?> mImageList = new ArrayList<>();
private LayoutInflater inflater;
public ImageAdapter(LayoutInflater i, List<?> images) {
this.mImageList = images;
this.inflater = i;
}
@Override
public Object getItem(int position) {
return mImageList.get(position);
}
@Override
public int getCount() {
return mImageList.size();
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null){
imageView = new ImageView(inflater.getContext());
} else {
imageView = (ImageView) convertView;
}
Log.v(LOG_TAG,"New one: " + mImageList.get(position).toString());
Picasso
.with(inflater.getContext())
.load(mImageList.get(position).toString())
.into(imageView);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setAdjustViewBounds(true);
return imageView;
}
}
public class GalleryFragment extends Fragment {
public static GridView gridView;
public static ImageAdapter imageAdapter;
public GalleryFragment() {
// Required empty public constructor
}
@Override
public void onStart() {
super.onStart();
FetchMovies data = new FetchMovies(getActivity());
data.execute();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
gridView = (GridView) rootView.findViewById(R.id.gridview);
return rootView;
}
}
public class FetchMovies extends AsyncTask <Void, Void, String[]> {
private final String LOG_TAG = FetchMovies.class.getSimpleName();
private Context context;
List<Uri> posterURLs = new ArrayList<>();
String[] title, overview, popularity, rating, releaseDate;
public FetchMovies(Context c){
this.context = c;
}
/**
* Prepare image URL for presentation.
*/
private String formatURL(String relativeURL) {
String imageBaseURL = "http://image.tmdb.org/t/p/";
String size = "w185";
relativeURL = relativeURL.substring(1);
Uri uri = Uri.parse(imageBaseURL).buildUpon()
.appendPath(size)
.appendPath(relativeURL).build();
return uri.toString();
}
private String[] getMovieDataFromJson(String movieJsonStr)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String RESULT_LIST = "results";
final String TITLE = "original_title";
final String POSTER_URL = "poster_path";
final String OVERVIEW = "overview";
final String POPULARITY = "popularity";
final String RATING = "vote_average";
final String RELEASE_DATE = "release_date";
JSONObject allMovieData = new JSONObject(movieJsonStr);
JSONArray resultsArray = allMovieData.getJSONArray(RESULT_LIST);
String[] posterPaths = new String[resultsArray.length()];
title = new String[resultsArray.length()];
overview = new String[resultsArray.length()];
popularity = new String[resultsArray.length()];
rating = new String[resultsArray.length()];
releaseDate = new String[resultsArray.length()];
for(int i = 0; i < resultsArray.length(); i++) {
// Get the JSON object representing one movie's details
JSONObject eachMovie = resultsArray.getJSONObject(i);
title[i] = eachMovie.getString(TITLE);
String relativeURL = eachMovie.getString(POSTER_URL);
posterPaths[i] = formatURL(relativeURL);
overview[i] = eachMovie.getString(OVERVIEW);
popularity[i] = eachMovie.getString(POPULARITY);
rating[i] = eachMovie.getString(RATING);
releaseDate[i] = eachMovie.getString(RELEASE_DATE);
Log.v("poster path", posterPaths[i]);
}
return posterPaths;
}
@Override
protected String[] doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
//For building the URL for the weather query from OpenWeatherMap
final String BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
final String SORT_PARAM = "sort_by";
final String API_PARAM = "api_key";
String sort_by = "popularity.desc",
apiKey = "MY API KEY IS PLACED HERE";
// Will contain the raw JSON response as a string.
String movieJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are available at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
Uri queryUri = Uri.parse(BASE_URL).buildUpon()
//.appendQueryParameter(SORT_PARAM,params[0])
.appendQueryParameter(SORT_PARAM, sort_by)
.appendQueryParameter(API_PARAM,apiKey).build();
URL queryUrl = new URL(queryUri.toString());
// Create the request to TheMovieDB, and open the connection
urlConnection = (HttpURLConnection) queryUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
Log.v(LOG_TAG, "Couldn't open input stream.");
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
Log.v(LOG_TAG, "Input stream was empty.");
// Stream was empty. No point in parsing.
return null;
}
//if all's well, parse the required data and return it to the system
//(which then calls the onPostExecute() method with this data).
movieJsonStr = buffer.toString();
Log.v(LOG_TAG,movieJsonStr);
return getMovieDataFromJson(movieJsonStr);
//return getWeatherDataFromJson(forecastJsonStr, numDays);
} catch (IOException e) {
Log.e(LOG_TAG, "Error: Couldn't get movie data. ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
return null;
} catch (JSONException e) {
Log.e(LOG_TAG, "Error in parsing: ", e);
//If there is an error in parsing the JSON data, there's nothing to display.
return null;
}
finally
{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
}
@Override
protected void onPostExecute(String[] strings) {
super.onPostExecute(strings);
for (int i=0; i<strings.length;i++){
Uri uri = Uri.parse(strings[i]);
posterURLs.add(uri);
}
LayoutInflater inflater = LayoutInflater.from(context);
GalleryFragment.imageAdapter = new ImageAdapter(inflater,posterURLs);
GalleryFragment.gridView.setAdapter(GalleryFragment.imageAdapter);
}
}
我的日志还显示ImageAdapter类只被调用一次。当它填充gridview时,是否应该多次调用它?
在这一点上,我非常确信问题与布局文件有关,也许我没有在正确的位置调用正确的布局文件或类似的东西,但我无法找到它。非常感谢您的帮助,谢谢 我终于找到了问题所在。正如我所想的,很明显,我是用布局来俯瞰的 在fragment_gallery.xml中,我有:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.zakna.popularmovies.GalleryFragment">
<GridView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/gridview"
android:layout_gravity="start|top"
android:numColumns="auto_fit"
android:clickable="false" />
</FrameLayout>
现在我的应用程序正确地显示了gridView中的所有图像
谢谢 我终于找到了问题所在。正如我所想的,很明显,我是用布局来俯瞰的 在fragment_gallery.xml中,我有:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.zakna.popularmovies.GalleryFragment">
<GridView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/gridview"
android:layout_gravity="start|top"
android:numColumns="auto_fit"
android:clickable="false" />
</FrameLayout>
现在我的应用程序正确地显示了gridView中的所有图像
谢谢 你有权限吗?我有清单文件中的internet权限。我是否需要任何其他权限?可能是存储权限?我找到的唯一存储权限是在外部存储上读/写,应用程序从不尝试访问这些存储;我还是试过了,但是gridview仍然没有填充。我不认为权限是问题所在;因为如果存在权限问题,应用程序将崩溃并向您提供与权限相关的错误。您有权限吗?我在清单文件中有internet权限。我是否需要任何其他权限?可能是存储权限?我找到的唯一存储权限是在外部存储上读/写,应用程序从不尝试访问这些存储;我还是试过了,但是gridview仍然没有填充。我不认为权限是问题所在;因为如果存在权限问题,应用程序会崩溃,并给出与权限相关的错误。