I want to implement a lazy loading image in my ListView. At first I need to connect to a url and get the urlStrings for all images which belong to an object. I get a jsonString and then parse:
String RESTUrl = new MasterdataDataProvider(mContext).getSyncServicePath() + "PhotoInfo/" + objectEntryID;
List<String> urlStrings = new ArrayList<String>();
try {
HttpGet httpGet = new HttpGet((RESTUrl + "/" + token));
HttpParams httpParameters = new BasicHttpParams();
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
httpGet.addHeader("Accept", "application/json");
httpGet.addHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpGet);
String jsonData = EntityUtils.toString(response.getEntity());
if (!jsonData.equals("[]")) {
GsonPhotoInfo x = new GsonPhotoInfo(new GsonBuilder());
PhotoInfo[] info = x.parseJSON(jsonData);
for(PhotoInfo p : info) {
System.out.println(p.getFileName());
urlStrings.add(photoWebURL + objectDefID + "/" + objectEntryID + "/" + p.getFileName());
}
}
} catch(Exception e) {
e.printStackTrace();
}
As you see in this piece of code I fetch the FileName from jsonData
.
Then I need to download the images from urlStrings:
final Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
ImagePagerAdapter adapter = new ImagePagerAdapter((Drawable[]) message.obj);
viewPager.setAdapter(adapter);
}
};
Thread thread = new Thread() {
@Override
public void run() {
//PARSE THE JSON DATA and FETCH URLStrings (as you see in the piece of code at top)
Drawable[] drawables = new Drawable[urlStrings.size()];
for(int i=0; i< urlStrings.size(); i++)
drawables[i] = fetchDrawable(urlStrings.get(i));
Message message = handler.obtainMessage(1, drawables);
handler.sendMessage(message);
}
};
thread.start();
The code to fetch image is taken from James Wilson answer.
So as you can see there as well, I have to use HTTPClient once again to download every image:
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
The problem is it is not working in my listView. The images are not loaded correctly in listView sometimes
, and I am just wondering that is it because of the way that :
- I get the urlStrings from jsonData, and then
- Download the images from urlStrings one by one.
I mean I connect to REST two times. I am also using a Handler
that maybe is not a good option, but actually I tested it with a AsyncTask
and I had the same problem.
I appreciate for any idea that could solve my problem.
Addenda:
I found out images are loaded incorrectly when I scroll in the list very fast, otherwise it is fine.