有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用GridView、适配器和毕加索制作流行电影应用程序

我正在尝试制作一个应用程序,我希望我的应用程序在发布时显示一个流行电影海报网格。电影海报可从MovieDatabase API下载。然后我用毕加索来加载图像。对于GridView,我还使用了一个自定义适配器。我不知道怎么做。这是我到目前为止所做的事情。 //删除旧代码

请告诉我我必须做什么才能使我的应用程序看起来像:App mock

此应用程序是Udacity在Android中开发课程的一部分,下面是他们提供的实施指南:Implementation Guide

编辑: 由于有些人将我的问题标记为“过于宽泛”,我在陈述我的问题。下面的代码从TMDBAPI请求电影详细信息,然后以文本形式显示电影名称的网格。现在我想显示电影海报,而不是网格中的名字。海报路径存储在moviePosterPath字符串数组中。我该怎么做

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

共 (1) 个答案

  1. # 1 楼答案

    编辑:[这肯定不是我解决这个问题的方式,但为了简单起见,我将根据您已有的答案进行回答。这也没有经过测试,但只是在我的头脑中]有很多方法可以实现这一点。在我看来,基于代码,最简单的方法是向适配器添加一个新方法,清除当前数据,并用新列表更新它。我已经修改了您的代码,添加了replace方法,但是当您的Asynctask完成并且有如下新列表时,不要忘记调用它:mMovieAdapter.replace(listFromtheAsyncTask);另外,如果您听起来不熟悉,请确保您只在Asynctask的onPostExecute()方法中调用它

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