java - Using same code in Main and AsyncTask gives different results -
im trying progress of download using following code:
java program code:
urlconnection conn = null; url url = null; try { url = new url("http://stackoverflow.com"); conn = url.openconnection(); conn.connect(); inputstream in = new bufferedinputstream(url.openstream()); int filesize = conn.getcontentlength(); system.out.println("file size " + filesize); int count; int i=0; while ((count = in.read()) != -1) { i++; if(i%50000==0){//prints decimal percentage every 50000 bytes system.out.println(((double)i)/((double)filesize)); } } in.close(); system.out.println("read " + + " bytes of possible " + filesize); } catch (malformedurlexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } when try same code in main of java application (almost) correct output:
read 191202 bytes of possible 191174
now if try , integrate asynctask of android app, using exact same code within asynctasks doinbackground() , calling asynctask in oncreate() (shown below) result
read 156846 bytes of possible 16983
so not filesize wrong in android number of bytes read in different too? im downloading same file , getting different results. have run both multiple times , both give approximately same results (stackoverflow vary in size +/-5000 bytes). can explain , me fix it?
android code:
public class mainactivity extends activity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); new loaddata().execute(); } private class loaddata extends asynctask<string, void, string> { protected string doinbackground(string... params) { urlconnection conn = null; url url = null; try { url = new url("http://stackoverflow.com"); conn = url.openconnection(); conn.connect(); inputstream in = new bufferedinputstream(url.openstream()); int filesize = conn.getcontentlength(); system.out.println("file size " + filesize); int count; int i=0; while ((count = in.read()) != -1) { i++; if(i%50000==0){//prints decimal percentage every 50000 bytes system.out.println(((double)i)/((double)filesize)); } } in.close(); system.out.println("read " + + " bytes of possible " + filesize); } catch (malformedurlexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } return null; } } }
Comments
Post a Comment