如何在android studio中使用适配器将图像从api加载到gridview中?

时间:2016-02-15 14:27:24

标签: android-studio android-gridview baseadapter

public class MainActivityFragment extends Fragment {


    static String[] str1;
    GridView gridview;

    public MainActivityFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.refresh_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id=item.getItemId();
        if (id == R.id.action_refresh) {
            updateWeather();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void updateWeather() {
        fetchMovies movieTask=new fetchMovies();
         movieTask.execute("hi");
    }

    @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(getActivity()));

        return rootview;
    }

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

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

        private String[] getMovieDataFromJson(String forecastJsonStr, int numDays)
                throws JSONException {


            JSONObject movieJson = new JSONObject(forecastJsonStr);
            JSONArray movieArray = movieJson.getJSONArray("results");


            String[] resultStrs = new String[movieArray.length()];
            for(int i = 0; i < movieArray.length(); i++) {

                JSONObject getMovie = movieArray.getJSONObject(i);

                String moviePosterPathImage=getMovie.getString("poster_path");
                String movieOverview=getMovie.getString("overview");
                String split_release_date=getMovie.getString("release_date");
                String[] Segments = split_release_date.split("-");
                String release_date=Segments[1]+"-"+Segments[2]+"-"+Segments[0];
                String title=getMovie.getString("title");
                Double vote_Average=getMovie.getDouble("vote_average");

                resultStrs[i] = moviePosterPathImage + " - " + movieOverview + " - " + release_date + " - " + title + " - " + vote_Average;
            }

            for (String s : resultStrs) {
                Log.v(LOG_TAG, "Forecast entry: " + s);
            }
            return resultStrs;

        }


        @Override
        protected String[] doInBackground(String... params) {
            HttpURLConnection urlConnection=null;
            BufferedReader reader=null;

            //will contain the raw json response as a string
            String forecastJsonStr=null;
            int Format_Cnt_Value=7;
            String Format_Api="api_key";
            try {
                String Format_Mode="sort_by";
                String Format_Mode_Val="popularity.desc";


                String OPEN_MOVIES_API_KEY="-----My Api Key------";

                String baseUrl="http://api.themoviedb.org/3/discover/movie?";
                Uri builtUri=Uri.parse(baseUrl).buildUpon()
                         .appendQueryParameter(Format_Mode,Format_Mode_Val)
                         .appendQueryParameter(Format_Api,OPEN_MOVIES_API_KEY)
                         .build();

                 URL url=new URL(builtUri.toString());

                Log.v(LOG_TAG,"test_Uri= " + builtUri);


                urlConnection= (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                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;
                }
                forecastJsonStr = buffer.toString();
                Log.v(LOG_TAG, "Forecast JsonString:=" + forecastJsonStr);
            } catch (IOException e) {
                Log.e(LOG_TAG, "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(LOG_TAG, "Error closing stream", e);
                    }
                }
            };
            try {

                return getMovieDataFromJson(forecastJsonStr,Format_Cnt_Value);
            } catch (JSONException e) {
                e.printStackTrace();
            }



            return null;
        }
        @Override
        protected void onPostExecute(String[] Strings) {
             if (Strings != null) {
                //adp.clear();
                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];
                }
                adp=new ImageAdapter(getActivity(),str1);
                gridview.setAdapter(adp);   //error

            }
        }
    }
}

我现在应该怎么做...... 我也有ImageAdapter类

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

//        imageView.setImageResource(Integer.parseInt(mThumbIds[position]));
        imageView.setImageResource(Integer.parseInt(mThumbIds[position]));
        return imageView;
    }
}

请帮忙。     我已从api加载数据并想填充gridview。     我在string []中获取图像...如何填充gridview ..     我需要你的帮助来使用适配器填充gridview     提前数十亿的感谢。

1 个答案:

答案 0 :(得分:0)

使用Picasso库在网格视图中加载网址图片。查看有关如何使用picasso的this链接。 在你的适配器getView()方法中添加以下行:

Picasso.with(mContext).load(mThumbIds[position]).into(imageView);