I'm trying to retrieve some pictures from server in order to populate a GridView with the results. To do so I have a custom adapter in which one I would like to download the picture and set it as Bitmap of a ImageButton widget. I'm using ImageRequest from Volley library and also need Basic Authentication with it, which is the point that I cannot figure out how to do. This is the code of the custom adapter :
public View getView(int position, View convertView, ViewGroup parent) {
final boolean loaded = false;
currentMarque = getItem(position);
String url = "https://uriToServer";
currentMarque.setImageUrl(url + currentMarque.getId());
if (convertView == null)
convertView = LayoutInflater.from(getContext()).inflate(R.layout.brand_gridcell_layout, parent, false);
currentImageBtn = (ImageButton) convertView.findViewById(R.id.brandImageBtn);
ImageRequest request = new ImageRequest(currentMarque.getImageUrl(),
new Response.Listener<Bitmap>()
{
@Override
public void onResponse(Bitmap bitmap)
{
currentImageBtn.setImageBitmap(bitmap);
}
}, 0, 0, null,
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError arg0)
{
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
String auth = "Basic " + Base64.encodeToString((GlobalVariables.getInstance().getWS_KEY()+":").getBytes(),
Base64.NO_WRAP);
headers.put("Authorization", auth);
return headers;
}
};
GlobalVariables.getInstance().addToRequestQueue(request);
return convertView;
}
The problem is that an ImageRequest is an asynchronous request, we don't know when will we get the response so the ConvertView is returning before the call ends. Is there a way to wait till the request finishes ?