Reputation: 4109
I am retrieving a String[]
of images from the web using an AsyncTask
which works fine.
The problem is that when I try to load the GridView Adapter
, the data has not arrived yet. So, the array
at that moment is null
. How can I ensure the String[]
will contain data at the moment I instantiate the GridView
?
Here is the 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();
}
});
}
Here is the Adapter
(Please, see the comment about the images)
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;
}
}
Thank you
Upvotes: 2
Views: 1264
Reputation: 7384
You can instantiate the adapter without any content..Just only instantiate the urls collection in the contructor, you don't have to add any content to it at the time of its creation. It just won't display anything until you will provide it..
Just add a method called for example addData()
which will take your loaded data as argument and which will add this data to the Collection in the adapter. You must then call the notifyDatasetChanged()
method of the adapter, which will tell it that it should requery the GridView with new content..
Upvotes: 3