This example describes the Android implementation textview display HTML plus pictures. Share to everyone for your reference, specific as follows:
TextView Display Network pictures, I use the android2.3 system, can display the picture out, and if the picture is bigger, the application will card phenomenon, certainly is because uses the main thread to obtain the network picture to cause, but if I use android4.0 above system to run, cannot display the picture, only displays the small box.
The reason is that in 4.0 of the system on the implementation of the error, the exception is: Android.os.NetworkOnMainThreadException after the document, the original is 4.0 system does not allow the main thread (UI thread) access to the network, resulting in its exception. To put it bluntly is to access the network on the main thread, which will cause the main thread to hang, the system is not allowed to use.
There are partial modifications here and the code is independent. The picture implementation is loaded asynchronously. Solve the above problems
Usage, calling code activity
TextView control
textviewcontent = (TextView) getactivity (). Findviewbyid (R.id.textview_prodcut_detail_more_zp_ content);
HTML text
zp_content = "Test picture information: <br>
Htmlimagegetter class:
Import Java.io.InputStream;
Import Android.graphics.Canvas;
Import android.graphics.drawable.BitmapDrawable;
Import android.graphics.drawable.Drawable;
Import Android.os.AsyncTask;
Import android.os.Environment;
Import Android.text.Html.ImageGetter;
Import Android.util.Log;
Import Android.widget.TextView;
public class Htmlimagegetter implements imagegetter{private TextView _htmltext;
Private String _imgpath;
Private drawable _defaultdrawable;
Private String TAG = "Htmlimagegetter";
Public Htmlimagegetter (TextView htmltext, String Imgpath, drawable defaultdrawable) {_htmltext = HTMLText;
_imgpath = Imgpath;
_defaultdrawable = defaultdrawable;
@Override Public drawable getdrawable (string imgurl) {string imgkey = String.valueof (Imgurl.hashcode ());
String path = environment.getexternalstoragedirectory () + _imgpath;
Fileutil.createpath (path);
string[] ss = Imgurl.split ("\ n.");
String IMGX = ss[ss.length-1]; Imgkey = path+ "/" + imgkey+"."
+IMGX;
if (fileutil.exists (Imgkey)) {drawable drawable = fileutil.getimagedrawable (Imgkey);
if (drawable!= null) {drawable.setbounds (0, 0, drawable.getintrinsicwidth (), Drawable.getintrinsicheight ());
return drawable;
}else{log.v (TAG, "load img:" +imgkey+ ": null");
} urldrawable urldrawable = new urldrawable (_defaultdrawable);
New Asyncthread (urldrawable). Execute (Imgkey, imgurl);
return urldrawable;
Private class Asyncthread extends Asynctask<string, Integer, drawable> {private String imgkey;
Private Urldrawable _drawable;
Public Asyncthread (Urldrawable drawable) {_drawable = drawable;
} @Override protected drawable doinbackground (String ... strings) {imgkey = strings[0];
InputStream INPs = Network.getinputstream (strings[1]);
if (INPs = null) return _drawable;
Fileutil.savefile (Imgkey, INPS);
drawable drawable = Drawable.createfrompath (Imgkey); return drawable; The public void Onprogressupdate (Integer ... value) {} @Override protected void OnPostExecute (drawable resul
T) {_drawable.setdrawable (result);
_htmltext.settext (_htmltext.gettext ());
} public class Urldrawable extends bitmapdrawable {private drawable drawable;
Public urldrawable (drawable defaultdraw) {setdrawable (Defaultdraw);
} private void Setdrawable (drawable ndrawable) {drawable = ndrawable;
Drawable.setbounds (0, 0, drawable.getintrinsicwidth (), drawable. Getintrinsicheight ());
SetBounds (0, 0, drawable.getintrinsicwidth (), drawable. Getintrinsicheight ());
@Override public void Draw (Canvas Canvas) {Drawable.draw (Canvas);
}
}
}
Network class:
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import java.net.HttpURLConnection;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import Java.util.Map;
Import Java.util.zip.GZIPInputStream;
Import Java.util.zip.InflaterInputStream;
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.methods.HttpGet;
Import org.apache.http.entity.BufferedHttpEntity;
Import org.apache.http.impl.client.DefaultHttpClient;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.util.Log;
public class Network {private static String TAG = "Network";
public static string Gethttpdata (String baseurl) {return gethttpdata (BaseURL, ' Get ', ' ", null);
public static string Posthttpdata (string BaseURL, String reqdata) { Return Gethttpdata (BaseURL, "POST", reqdata, NULL); public static string Posthttpdata (string BaseURL, String reqdata, hashmap<string, string> propertys) {return
Gethttpdata (BaseURL, "POST", Reqdata, Propertys); /** * Get Event Info * @return/public static string Gethttpdata (string BaseURL, String method, String reqdata, H
Ashmap<string, string> propertys) {String data = "", str;
PrintWriter outwrite = null;
InputStream inpstream = null;
BufferedReader reader = null;
HttpURLConnection urlconn = null;
try{url url = new URL (baseurl);
Urlconn = (httpurlconnection) url.openconnection ();
Enable gzip compression urlconn.addrequestproperty ("accept-encoding", "gzip, deflate");
Urlconn.setrequestmethod (method);
Urlconn.setdooutput (TRUE);
Urlconn.setconnecttimeout (3000); if (propertys!= null &&!propertys.isempty ()) {iterator<map.entry<string, string>> props = Pro Pertys.entrYset (). iterator ();
Map.entry<string, string> Entry;
while (Props.hasnext ()) {entry = Props.next ();
Urlconn.setrequestproperty (Entry.getkey (), Entry.getvalue ());
} Outwrite = new PrintWriter (Urlconn.getoutputstream ());
Outwrite.print (Reqdata);
Outwrite.flush ();
Urlconn.connect ();
Gets the data stream inpstream = Urlconn.getinputstream ();
String encode = Urlconn.getheaderfield ("content-encoding");
If through the gzip if (encode!=null && encode.indexof ("gzip")!=-1) {LOG.V (TAG, "Get data:" + encode);
Inpstream = new Gzipinputstream (inpstream); }else if (encode!= null && encode.indexof ("deflate")!=-1) {Inpstream = new Inflaterinputstream (inpstream
);
reader = new BufferedReader (new InputStreamReader (Inpstream));
while (str = Reader.readline ())!= null) {data = str; }}catch (Malformedurlexception ex) {Ex.prinTstacktrace ();
}catch (IOException ex) {ex.printstacktrace ();
}finally{if (reader!=null && urlconn!=null) {try {outwrite.close ();
Inpstream.close ();
Reader.close ();
Urlconn.disconnect ();
catch (IOException ex) {ex.printstacktrace ();
}} log.d (TAG, "[Http data][" +baseurl+ "]:" + data);
return data;
/** * Get image information * @return/public static Bitmap Getbitmapdata (String imgurl) {Bitmap bmp = null;
LOG.D (TAG, "Get Imgage:" +imgurl);
InputStream inpstream = null;
try{HttpGet http = new HttpGet (Imgurl);
HttpClient client = new Defaulthttpclient ();
HttpResponse response = (httpresponse) client.execute (HTTP);
Httpentity httpentity = response.getentity ();
Bufferedhttpentity bufferedhttpentity = new bufferedhttpentity (httpentity);
Gets the data stream inpstream = Bufferedhttpentity.getcontent (); BMP = BitmApfactory.decodestream (Inpstream);
}catch (Exception ex) {ex.printstacktrace ();
}finally{if (Inpstream!=null) {try {inpstream.close ();
catch (IOException ex) {ex.printstacktrace ();
}} return bmp; /** * Get URL InputStream * @param urlstr * * @return/public static InputStream getinputstream (String URL
STR) {log.d (TAG, "Get HTTP Input:" +URLSTR);
InputStream inpstream = null;
try{HttpGet http = new HttpGet (URLSTR);
HttpClient client = new Defaulthttpclient ();
HttpResponse response = (httpresponse) client.execute (HTTP);
Httpentity httpentity = response.getentity ();
Bufferedhttpentity bufferedhttpentity = new bufferedhttpentity (httpentity);
Gets the data stream inpstream = Bufferedhttpentity.getcontent ();
}catch (Exception ex) {ex.printstacktrace ();
}finally{if (Inpstream!=null) {try {inpstream.close (); catch (IOException ex) {ex.printstacktrace ();
}} return inpstream;
}
}
Fileutil class:
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import android.graphics.drawable.BitmapDrawable;
Import android.graphics.drawable.Drawable;
Import android.os.Environment;
Import Android.util.Log;
public class Fileutil {private static int file_size = 4*1024;
private static String TAG = "Fileutil";
public static Boolean Hassdcard () {String status = Environment.getexternalstoragestate ();
if (Status.equals (environment.media_mounted)) {return true;
return false;
public static Boolean Createpath (String path) {file F = new file (path);
if (!f.exists ()) {Boolean o = F.mkdirs ();
LOG.I (TAG, "Create dir:" +path+ ":" +o.tostring ());
return o;
return true;
public static Boolean exists (String file) {return new file (file). exists (); public static File SaveFile (String file, InputStream inputstream) {
File f = null;
OutputStream OUTSM = null;
try{f = new file (file);
String path = F.getparent ();
if (!createpath (path)) {LOG.E (TAG, "can ' t create dir:" +path);
return null;
} if (!f.exists ()) {f.createnewfile ();
} OUTSM = new FileOutputStream (f);
byte[] buffer = new Byte[file_size];
while ((Inputstream.read (buffer))!=-1) {outsm.write (buffer);
} outsm.flush ();
}catch (IOException ex) {ex.printstacktrace ();
return null;
}finally{try{if (outsm!= null) outsm.close ();
}catch (IOException ex) {ex.printstacktrace ();
} log.v (TAG, "[Fileutil]save File:" +file+ ":" +boolean.tostring (F.exists ()));
return F;
The public static drawable getimagedrawable (String file) {if (!exists (file)) is return null;
try{InputStream INP = new FileInputStream (new file); Return Bitmapdrawable.createfromstream (INP, "IMG");
}catch (Exception ex) {ex.printstacktrace ();
return null;
}
}
For more information on Android-related content readers can view the site: "The activity of Android programming skills Summary", "Android Resources Operating Skills Summary", "Android File Operating skills summary", " Android Operation SQLite Database skills Summary, "Android operation JSON format Data Skills summary", "Android Database Operation skills Summary", "Android programming development of SD card Operation Summary", "Android Development introduction and Advanced Course", The Android View view tips summary and the Android Control usage summary
I hope this article will help you with the Android program.