【问题标题】:load image from url to imageview in a gridview using picasso使用毕加索将图像从url加载到gridview中的imageview
【发布时间】:2016-03-12 20:40:15
【问题描述】:

我正在尝试从服务器获取解析的图像 URL,然后将它们发送到适配器以使用 picasso 将它们加载到 imageviews

问题是图像有时会加载,但大多数时候它们不会加载,并且活动只是显示为空白。 请我需要帮助,我已经被困了将近 2 周了!

public class MainActivity extends AppCompatActivity {

ArrayList<movie> movies ;
movieAdapter adapter;
GridView gridview;
public static String API_Key = "b932ba435fc93a5944938fe9d44cd198";



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    gridview = (GridView) findViewById(R.id.gridView);

    movies = new ArrayList<>();
    new JsonAsyncTask().execute();

    adapter = new movieAdapter(MainActivity.this,R.layout.movie_item, movies);
    gridview.setAdapter(adapter);


}

class JsonAsyncTask extends AsyncTask<String , Void ,Boolean>{

    @Override
    protected Boolean doInBackground(String... params) {

        String baseUrl="http://image.tmdb.org/t/p/";
        String posterSize = "w185";
        HttpURLConnection urlConnection = null;

        try {
            URL url = new URL("http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key="+API_Key);
            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream in = urlConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
            StringBuilder sb = new StringBuilder();
            String line;

            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }

            String response = sb.toString();

            JSONObject jsono = new JSONObject(response);
            Log.v("Json", response);
            JSONArray jarray = jsono.getJSONArray("results");

            for (int i = 0; i < jarray.length(); i++) {
                JSONObject object = jarray.getJSONObject(i);

                String posterPath =object.getString("poster_path");
                Log.v("posterPath", posterPath);

                String complete_url = baseUrl + posterSize + posterPath ;

                movie m = new movie(complete_url);
                Log.v("complete url", m.getPoster());
                movies.add(m);
            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            urlConnection.disconnect();
        }

        return null;
    }
}
}


public class movie {
private String poster;

public movie(String poster) {
    super();
    this.poster=poster;
}



public String getPoster() {
    return poster;
}

public void setPoster(String poster) {
    this.poster = poster;
}
}

public class movieAdapter extends ArrayAdapter<movie> {
Context context;
int resource;
ArrayList<movie> movies = new ArrayList<movie>();

public movieAdapter(Context context,int resource ,  ArrayList<movie> objects) {
    super(context,  resource, objects);
    this.context=context;
    this.resource=resource;
    movies=objects;
}

public View getView(int position, View convertView, ViewGroup parent) {
    // convert convertview = design
    View convertview = convertView;
    ViewHolder holder;

    if (convertview == null)
    {
        LayoutInflater inflater = ((Activity)context).getLayoutInflater();
        convertview = inflater.inflate(resource, parent, false);

        holder = new ViewHolder();
        holder.imageview = (ImageView) convertview.findViewById(R.id.img);

        convertview.setTag(holder);
    }
    else {
        holder = (ViewHolder) convertView.getTag();
    }

    movie movie = movies.get(position);

    Picasso.with(context).load(movie.getPoster()).into(holder.imageview);

    return convertview;

}


static class ViewHolder  {
    public ImageView imageview;


}
}

这是我的主要活动布局(Content_main)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main" tools:context=".MainActivity">


    <GridView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/gridView"
        android:numColumns="2"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

这是我的电影项目布局

<?xml version="1.0" encoding="utf-8"?>

<ImageView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/img"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:scaleType="fitCenter"
    android:contentDescription="@string/app_name"
    />

【问题讨论】:

    标签: android gridview imageview adapter picasso


    【解决方案1】:

    问题是图像有时会加载,但大多数时候不会 被加载并且活动只是显示为空白

    这是由于ListView setAdapter 方法在JsonAsyncTask AsyncTask 执行完成之前被调用。

    doInBackground执行完成后,使用onPostExecutemovies对象传递给Adapter:

     @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
             // set Adapter here
            movies = new ArrayList<>();
            adapter = new movieAdapter(MainActivity.this,
                                    R.layout.movie_item, movies);
            gridview.setAdapter(adapter);
         }
    

    【讨论】:

    • Thnx 老兄,它的工作只是 arrayList 的初始化必须在 main 中,其余代码是正确的。你真的再次救了我的命^^
    猜你喜欢
    • 2017-05-09
    • 2020-05-19
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    相关资源
    最近更新 更多