Load multiple Url images without using third party libraries in Recyclerview - android

Hi all I'm new to Android, I'm facing difficulty in loading Multiple images through URL into a Recycler view, My task is not to use any third Party Libraries and also not to add in string array in xml file. Is it Possible to loop an URL? for example "http://onethousandpaintings.com/imgs/numbers/number_1.png", if the number is change the image correspondingly changes.try it yourself once! I'm thinking an way to increment that number in a "For Loop" but could not figure it out. Kindly provide me an solution for it.

#sample AsycTask Code, you can pass the url to this class by execute method.
public class ShowImage extends AsyncTask<String,Void,Bitmap>{
private WeakReference<ImageView> imageview;
public ShowImage(ImageView imv){
imageview=new WeakReference<ImageView>(imv);
}
/** Background process
* input:url
* output: Bitmap image
* It passed into onPostExecute method
**/
#Override
protected Bitmap doInBackground(String... urls) {
return getBitMapFromUrl(urls[0]);
}
/** This method called after the doINputBackground method
* input:Bitmap image
* output: image set into the image view
* Image view passed from RecyclerViewOperation to ShowImage class through constructor
**/
#Override
protected void onPostExecute(Bitmap result) {
if((imageview!=null)&&(result!=null)){
ImageView imgview=imageview.get();
if(imgview!=null){
imgview.setImageBitmap(result);
}
}
}
/** This method called by doInBackground method
* input:url
* output: Bitmap image
*
**/
private Bitmap getBitMapFromUrl( String imageuri){
HttpURLConnection connection=null;
try {
URL url=new URL(imageuri);
// Log.d("bucky","bitmap" + imageuri);
connection= (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream is=connection.getInputStream();
Bitmap mybitmap=BitmapFactory.decodeStream(is);
return mybitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
finally {
if(connection!=null) {
connection.disconnect();
}
}
}
}

You can use AsynTask so it will load multiple Images from the Url, which provides the functionality to work in Background. So Your main thread does not gets affected and the Images downloads in the backgreound continously. I hope this answer your Question.

Related

why my animations are not proper and image loading is taking more time in some of the images?

public class LoadImageActivity extends Activity {
ImageView image_view;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
image_view = (ImageView)findViewById(R.id.imageview);
me m1=new me();
m1.execute("http://wallbase1.org/thumbs/rozne/thumb-499842.jpg");
me m2=new me();
m2.execute( "http://wallbase1.org/thumbs/rozne/thumb-637449.jpg");
me m3=new me();
m3.execute( "http://wallbase1.org/thumbs/rozne/thumb-2509834.jpg");
me m4=new me();
m4.execute( "http://wallbase1.org/thumbs/rozne/thumb-2501884.jpg");
me m5=new me();
m5.execute( "http://wallbase1.org/thumbs/rozne/thumb-2514440.jpg");
};
class me extends AsyncTask<String, Integer, Bitmap> {
Bitmap b1;
// private MainActivity m1;
protected Bitmap doInBackground(String...params) {
// TODO Auto-generated method stub
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL(params[0]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
b1=bm;
bis.close();
is.close();
} catch (IOException e)
{
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
image_view.setImageBitmap(b1);
Animation rotation = AnimationUtils.loadAnimation(LoadImageActivity.this, R.anim.rotate);
image_view.startAnimation(rotation);
}
}}
I am trying to show an image from internet by decoding it into bitmap,i want to show multiple images from multiple urls.Is there any better way of implementing it?
The duration of a download depends on a lot of different stuff. You currently spawn 5 AsyncTasks and there is no guarantee that the order of delivery/execution will be the same order you spawned them. It is easily possible that the fifth image might be the first you received and this would result in a totally wrong order. So you should download all images first, possibly with just one AsyncTask. After that and if that succeeded, you should start the animation and switch between the images.
There're several better ways of doing it and all of them are far more complex than your code. But you do have a good start.
This video form Google I/O have some good techniques for image, check around 4:40 https://www.youtube.com/watch?v=gbQb1PVjfqM
It takes different times because they are different images with probably different sizes.
Please post your XML R.anim.rotate code so someone can try to check why the animation is not working.

Download images with AsyncTask

I'm not really sure what goes wrong with my code or structure. I wanted to use AsyncTask to download images and display out the progress bar at the mean time. But I tried out a few different way of doing it. It still failed and no idea what's wrong with it. My structure flow is
ContentID is a string array that stores the content ID of the Images.
Primary Issue: It managed to download images from the url and store into the phone, but the downloaded images are all the same image. It should be different images, it's not what I expected.
Secondary Issue: The progress bar pop up while the application downloading images, but the progress bar did not update it's progress. It just remains 0% and dismissed after the download completed.
I wanted to know what causes primary and secodary issue as i mentioned. Please leave a comment or answer if you might know what's wrong with my code. Any help will be appreciated.
if(isSyncSuccess){
SetConstant.IMAGE_EXIST = 1;
pDialog = new ProgressDialog(GalleryScreen.this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setProgress(0);
pDialog.setMax(contentId.length);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
if (contentId.length>0){
Log.i(TAG, "contentid.length:" +contentId.length);
for (int i=0;i<contentId.length;i++){
if(helper.databaseChecking(useremail, contentId[i])){
contentdownload = i;
SetConstant.CONTENT_ID = contentId[i];
String URL = SetConstant.URL_DOWNLOAD_CONTENT+contentId[i];
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute(URL);
}
private class DownloadFile extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... sUrl){
Bitmap bm;
InputStream in;
try{
in = new java.net.URL(sUrl[0]).openStream();
bm = BitmapFactory.decodeStream(new PatchInputStream(in));
File storage = new File(Environment.getExternalStorageDirectory() + File.separator + "/Image/");
Log.i(TAG,"storage:" +storage);
Log.i(TAG,"storage:" +storage.getAbsolutePath());
if(!storage.exists()){
storage.mkdirs();
}
String FileName = "/"+SetConstant.CONTENT_ID+".jpg";
FileOutputStream fos = new FileOutputStream(storage + FileName);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fos);
String filepath = storage + FileName;
File filecheck = new File (filepath);
long fileSize = filecheck.length();
fos.flush();
fos.close();
Log.i(TAG, "bm:" +bm);
Log.i(TAG, "fos:" +fos);
Log.i(TAG, "filesize:" +fileSize);
Log.i(TAG, "filepath:" +filepath);
}
catch(IOException e1){
e1.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress){
super.onProgressUpdate(progress);
pDialog.setProgress(progress[0]);
}
protected void onPostExecute(String result){
super.onPostExecute(result);
pDialog.dismiss();
}
}
Edit
Now the application able to download images according and the progress bar is working as well! But I got another issue is how to return error message when the application failed to complete the download. Currently when the application failed to download it will crash. I believed that I should not run it inside the doInBackground side. But where else can I do the checking? Any idea how to return as an error message and request for the user to retry instead of crashing the application?
You never called onProgressUpdate during your doInBackGround(...). Please note that running multiple instances of AsyncTask is a bad idea. Here is what I suggest:
if(isSyncSuccess){
SetConstant.IMAGE_EXIST=1;
pDialog=new ProgressDialog(GalleryScreen.this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setProgress(0);
pDialog.setMax(contentId.length);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
new DownloadFile().execute();
}
private class DownloadFiles extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
Bitmap bm;
InputStream in;
if (contentId.length > 0) {
for (int i = 0; i < contentId.length; i++) {
if (helper.databaseChecking(useremail, contentId[i])) {
contentdownload = i;
SetConstant.CONTENT_ID = contentId[i];
String URL = SetConstant.URL_DOWNLOAD_CONTENT + contentId[i];
//YOUR INTRESTING LOOP HERE.
publishProgress(30);
//SOME INTRESTING NUMBER FOR PROGRESS UPDATE
}
}
try {
in = new java.net.URL(sUrl[0]).openStream();
bm = BitmapFactory.decodeStream(new PatchInputStream(in));
File storage = new File(Environment.getExternalStorageDirectory() + File.separator + "/Image/");
Log.i(TAG, "storage:" + storage);
Log.i(TAG, "storage:" + storage.getAbsolutePath());
if (!storage.exists()) {
storage.mkdirs();
}
String FileName = "/" + SetConstant.CONTENT_ID + ".jpg";
FileOutputStream fos = new FileOutputStream(storage + FileName);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fos);
String filepath = storage + FileName;
File filecheck = new File(filepath);
long fileSize = filecheck.length();
fos.flush();
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute () {
super.onPreExecute();
pDialog.show();
}
#Override
protected void onProgressUpdate (Integer...progress){
super.onProgressUpdate(progress);
pDialog.setProgress(progress[0]);
}
protected void onPostExecute (String result){
super.onPostExecute(result);
pDialog.dismiss();
}
}
}
Of course this code don't run and you need to fix the scopes. But what I am trying to suggest is that your loop should be in doInBackGround(...), you should only have 1 instance of AsyncTask at given time for this case, and call the onProgressUpdate().
Primary issue :
SetConstant.CONTENT_ID = contentId[i];
String URL = SetConstant.URL_DOWNLOAD_CONTENT+contentId[i];
Here, you are facing trouble. As #Sofi Software LLC's answer, you are using a global variable, whose value is being changed by the main thread, in another thread.
Secondary Issue :
If you want a progress bar to update, you have to update its value;
it doesn't update itself.
You do need to download the image in AsyncTask (Downloading from URL). Effectively to achieve your functionality, you need to do
Create AsyncTask to download your image (implement download in
doInBackground()), also have a boolean (say isImageDownloaded) to
track if the image is successfully downloaded in postExecute().
Don't forget to also show your progress bar before initiating the
download
Execute your AsyncTask to initiate download
Create extension of android.os.CountDownTimer to countdown a minimum
time
On the method onFinish() check the boolean that you track, if it is
false then you cancel the AsyncTask and throw the toast/dialog that
you intended
Running multipule instance of AsyncTask is not a good idea, so do one after another. You can execute your AsyncTask's on an Executor using executeOnExecutor().To make sure that the threads are running in a serial fashion please use: SERIAL_EXECUTOR.
Following resources may help you #
If you need to download an image, show progress bar and load in a imageview
https://github.com/koush/UrlImageViewHelper
http://developer.aiwgame.com/imageview-show-image-from-url-on-android-4-0.html
http://blog.blundell-apps.com/imageview-with-loading-spinner/
If you need to download multiple files (here, for images) using AsyncTask
Problem with downloading multiple files using AsyncTask
How to get back the task completion status in AsyncTask
Implement Progress Bar for File Download in Android
EDIT:
From http://developer.aiwgame.com/imageview-show-image-from-url-on-android-4-0.html
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png"); }
public void onClick(View v) {
startActivity(new Intent(this, IndexActivity.class));
finish();
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
} }
From Image download in an Android ImageView and Progressbar implementation
// note that you could also use other timer related class in Android aside from this CountDownTimer, I prefer this class because I could do something on every interval basis
// tick every 10 secs (or what you think is necessary)
CountDownTimer timer = new CountDownTimer(30000, 10000) {
#Override
public void onFinish() {
// check the boolean, if it is false, throw toast/dialog
}
#Override
public void onTick(long millisUntilFinished) {
// you could alternatively update anything you want every tick of the interval that you specified
}
};
timer.start()
In the following line:
SetConstant.CONTENT_ID = contentId[i];
You're setting a global variable to a value, then you create a string url based on that same value and pass it to the AsyncTask. That executes, and then when it is done downloading, it create a file whose name is based on the global variable SetConstant.CONTENT_ID.
In other words, you are using a global variable, whose value is being changed by the main thread, in another thread. Don't do this, as you will get all kinds of weird problems due to the different threads updating at different times.. Pass in the value or the name of the output file to the AsyncTask. You can do that in a constructor for DownloadFile, and stash the value in a field.
If you want a progress bar to update, you have to update its value; it doesn't update itself. Call AsyncTask.publishProgress during the task (in doInBackground) and implement onProgressUpdate to update the progress dialog.
[EDIT: onProgressUpdate is indeed called in the UI thread.]
First create a separated class which allows you to reach to image address
like following:
public class ImageDownloader extends AsyncTask {
#Override
protected Bitmap doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Then get access to that class (through a method called by a button) by creating an object and execute the Bitmap task like following :
public class MainActivity extends Activity {
ImageView downloadedImg;
public void downloadImage(View view) {
ImageDownloader task = new ImageDownloader();
Bitmap myImage;
try {
myImage = task.execute("YOUR IMAGE ADDRESS ........").get();
downloadedImg.setImageBitmap(myImage);
} catch (Exception e) {
e.printStackTrace();
}
}
Do NOT forget to:
1 - define the imageView in onCreat method ==> downloadedImg = (ImageView) findViewById(R.id.imageView);
2 - to link the method you've created by a button in user interface ==> (public void downloadImage(View view){})
3 - ask for permission in manifest file

Android HTML ImageGetter as AsyncTask

Okay, I'm losing my mind over this one. I have a method in my program which parses HTML. I want to include the inline images, and I am under the impression that using the Html.fromHtml(string, Html.ImageGetter, Html.TagHandler) will allow this to happen.
Since Html.ImageGetter doesn't have an implementation, it's up to me to write one. However, since parsing URLs into Drawables requires network access, I can't do this on the main thread, so it must be an AsyncTask. I think.
However, when you pass the ImageGetter as a parameter to Html.fromHtml, it uses the getDrawable method that must be overridden. So there's no way to call the whole ImageGetter.execute deal that triggers the doInBackground method, and so there's no way to actually make this asynchronous.
Am I going about it completely wrong, or worse, is this impossible? Thanks
I've done something very similar (I think) to what you want to do. What I needed to do back then is parse the HTML and set it up back to TextView and I needed to use Html.ImageGetter as well and having the same problem on fetching image on the main thread.
The steps that I did basically:
Create my own subclass for Drawable to facilitate redraw, I called it URLDrawable
Return the URLDrawable in getDrawable method of Html.ImageGetter
Once onPostExecute is called, I redraw the container of the Spanned result
Now the code for URLDrawable is as follow
public class URLDrawable extends BitmapDrawable {
// the drawable that you need to set, you could set the initial drawing
// with the loading image if you need to
protected Drawable drawable;
#Override
public void draw(Canvas canvas) {
// override the draw to facilitate refresh function later
if(drawable != null) {
drawable.draw(canvas);
}
}
}
Simple enough, I just override draw so it would pick the Drawable that I set over there after AsyncTask finishes.
The following class is the implementation of Html.ImageGetter and the one that fetches the image from AsyncTask and update the image
public class URLImageParser implements ImageGetter {
Context c;
View container;
/***
* Construct the URLImageParser which will execute AsyncTask and refresh the container
* #param t
* #param c
*/
public URLImageParser(View t, Context c) {
this.c = c;
this.container = t;
}
public Drawable getDrawable(String source) {
URLDrawable urlDrawable = new URLDrawable();
// get the actual source
ImageGetterAsyncTask asyncTask =
new ImageGetterAsyncTask( urlDrawable);
asyncTask.execute(source);
// return reference to URLDrawable where I will change with actual image from
// the src tag
return urlDrawable;
}
public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
URLDrawable urlDrawable;
public ImageGetterAsyncTask(URLDrawable d) {
this.urlDrawable = d;
}
#Override
protected Drawable doInBackground(String... params) {
String source = params[0];
return fetchDrawable(source);
}
#Override
protected void onPostExecute(Drawable result) {
// set the correct bound according to the result from HTTP call
urlDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(), 0
+ result.getIntrinsicHeight());
// change the reference of the current drawable to the result
// from the HTTP call
urlDrawable.drawable = result;
// redraw the image by invalidating the container
URLImageParser.this.container.invalidate();
}
/***
* Get the Drawable from URL
* #param urlString
* #return
*/
public Drawable fetchDrawable(String urlString) {
try {
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0
+ drawable.getIntrinsicHeight());
return drawable;
} catch (Exception e) {
return null;
}
}
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();
}
}
}
Finally, below is the sample program to demonstrate how things work:
String html = "Hello " +
"<img src='http://www.gravatar.com/avatar/" +
"f9dd8b16d54f483f22c0b7a7e3d840f9?s=32&d=identicon&r=PG'/>" +
" This is a test " +
"<img src='http://www.gravatar.com/avatar/a9317e7f0a78bb10a980cadd9dd035c9?s=32&d=identicon&r=PG'/>";
this.textView = (TextView)this.findViewById(R.id.textview);
URLImageParser p = new URLImageParser(textView, this);
Spanned htmlSpan = Html.fromHtml(html, p, null);
textView.setText(htmlSpan);
Pretty nice. However, The type DefaultHttpClient is deprecated. Try this on fetch method:
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = urlConnection.getInputStream();
return stream;
}
I got a bit confused, is the HTML you want to render static and merely for formatting, or is it dynamic and coming from the web? If you wanted the latter, that is, to render the HTML and retrieve the images, well it's gonna be a bit of a pain (suggestion - just use a WebView?).
Anyway, you would first have to run the AsyncTask to retrieve the initial HTML. You would then pass those results into the Html.fromHtml() with the custom implementation for the Html.ImageGetter class. Then in that implementation you'd have to kick off an individual AsyncTask to retrieve each of the images (you probably want to implement some caching).
However, from reading the documentation (and I think I've seen some samples), it would seem to me that this is not what they meant the Html.ImageGetter for. I think it's meant for hardcoded HTML with references to internal drawables, but that's just my take.
if you using Picasso, change part of #momo code to
/***
* Get the Drawable from URL
* #param urlString
* #return
*/
public Drawable fetchDrawable(String urlString) {
try {
Drawable drawable = fetch(urlString);
drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0
+ drawable.getIntrinsicHeight());
return drawable;
} catch (Exception e) {
return null;
}
}
private Drawable fetch(String urlString) throws MalformedURLException, IOException {
return new BitmapDrawable(c.getResources(), Picasso.with(c).load(urlString).get());
}
AsyncTask task = new AsyncTask (){
#Override
protected String doInBackground(Integer... params) {
span = Html.fromHtml(noticeList.get(0)
.getContent(), imgGetter, null);
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
text.setMovementMethod(ScrollingMovementMethod
.getInstance());
if(span != null){
text.setText(span);
}
}
};
task.execute();

