使用毕加索将图像从url加载到gridview中的imageview

时间:2015-12-08 02:59:47

标签: android gridview imageview adapter picasso

我尝试从服务器获取解析后的图片网址,然后将其发送到适配器,使用imageviewspicasso中加载它们。

问题是图像有时会加载,但大部分时间它们都没有加载,活动只显示为空白。 我需要帮助,我已经坚持了将近两个星期!

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>

这是我的movie_item布局

<?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"
    />

1 个答案:

答案 0 :(得分:0)

  

问题是图像有时会加载,但大多数情况下它们没有加载   加载,活动只显示空白

这是因为在ListView AsyncTask执行完成之前调用了setAdapter JsonAsyncTask方法。

onPostExecute执行完成后,使用moviesdoInBackground对象传递给适配器:

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