Android HTML ImageGetter as AsyncTask
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
ingetDrawable
method ofHtml.ImageGetter
- Once
onPostExecute
is called, I redraw the container of theSpanned
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);
Asynchronous Html.ImageGetter for setting multiple images in a TextView
Doing this synchronously is trivial, but is there a suggested way to do this asynchronously so that it doesn't lock up my UI thread?
That will be difficult, perhaps impossible. You have to return something immediately. Even if that is a placeholder, you then have the challenge of how to replace the placeholder once the download is complete. Since you lack access to the ImageView
rendering the image (if there is an ImageView
), I don't know how you would arrange to replace the placeholder.
Display images on Android using TextView and Html.ImageGetter asynchronously?
Now I'm using an AsyncTask to download the images in the ImageGetter
:
Spanned spannedContent = Html.fromHtml(htmlString, new ImageGetter() {
@Override
public Drawable getDrawable(String source) {
new ImageDownloadAsyncTask().execute(textView, htmlString, source);
return null;
}
}, null);
And set the text again into the TextView
when the image has been downloaded.
Now it works. But It failed when I tried to do the TextView.postInvalidate()
to redraw the downloaded images. I have to do setText()
again in the AsyncTask
.
Does anyone know why?
Loading Images to Textview with AsyncTask
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);
AsyncTask ImageGetter
in your onCreate, you need to set the set to "loading.." or something, and start the task:
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.myUrl.com" });
And then:
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
//Download your pictures and prepare the text
return response;
}
@Override
protected void onPostExecute(String result) {
textView.setText(result);
//Better:
ImageView.setbackground(....)
}
}
}
Extra note
I would personally use an ImageView for the picture! textView is not optimal for what you need and will not scale easily.
How to load images from html in the AsyncTask
This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask
public class MainActivity extends Activity implements ImageGetter {
private final static String TAG = "MainActivity";
private TextView mTv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String source = <your source from json here>;
Spanned spanned = Html.fromHtml(source, this, null);
mTv = (TextView) findViewById(R.id.text);
mTv.setText(spanned);
}
@Override
public Drawable getDrawable(String source) {
LevelListDrawable d = new LevelListDrawable();
Drawable empty = getResources().getDrawable(R.drawable.ic_launcher);
d.addLevel(0, 0, empty);
d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());
new LoadImage().execute(source, d);
return d;
}
class LoadImage extends AsyncTask<Object, Void, Bitmap> {
private LevelListDrawable mDrawable;
@Override
protected Bitmap doInBackground(Object... params) {
String source = (String) params[0];
mDrawable = (LevelListDrawable) params[1];
Log.d(TAG, "doInBackground " + source);
try {
InputStream is = new URL(source).openStream();
return BitmapFactory.decodeStream(is);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
Log.d(TAG, "onPostExecute drawable " + mDrawable);
Log.d(TAG, "onPostExecute bitmap " + bitmap);
if (bitmap != null) {
BitmapDrawable d = new BitmapDrawable(bitmap);
mDrawable.addLevel(1, 1, d);
mDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
mDrawable.setLevel(1);
// i don't know yet a better way to refresh TextView
// mTv.invalidate() doesn't work as expected
CharSequence t = mTv.getText();
mTv.setText(t);
}
}
}
}
Related Topics
Intercept Back Button from Soft Keyboard
Googleservice Failed to Initialize
Failed to Resolve: Com.Google.Firebase:Firebase-Core:9.0.0
Date and Time Change Listener in Android
Couldn't Load Memtrack Module Logcat Error
Tabwidget Current Tab Bottom Line Color
Google Map Signed API Key Errors in Android
An Established Connection Was Aborted by the Software in Your Host MAChine
Bad Class File Magic or Version
Importing Google-Play-Service Library Showing a Red X Next to This Reference Android
Error:Execution Failed for Task ':Android:Transformclassesandresourceswithproguardforrelease'
How to Monitor the Network Connection Status in Android
Upload Large File in Android Without Outofmemory Error
Android: How Does Bitmap Recycle() Work
No Resource Found - Theme.Appcompat.Light.Darkactionbar
Could Not Find Com.Android.Tools.Build:Gradle:3.0.0-Alpha1 in Circle Ci