Siggy
Siggy

Reputation: 752

Loading Images to Textview with AsyncTask

My problem is the following: I try to load images to a text view like this:

URLImageParser p = new URLImageParser(textView, this);     
Spanned htmlSpan = Html.fromHtml(textWithImages, p, null);
textView.setText(htmlSpan);

I followed this example https://stackoverflow.com/a/7442725/1835251

If I load images from the web it works perfectly.

I modified to code a bit to load certain images from SDCard as well.

In the "doInBackground" Method of the async task I implemented this:

@Override  
protected Drawable doInBackground(String... params) {  
    String source = params[0];  
    Drawable d = null  
    if(source != null) {  
      if(source.startsWith("/myApp/images/")) {  
          localImage = true;  
      }  
    }  
    if(localImage) {  
      String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();  
      d = Drawable.createFromPath(sdcard+source);  
      d.setBounds(0, 0, 0 + (int)(d.getIntrinsicWidth()), 0   
        + (int) (d.getIntrinsicHeight()));   
      localImage = false;  
    } else {  
      // load images from internet  
    }  
    return d;

localImage is a boolen which is set to determine if the current source "points" to an image from the internet or a local image.

As stated before: Loading images from the internet works perfectly.
BUT when I load images from the SDCard it sometimes happens that not all images are displayed.
The whole text (including the images) gets cut as if it hasn't been loaded correctly.
I figured out that this happens much more often on a Samsung Galaxy S3 than on a Samsung S Plus.
On the S3 I sometimes load only 1 or 1.5 images and the rest gets cut.
The S Plus always loads all 4 images but rarely cuts the last 2 or 3 sentences of the text.

I think that it is a sort of a timing problem with the AsyncTask but I never worked with it before.

I know this is a really large post but I hope that someone still can help me.

Best regards

Siggy

Upvotes: 1

Views: 1189

Answers (1)

Siggy
Siggy

Reputation: 752

Ok I am stupid... I solved it!

I forgot that I only need the AsyncTask if I load images from the internet. For local images I don't need that.

Solution for the interested:

ImageGetter imgGetter = new ImageGetter() {
  @Override
  public Drawable getDrawable(String source) {                      
    String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();
    Drawable d = Drawable.createFromPath(sdcard+source);                    
    d.setBounds(0, 0, 0 + (int)(d.getIntrinsicWidth()), 0 
      + (int) (d.getIntrinsicHeight())); 
    return d;
  }
};
Spanned htmlSpan = Html.fromHtml(textAndImage, imgGetter, null);
textView.setText(htmlSpan);

Upvotes: 1

Related Questions