如何将异步数据加载到GridView中?

时间:2014-02-11 22:01:53

标签: android gridview android-asynctask

我正在使用String[]从网上检索AsyncTask张图片,效果很好。

问题在于,当我尝试加载GridView Adapter时,数据尚未到达。那么,那时的arraynull。在实例化String[]时,如何确保GridView将包含数据?

以下是onCreate()

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

     Bundle extras = getIntent().getExtras();
     if (extras != null) {
         query = extras.getString("query");
     }

     new AsyncDownload().execute();

    GridView gv = (GridView) findViewById(R.id.grid_view);
    gv.setAdapter(new SampleGridViewAdapter(this));
    gv.setOnItemClickListener(new AdapterView.OnItemClickListener(){

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(getApplicationContext(), "You have touched picture number " + String.valueOf(position) , Toast.LENGTH_SHORT).show();

    }

    });
}

以下是Adapter(请参阅有关图片的评论)

final class SampleGridViewAdapter extends BaseAdapter {
  private final Context context;
  private final List<String> urls = new ArrayList<String>();

  public SampleGridViewAdapter(Context context) {
    this.context = context;
//In this line is where I call the images retrieved by the AsyncTask. 
//After finishing and opening the activity again, the images will be there, and will load correctly.
    Collections.addAll(urls, SampleGridViewActivity.returnImages());
    Collections.shuffle(urls);

  }

  @Override public View getView(int position, View convertView, ViewGroup parent) {
    SquaredImageView view = (SquaredImageView) convertView;
    if (view == null) {
      view = new SquaredImageView(context);
      view.setScaleType(CENTER_CROP);
    }

    // Get the image URL for the current position.
    String url = getItem(position);

    // Trigger the download of the URL asynchronously into the image view.
    Picasso.with(context) //
        .load(url) //
        .placeholder(R.drawable.placeholder) //
        .error(R.drawable.error) //
        .fit() //
        .into(view);

    return view;
  }

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

  @Override public String getItem(int position) {
    return urls.get(position);
  }

  @Override public long getItemId(int position) {
    return position;
  }

}

谢谢

1 个答案:

答案 0 :(得分:2)

您可以在没有任何内容的情况下实例化适配器。只需在构造函数中实例化urls集合,您不必在创建时添加任何内容。在你提供它之前它不会显示任何东西.. 只需添加一个名为addData()的方法,它将加载的数据作为参数,并将此数据添加到适配器中的Collection。然后,您必须调用适配器的notifyDatasetChanged()方法,这将告诉它应该使用新内容重新查询GridView ..