Async ImageGetter not functioning properly
I was trying to download inline images from html asynchronously, following the information in this thread: Android HTML ImageGetter as AsyncTask
I could make the images download okay. BUT!
This is how it ends up:
This is how it is supposed to look and how it looks if I don't download them asynchronously:
Any ideas to how this can be fixed? Thank you in advance.
EDIT:
Code for my URLImageParser:
public URLImageParser( View t, Context c )
{
this.c = c;
this.container = t;
}
public Drawable getDrawable( String source )
{
URLDrawable urlDrawable = new URLDrawable();
ImageGetterAsyncTask asyncTask = new ImageGetterAsyncTask( urlDrawable );
asyncTask.execute( source );
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 )
{
urlDrawable.setBounds( 0, 0, 0 + result.getIntrinsicWidth(), 0
+ result.getIntrinsicHeight() );
urlDrawable.drawable = result;
URLImageParser.this.container.invalidate();
}
public Drawable fetchDrawable( String urlString )
{
try {
InputStream is = fetch( urlString );
Drawable dra开发者_JAVA百科wable = 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 Exception
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet( urlString );
HttpResponse response = httpClient.execute( request );
return response.getEntity().getContent();
}
}
And the code for URLDrawable
@Override
public void draw( Canvas canvas )
{
if( drawable != null )
{
drawable.draw( canvas );
}
}
I've found a workaround for this problem. You have to keep a reference to the TextView instance and after the image is being downloaded you have to call setText with the same text in your onPostExecute method:
@Override
protected void onPostExecute( Drawable result )
{
urlDrawable.setBounds( 0, 0, 0 + result.getIntrinsicWidth(), 0
+ result.getIntrinsicHeight() );
urlDrawable.drawable = result;
// mTextView is the reference to the TextView instance
mTextView.setText(mTextView.getText());
}
This forces the TextView to re-layout its content.
精彩评论