java - 在android中使用Picasso填充gridview

java - 在android中使用Picasso填充gridview,第1张

我正在尝试使用从电影数据库返回的海报图像填充网格视图。我一步一步,没有遇到和错误,但没有显示任何内容。这是我的代码任何帮助将不胜感激。我认为问题在于适配器,但我调试了这个,并且网格视图最终得到了正确数量的子项。

公共类MainActivity扩展了AppCompatActivity {

private GridView mMoviesGrid;
private ListAdapter mMoviesAdapter;
public ArrayList<String> mPosterMoviePaths;
String mMovieJsonStr = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mMoviesGrid = (GridView) findViewById(R.id.movie_list_grid);

    new FetchMovieData().execute();

    if(mMovieJsonStr != null){
        mPosterMoviePaths =  MovieDataParser.getMoviePosterPaths(mMovieJsonStr);
    }

    mMoviesAdapter = new MovieAdapter(this, mPosterMoviePaths);
    mMoviesGrid.setAdapter(mMoviesAdapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

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

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private class MovieAdapter extends ArrayAdapter {
    private Context mContext;
    private ArrayList<String> mItems;

    public MovieAdapter(Context context, ArrayList<String> objects) {
        super(context, R.layout.movie_grid_item,objects);
        this.mContext = context;
        this.mItems = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){

        //if the view is null than inflate it otherwise just fill the list with
        if(convertView == null){
            //inflate the layout
            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
            convertView = inflater.inflate(R.layout.movie_grid_item, parent, false);
        }
        ImageView image =(ImageView) convertView.findViewById(R.id.movie_image);
        Picasso.with(mContext).load(mItems.get(position)).into(image);
        return  convertView;
    }
}

public class FetchMovieData extends AsyncTask <String, Void, Void> {

    @Override
    protected Void 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;

        try {
            // Construct the URL for the OpenWeatherMap query
            // Possible parameters are available at OWM's forecast API page, at
            // http://openweathermap.org/API#forecast
            URL url = new URL(getString(R.string.picasso_url_popular_movies));

            // 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.
                mMovieJsonStr = 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.
                mMovieJsonStr = null;
            }
            mMovieJsonStr = buffer.toString();
        } catch (IOException e) {
            Log.e("PlaceholderFragment", "Error ", e);
            // If the code didn't successfully get the weather data, there's no point in attempting
            // to parse it.
            mMovieJsonStr = null;
        } finally{
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("PlaceholderFragment", "Error closing stream", e);
                }
            }
        }

        return null;
    }

}

}

最佳答案:

1 个答案:

答案 0 :(得分:1)

问题是你在你的onCreate方法和下面调用了AsyncTask,你正在填充你的gridView所以,AsyncTask需要时间从服务器通过互联网获取json,但是你没有给它时间。所以当你填充你的时候gridview,那时你没有图片网址,这就是毕加索无法加载图片的原因。

从onCreate

中删除以下行
if(mMovieJsonStr != null){
    mPosterMoviePaths =  MovieDataParser.getMoviePosterPaths(mMovieJsonStr);
}
mMoviesAdapter = new MovieAdapter(this, mPosterMoviePaths);
mMoviesGrid.setAdapter(mMoviesAdapter);

将它们写入AsyncTask中的onPostExecute

@Override
protected void onPostExecute(String result) {
   if(mMovieJsonStr != null){
    mPosterMoviePaths =  MovieDataParser.getMoviePosterPaths(mMovieJsonStr);
   }
   mMoviesAdapter = new MovieAdapter(Your_Activity_Name.this, mPosterMoviePaths);
   mMoviesGrid.setAdapter(mMoviesAdapter);
}

参考参考下面的链接

http://developer.android.com/reference/android/os/AsyncTask.html

public class FetchMovieData extends AsyncTask <String, Void, Void> {

@Override
protected Void 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;

    try {
        // Construct the URL for the OpenWeatherMap query
        // Possible parameters are available at OWM's forecast API page, at
        // http://openweathermap.org/API#forecast
        URL url = new URL(getString(R.string.picasso_url_popular_movies));

        // 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.
            mMovieJsonStr = 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.
            mMovieJsonStr = null;
        }
        mMovieJsonStr = buffer.toString();
    } catch (IOException e) {
        Log.e("PlaceholderFragment", "Error ", e);
        // If the code didn't successfully get the weather data, there's no point in attempting
        // to parse it.
        mMovieJsonStr = null;
    } finally{
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e("PlaceholderFragment", "Error closing stream", e);
            }
        }
    }

    return null;
  }
 ****Below is the onPostExecute method****

@Override
protected void onPostExecute(String result) {
   if(mMovieJsonStr != null){
    mPosterMoviePaths =  MovieDataParser.getMoviePosterPaths(mMovieJsonStr);
   }
   mMoviesAdapter = new MovieAdapter(Your_Activity_Name.this, mPosterMoviePaths);
   mMoviesGrid.setAdapter(mMoviesAdapter);
}

}

并使用Activity

扩展您的活动
public class MainActivity extends Activity {
}
本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复