如何使用Picasso从json url加载图像?

时间:2016-06-28 16:40:32

标签: android json gridview picasso

我是新的android和stackovrflow。我怎样才能使用Picasso所以我可以从我从他们的数据库url解析的json中加载电影图像?你能看看我的代码并告诉我我错过了什么吗?首先我使用虚拟图像,所以我可以填写我的gridview

private GridView gridview;

public ShowMoviesFragment() {
}

@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_main, container, false);

    gridview = (GridView) rootView.findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(getContext()));

    gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {
            Toast.makeText(getContext(), "" + position,
                    Toast.LENGTH_SHORT).show();
        }
    });
    return rootView;


}

private class ImageAdapter extends BaseAdapter {
    private List<Item> items = new ArrayList<Item>();
    private LayoutInflater inflater;

    public ImageAdapter(Context context) {
        inflater = LayoutInflater.from(context);

        items.add(new Item("", R.drawable.sample_0));
        items.add(new Item("", R.drawable.sample_1));
        items.add(new Item("", R.drawable.sample_2));
        items.add(new Item("", R.drawable.sample_3));
        items.add(new Item("", R.drawable.sample_4));
        items.add(new Item("", R.drawable.sample_5));
        items.add(new Item("", R.drawable.sample_6));
        items.add(new Item("", R.drawable.sample_7));
        items.add(new Item("", R.drawable.zootopiaposter1));
        items.add(new Item("", R.drawable.sample_4));
        items.add(new Item("", R.drawable.sample_5));
        items.add(new Item("", R.drawable.sample_6));
        items.add(new Item("", R.drawable.sample_7));


    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int i) {
        return items.get(i);
    }

    @Override
    public long getItemId(int i) {
        return items.get(i).drawableId;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v = view;
        ImageView picture;
        TextView name;

        if (v == null) {
            v = inflater.inflate(R.layout.grid_view_item, viewGroup, false);
            v.setTag(R.id.picture, v.findViewById(R.id.picture));
        }

        picture = (ImageView) v.getTag(R.id.picture);

        Item item = (Item) getItem(i);

        picture.setImageResource(item.drawableId);

        return v;
    }

    private class Item {
        final String name;
        final int drawableId;

        Item(String name, int drawableId) {
            this.name = name;
            this.drawableId = drawableId;
        }
    }
}

public class FetchMovieTask extends AsyncTask<String, Void, String[]> {

    private final String LOG_TAG = FetchMovieTask.class.getSimpleName();


    private String[] getPosterPathFromJson(String movieJsonStr) throws JSONException {
        //These are the names of the JSON objects that need to be extracted.

        final String TMDB_RESULTS = "results";
        final String TMDB_TITLE = "original_title";
        final String TMDB_OVERVIEW = "overview";
        final String TMDB_RELEASE_DATE = "release_date";
        final String TMDB_USER_RATING = "vote_average";
        final String TMDB_POSTER = "poster_path";

        JSONObject moviesDataJson = new JSONObject(movieJsonStr);
        JSONArray moviesDataArray = moviesDataJson.getJSONArray(TMDB_RESULTS);

        String[] posterPathStrs = new String[moviesDataArray.length()];

        for (int i = 0; i < moviesDataArray.length(); i++) {

            String poster_path;

            poster_path = moviesDataJson.getString(TMDB_POSTER);
            posterPathStrs[i] = poster_path;


        }

        for (String s : posterPathStrs) {
            Log.v(LOG_TAG, "Poster Paths entry : " + s);
        }
        return posterPathStrs;


    }


    @Override
    protected String[] doInBackground(String... params) {

        // These two need to be declared outside the try/catch
        // so that they can be closed in the finally block.
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        // Will contain the raw JSON response as a string.
        String movieDataJsonStr = null;
        String format = "json";

        try {
            // Construct the URL for the TheMovieDatabase query
            final String MOVIE_BASE_URL = "http://api.themoviedb.org/3/movie/popular?";
            final String FORMAT_PARAM = "mode";
            final String APPID_PARAM = "appid";

            Uri builtUri = Uri.parse(MOVIE_BASE_URL).buildUpon()
                    .appendQueryParameter(FORMAT_PARAM, format)
                    .appendQueryParameter(APPID_PARAM, BuildConfig.THE_MOVIE_DATABASE_API_KEY)
                    .build();

            URL url = new URL(builtUri.toString());
            Log.v(LOG_TAG, "Build 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;
            }
            movieDataJsonStr = buffer.toString();
            Log.v(LOG_TAG, "Movie Data JSON String:" + movieDataJsonStr);
        } catch (IOException e) {
            Log.e("PlaceholderFragment", "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("PlaceholderFragment", "Error closing stream", e);
                }
            }
        }
        try {
            return getPosterPathFromJson(movieDataJsonStr);
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);

    }

    @Override
    protected void onPostExecute(String[] result) {

        for(String moviePath: result){
            Picasso.with(getContext())
                    .load("http://image.tmdb.org/t/p/w185/result")
                    .into(gridview);
        }


    }
}

}

1 个答案:

答案 0 :(得分:0)

您发布的代码有点大而复杂。 Picasso是一个可以从Urls中获取图像并将其显示在您的视图中的工具

这是一个小片段。

Picasso.with(aContext).load(imageUrl).into(yourImageView);
毕加索做了所有的魔术!