android - Format String into KB, MB and GB -
below class returns me data counter value in string. wanted format string kb, mb, , gb
public class mainactivity extends activity { @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); textview infoview = (textview)findviewbyid(r.id.traffic_info); string info = ""; long getmobilerxbytes = trafficstats.getmobilerxbytes(); long getmobilerxpackets = trafficstats.getmobilerxpackets(); long getmobiletxbytes = trafficstats.getmobiletxbytes(); long getmobiletxpackets = trafficstats.getmobiletxpackets(); long totalrxbytes = trafficstats.gettotalrxbytes(); long totalrxpackets = trafficstats.gettotalrxpackets(); long totaltxbytes = trafficstats.gettotaltxbytes(); long totaltxpackets = trafficstats.gettotaltxpackets(); info += "mobile interface:\n"; info += ("\treceived: " + getmobilerxbytes + " bytes / " + getmobilerxpackets + " packets\n"); info += ("\ttransmitted: " + getmobiletxbytes + " bytes / " + getmobiletxpackets + " packets\n"); info += "all network interface:\n"; info += ("\treceived: " + totalrxbytes + " bytes / " + totalrxpackets + " packets\n"); info += ("\ttransmitted: " + totaltxbytes + " bytes / " + totaltxpackets + " packets\n"); infoview.settext(info);
}
here beautiful method :
public static string humanreadablebytecount(long bytes, boolean si) { int unit = si ? 1000 : 1024; if (bytes < unit) return bytes + " b"; int exp = (int) (math.log(bytes) / math.log(unit)); string pre = (si ? "kmgtpe" : "kmgtpe").charat(exp-1) + (si ? "" : "i"); return string.format("%.1f %sb", bytes / math.pow(unit, exp), pre); }
but not sure how can use above method in oncreate code
thanks in advance
call method passing bytes . add string returned after doing calculations textview.
public static string getfilesize(long size) { if (size <= 0) return "0"; final string[] units = new string[] { "b", "kb", "mb", "gb", "tb" }; int digitgroups = (int) (math.log10(size) / math.log10(1024)); return new decimalformat("#,##0.#").format(size / math.pow(1024, digitgroups)) + " " + units[digitgroups]; }
Comments
Post a Comment