我正在尝试创建一个应用程序,我想要我的应用程序,在发布时,显示一个流行的电影海报网格。电影海报是从TheMovieDataBase API下载的。然后我使用Picasso加载图像。对于GridView,我也使用自定义适配器。我无法理解如何做到这一点。这是我到目前为止所做的。 //删除旧代码
请告诉我我必须这样做,以便我的应用看起来像这样:App mock
这个应用程序是Udacity在Android中开发的一部分,这里是他们提供的实施指南:Implementation Guide
编辑: 由于有些人将我的问题标记为“过于宽泛”,我重申了我的问题。以下代码从TMDB api请求电影详细信息,然后在文本中显示电影名称的网格。现在我想显示电影海报而不是网格中的名字。海报路径存储在moviePosterPath String数组中。我该怎么做?
public class MainActivityFragment extends Fragment {
ArrayAdapter<String> mMovieAdapter;
String[] movieId, movieTitle, movieReleaseDate, movieVoteAverage, movieOverview, moviePosterPath;
public MainActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
GridView listView = (GridView) rootView.findViewById(R.id.gridview_movies);
mMovieAdapter = new ArrayAdapter<String>(getActivity(),
R.layout.item_movies,
R.id.image_view_movie,
new ArrayList<String>());
listView.setAdapter(mMovieAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
Intent intent = new Intent(getActivity(), DetailActivity.class);
String forecast = mMovieAdapter.getItem(i);
String send = "Overview" + movieOverview[i] + "\n" + "Release Date" + movieReleaseDate[i];
intent.putExtra(Intent.EXTRA_TEXT, send);
startActivity(intent);
}
});
return rootView;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.moviefragment, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateMovie();
return true;
}
return super.onOptionsItemSelected(item);
}
public void onStart()
{
super.onStart();
updateMovie();
}
private void updateMovie() {
FetchMovieTask movieTask = new FetchMovieTask();
movieTask.execute();
}
class FetchMovieTask extends AsyncTask<Void, Void, String[]> {
private final String LOG_TAG = FetchMovieTask.class.getSimpleName();
@Override
protected String[] doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String movieJsonStr = null;
try {
URL url = new URL("http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=c20129fdf73b5df3ab44548ad7f73586");
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) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
movieJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
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);
}
}
}
try {
return getMovieDataFromJson(movieJsonStr);
} catch (JSONException j) {
Log.e(LOG_TAG, "JSON Error", j);
}
return null;
}
private String[] getMovieDataFromJson(String forecastJsonStr)
throws JSONException {
JSONObject movieJson = new JSONObject(forecastJsonStr);
JSONArray movieArray = movieJson.getJSONArray("results");
movieId = new String[movieArray.length()];
movieTitle = new String[movieArray.length()];
movieReleaseDate = new String[movieArray.length()];
movieVoteAverage = new String[movieArray.length()];
movieOverview = new String[movieArray.length()];
moviePosterPath = new String[movieArray.length()];
for (int i = 0; i < movieArray.length(); i++)
{
JSONObject movie = movieArray.getJSONObject(i);
movieId[i] = movie.getString("id");
movieTitle[i] = movie.getString("original_title");
movieReleaseDate[i] = movie.getString("release_date");
movieVoteAverage[i] = movie.getString("vote_average");
movieOverview[i] = movie.getString("overview");
moviePosterPath[i] = movie.getString("poster_path");
}
return movieTitle;
}
@Override
protected void onPostExecute(String[] strings)
{
super.onPostExecute(strings);
mMovieAdapter.clear();
mMovieAdapter.addAll(strings);
}
}
}
答案 0 :(得分:2)
编辑:[这绝对不是我会如何解决这个问题,但为了简单起见,我将根据您已有的内容进行回答。这也没有经过测试,但仅仅是我的头脑。有很多方法可以做到这一点。基于您的代码,我认为最简单的方法是向您的适配器添加一个清除当前数据的新方法,并使用新的List对其进行更新。我已经修改了你的代码来添加替换方法,但是当你的Asynctask完成时不要忘记调用它并且有这样的新列表:mMovieAdapter.replace(listFromtheAsyncTask);
另外,让你只调用它在Asynctask的onPostExecute()方法中读取Asynctask documentation,如果你觉得这听起来不熟悉的话。
public class MainActivityFragment extends Fragment {
//ArrayAdapter<String> mMovieAdapter;
String[] movieId,movieTitle,movieOverview,movieReleaseDate,moviePosterPath,movieVoteAverage;
public MainActivityFragment() {
}
MovieAdapter mMovieAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mMovieAdapter = new MovieAdapter(getActivity());
GridView listView = (GridView) rootView.findViewById(R.id.gridview_movies);
listView.setAdapter(mMovieAdapter);
updateMovie();
return rootView;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.moviefragment, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateMovie();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateMovie() {
FetchMovieTask movieTask = new FetchMovieTask();
movieTask.execute();
}
class FetchMovieTask extends AsyncTask<Void, Void, List<String>> {
private final String LOG_TAG = FetchMovieTask.class.getSimpleName();
@Override
protected List<String> doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String movieJsonStr = null;
try {
URL url = new URL("http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=c20129fdf73b5df3ab44548ad7f73586");
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) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
movieJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
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);
}
}
}
try {
return getMovieDataFromJson(movieJsonStr);
} catch (JSONException j) {
Log.e(LOG_TAG, "JSON Error", j);
}
return null;
}
private List<String> getMovieDataFromJson(String forecastJsonStr)
throws JSONException {
JSONObject movieJson = new JSONObject(forecastJsonStr);
JSONArray movieArray = movieJson.getJSONArray("results");
List<String> urls = new ArrayList<>();
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movie = movieArray.getJSONObject(i);
urls.add("http://image.tmdb.org/t/p/w185" + movie.getString("poster_path"));
}
return urls;
}
@Override
protected void onPostExecute(List<String> strings) {
mMovieAdapter.replace(strings);
}
}
class MovieAdapter extends BaseAdapter {
private final String LOG_TAG = MovieAdapter.class.getSimpleName();
private final Context context;
private final List<String> urls = new ArrayList<String>();
public MovieAdapter(Context context) {
this.context = context;
Collections.addAll(urls, moviePosterPath);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = new ImageView(context);
}
ImageView imageView = (ImageView) convertView;
String url = getItem(position);
Log.e(LOG_TAG," URL "+url);
Picasso.with(context).load(url).into(imageView);
return convertView;
}
@Override
public int getCount() {
return urls.size();
}
@Override
public String getItem(int position) {
return urls.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public void replace(List<String> urls) {
this.urls.clear();
this.urls.addAll(urls);
notifyDataSetChanged();
}
}
}