我的应用程序应该从TheMovieDB API获取流行电影照片到GridView。Udacity热门影片第1期发行
我已经构建了所有的应用程序组件,剩下的是如何将照片加载到适配器阵列中,当它落在手机上时,怎么样?
以下是我的片段代码。
public class PhotoGrid extends Fragment {
static String[] str1;
GridView gridView;
public PhotoGrid() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
}
@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();
if (id == R.id.action_refresh) {
FetchMoviesPosters fetchMoviesPosters = new FetchMoviesPosters();
fetchMoviesPosters.execute("popularity.desc");
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_photo_grid, container, false);
GridView gridView = (GridView) rootView.findViewById(R.id.grid_view);
return rootView;
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private String[] mThumbIds;
public ImageAdapter(Context c,String[] str2) {
mContext = c;
mThumbIds=str2;
}
@Override
public int getCount() {
if(mThumbIds!=null)
{
return mThumbIds.length;
}
else
{
return 0;
}
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(500,500));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(4, 4, 4, 4);
} else {
imageView = (ImageView) convertView;
}
Picasso.with(mContext).load(mThumbIds[position]).into(imageView);
//imageView.setImageResource(Integer.parseInt(mThumbIds[position]));
return imageView;
}
}
public class FetchMoviesPosters extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchMoviesPosters.class.getSimpleName();
private String[] MoviesJasonPrase(String moviesPosterStr) throws JSONException {
final String Poster_Path = "poster_path";
JSONObject moviesJson = new JSONObject(moviesPosterStr);
JSONArray resultsArray = moviesJson.getJSONArray("results");
String[] resultStrs = new String[0];
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject indexObject = resultsArray.getJSONObject(i);
String poster = indexObject.getString(Poster_Path);
resultStrs[i] = poster; // Add each item to the list
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Posters entry: " + s);
}
return resultStrs;
}
@Override
protected String[] doInBackground(String... params) {
if (params.length == 0) {
return null;
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String moviePostersJsonStr = null;
try {
final String FORECAST_BASE_URL =
"https://api.themoviedb.org/3/discover/movie?";
final String SORT_OPTI = "sort_by";
final String APPID_PARAM = "api_key";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(SORT_OPTI, params[0])
.appendQueryParameter(APPID_PARAM, BuildConfig.THE_MOVIE_DB)
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// 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) {
// Stream was empty. No point in parsing.
return null;
}
moviePostersJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("PhotoGrid", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PhotoGrid", "Error closing stream", e);
}
}
}
return null;
}
@Override
protected void onPostExecute(String[] Strings) {
if (Strings != null) {
str1 = new String[Strings.length];
for (int i = 0; i < Strings.length; i++) {
String[] getImage=Strings[i].split("-");
str1[i] = "http://image.tmdb.org/t/p/w185/" + getImage[0];
}
ImageAdapter adp = new ImageAdapter(getActivity(),str1);
gridView.setAdapter(adp);
}
}
}
}
这是我从我使用的JSONformatter,以使其更清晰的API获得的一部分:
{
"page":1,
"results":[
{
"poster_path":"\/6bCplVkhowCjTHXWv49UjRPn0eK.jpg",
"adult":false,
"overview":"Fearing the actions of a god-like Super Hero left unchecked, Gotham City’s own formidable, forceful vigilante takes on Metropolis’s most revered, modern-day savior, while the world wrestles with what sort of hero it really needs. And with Batman and Superman at war with one another, a new threat quickly arises, putting mankind in greater danger than it’s ever known before.",
"release_date":"2016-03-23",
"genre_ids":[
28,
12,
14,
878
],
"id":209112,
"original_title":"Batman v Superman: Dawn of Justice",
"original_language":"en",
"title":"Batman v Superman: Dawn of Justice",
"backdrop_path":"\/vsjBeMPZtyB7yNsYY56XYxifaQZ.jpg",
"popularity":51.416795,
"vote_count":302,
"video":false,
"vote_average":5.8
},
{
"poster_path":"\/w93GAiq860UjmgR6tU9h2T24vaV.jpg",
"adult":false,
"overview":"With the nation of Panem in a full scale war, Katniss confronts President Snow in the final showdown. Teamed with a group of her closest friends – including Gale, Finnick, and Peeta – Katniss goes off on a mission with the unit from District 13 as they risk their lives to stage an assassination attempt on President Snow who has become increasingly obsessed with destroying her. The mortal traps, enemies, and moral choices that await Katniss will challenge her more than any arena she faced in The Hunger Games.",
"release_date":"2015-11-18",
"genre_ids":[
28,
12,
18
],
"id":131634,
"original_title":"The Hunger Games: Mockingjay - Part 2",
"original_language":"en",
"title":"The Hunger Games: Mockingjay - Part 2",
"backdrop_path":"\/qjn3fzCAHGfl0CzeUlFbjrsmu4c.jpg",
"popularity":39.643568,
"vote_count":1326,
"video":false,
"vote_average":6.79
},
能否请你告诉我如何因为我想并没有和我一起工作 – Khaled
你能张贴JSON你从API得到什么? – androidnoobdev
androidnoobdev先生恳请 – Khaled