Uploading fresh images to application?

What would be the best way to show different images to applications in android?
For example...
I have a gallery that shows different images. i would like to change these images weekly. Right now i am using this...
public class ImageAdapter extends BaseAdapter {
/** The parent context */
private Context myContext;
/** URL-Strings to some remote images. */
private String[] myRemoteImages = {
"https://sites.google.com/site/theitrangers/images/modern_warfare_3_21027.jpg"
""
};
/** Simple Constructor saving the 'parent' context. */
public ImageAdapter(Context c) { this.myContext = c; }
/** Returns the amount of images we have defined. */
public int getCount() { return this.myRemoteImages.length; }
/* Use the array-Positions as unique IDs */
public Object getItem(int position) { return position; }
public long getItemId(int position) { return position; }
/ ** Returns a new ImageView to
* be displayed, depending on
* the position passed. */
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(this.myContext);
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL(myRemoteImages[position]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
/* Apply the Bitmap to the ImageView that will be returned. */
i.setImageBitmap(bm);
} catch (IOException e) {
Log.e("DEBUGTAG", "Remtoe Image Exception", e);
}
/* Image should be scaled as width/height are set. */
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
/ * Set the Width/Height of the ImageView. */
i.setLayoutParams(new Gallery.LayoutParams(150, 150));
return i;
}
public float getScale(boolean focused, int offset) {
/* Formula: 1 / (2 ^ offset) */
return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
}
}
}
So here in this example i am using a URL to get the image from. The only problem is i would have upgrade the application each time i wanted to use a new image.Correct? What would be the best way for me to accomplish this?
What I would do is have a server-side script sitting on a web server which would tell your app what images to show.
Every time you load the program you can query (HTTP GET) this script (you can use PHP, or any other CGI) which will return you the latest images. You could return the whole image directly, or just the URL for the application to load into it's image frame.
very simple answer: You could instead point the link to a static URL on a server you control (a free tier ec2 server would be perfect for this), and when you want to change the image, you can just overwrite the file the URL points to.
Also hotlinking is frowned upon because someone else is paying for your apps bandwidth usage

ListView scrolling lag in android

I am having a customized list view in my application, which is showing an image and text.
The Image I am getting from URL, using the code below:
private static Drawable ImageOperations(Context ctx, String url,
String saveFilename) {
try {
InputStream is = (InputStream) fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static Object fetch(String address) throws MalformedURLException,
IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
all is working perfect, except the list view scrolling, its very slow. If I disable the images, the scroll speed smooth-ens , but with the image enabled, it lags alot.
Is there any possible way I can reduce or remove this lagging?
Thanks
You need to do your fetching in the background.
One of the examples you can use :
http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html
use this library for downloading images in background and caching..
it won't hurt the UI
https://github.com/koush/UrlImageViewHelper
Are you lazy loading your images? See this question for details.

Categories

Resources