How would I be able to convert bytes received from TrafficStats.getTotalRxBytes() to MB with a format to start like this 0.5 or 0.7 MB.
This a snippet of what I did:
TextView txtData = (TextView)findViewById(R.id.txtBytes);
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
if(rxBytes>=1024){
DecimalFormat formatKB = new DecimalFormat("0");
double rxKb = rxBytes/1024;
txtData.setText("0" + "." + formatKB.format(rxKb) + " KB");
if(rxKb>=1024){
DecimalFormat formatMB = new DecimalFormat("0.0");
double rxMB = rxKb/1024;
txtData.setText(formatMB.format(rxMB) + " MB");
if(rxMB>=1024){
DecimalFormat formatGB = new DecimalFormat("0.0");
double rxGB = rxMB/1024;
txtData.setText(formatGB.format(rxGB) + " GB");
}
}
}
mHandler.postDelayed(mRunnable, 1000);
Thanks in advance for any help! :D
Related
I have created a simple Android-Application that takes a photo and stores the devices GPS infos in the exif-tags for the jpg-file. The following code shows this process (i know it's messy)
Android.Locations.Location loc = await client.GetLastLocationAsync();
ByteBuffer buffer = mImage.GetPlanes()[0].Buffer;
byte[] bytes = new byte[buffer.Remaining()];
buffer.Get(bytes);
using (var output = new FileOutputStream(mFile))
{
try
{
output.Write(bytes);
output.Flush();
ExifInterface exif = new ExifInterface(mFile.AbsolutePath);
string[] degMinSec = Location.Convert(loc.Latitude, Format.Seconds).Split(':');
string dms = degMinSec[0] + "/1," + degMinSec[1] + "/1" + degMinSec[2] + "/1000";
string[] degMinSec1 = Location.Convert(loc.Longitude, Format.Seconds).Split(':');
string dms1 = degMinSec1[0] + "/1," + degMinSec1[1] + "/1" + degMinSec1[2] + "/1000";
exif.SetAttribute(ExifInterface.TagGpsLatitude, dms);
exif.SetAttribute(ExifInterface.TagGpsLatitudeRef, loc.Latitude < 0?"S":"N");
exif.SetAttribute(ExifInterface.TagGpsLongitude, dms1);
exif.SetAttribute(ExifInterface.TagGpsLongitudeRef, loc.Longitude < 0 ? "W" : "E");
exif.SaveAttributes();
}
...
So now to the problem:
When i take a picture and debug the loc variable, it looks as this:
as you can see, the latitude is 48.4080605 and de longitude is 15.6257273
when i debug the converted values dms & dms1 they show these values:
dms represents latitude and has the value 48° 24' 29.0178'', dms1 represents longitude and has the value 15° 37' 32.61828''.
when i look at the pictures exif-data in metapicz.com it shows these values:
can anyone explain me what is going on and what i'm doing wrong?
i can't figure out why it shows a different location than it should
dms = degMinSec[0] + "/1," + degMinSec[1] + "/1" + degMinSec[2] + "/1000";
Should that not be
dms = degMinSec[0] + "/1," + degMinSec[1] + "/1," + degMinSec[2] + "/1000";
?
I'm having trouble formatting this decimal value format (8487.0) for that format. "8.48".
I have tried the solution of other issues posted here but I did not succeed.
Example:
Double n1 = Double.parseDouble (String.valueOf (8487.0));
DecimalFormat dec = new DecimalFormat ("#. ##");
String credits = dec.format (n1); Log.d (TAG, "test" + credits);
Currently it has the output like this: 8487
Any help is welcomed, Thanks.
You can use String format
String answer = String.format("%.2f", (8487.0 / 1000));
Log.d(TAG, answer); //8.49
There are two cases; whether you want to round off or not. Here's the sample code for both the cases.
double d = 8487.0;
d /= 1000;
DecimalFormat f = new DecimalFormat("##.00");
f.setRoundingMode(RoundingMode.FLOOR);
String notRounded = f.format(d);
System.out.println("Not Rounded: " + notRounded);
f.setRoundingMode(RoundingMode.HALF_UP);
String rounded = f.format(d);
System.out.println("Rounded: " + rounded);
So, do you want to reduce the number by a factor 1000 ? e.g. g to kg ?
Double n1 = Double.parseDouble (String.valueOf (8487.0));
Double n2 = n1 / 1000;
DecimalFormat dec = new DecimalFormat ("#. ##");
String credits = dec.format(n2);
Log.d (TAG, "test" + credits);
in my app i calculate the CPU usage and i get the result in % but sometimes the result is too big 20.234234234234
My question is, how can i completely remove the result numbers after the "."? And can i do this without changing float to integer?
Here is my code:
private float readCpuUsage() {
try {
RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
String load = reader.readLine();
String[] toks = load.split(" ");
long idle1 = Long.parseLong(toks[5]);
long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3])
+ Long.parseLong(toks[4]) + Long.parseLong(toks[6])
+ Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
try {
Thread.sleep(360);
} catch (Exception e) {
}
reader.seek(0);
load = reader.readLine();
reader.close();
toks = load.split(" ");
long idle2 = Long.parseLong(toks[5]);
long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3])
+ Long.parseLong(toks[4]) + Long.parseLong(toks[6])
+ Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
return (float) (cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));
} catch (IOException ex) {
ex.printStackTrace();
}
return 0;
}
To print the result i just throw:
textview.setText((readCpuUsage() * 100) + "%");
where readCpuUsage() is the result and to transform it to % i multiply it with 100
This is how i did it:
float xxz=readCpuUsage()*100;
textview.setText(String.format("%.0f",xxz) + "%");
Try This it may be help to you
String.format("%.0f",floatvalue);
or
Float.parseFloat(String.format("%.0f",floatvalue))
It looks like you are unnecessarily complicating things.
When you know for sure that you do not want the decimal component of your number you should just use the integer or long types. Unless you have a valid reason or specific bias against the int datatype.
There is only Long type used in the below operation hence the result will be always long.
return (float) (cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));
I don't understand why are you typecasting it to float at the first place.
Just change the return type to long from float.
And change the return statement to :
return (cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));
float x = 100.5;
float result = x - (int)x;
if (result != 0)
{
//If the value of `result` is not equal to zero, then, you have a decimal portion which is not equal to 0.
//If you want integer result
Integer yourAnswer1 = (Integer)result;
Float yourAnswer2 = (float)result;
}
float f=2443.4333;
println(Math.floor(f)+"");
this will give you result 2443.0
If I know the degress, minutes, and seconds of a location, how do I convert them to a valid location for ExifInterface.TAG_GPS_LATITUDE and ExifInterface.TAG_GPS_LONGITUDE?
I found following: https://developer.android.com/reference/android/media/ExifInterface.html#TAG_GPS_LATITUDE
But I'm not sure if I understand the format correctly. There is written following:
String. Format is "num1/denom1,num2/denom2,num3/denom3".
I'm not sure which fractions to use for each values... Always 1? Like in following code example:
String exifLatitude1 = degress+ "/1," + minutes + "/1," + seconds + "/1";
I often see strings with /1000 for the seconds, so I'm not sure if following is correct instead of the example above:
String exifLatitude2 = degress+ "/1," + minutes + "/1," + seconds + "/1000";
Can anyone tell me, which one is correct?
My working solution uses milliseconds/1000
-79.948862 becomes
-79 degrees, 56 minutes, 55903 millisecs (equals 55.903 seconds)
79/1,56/1,55903/1000
I have never checked if 79/1,56/1,56/1 would be ok, too.
I am using this code:
from https://github.com/k3b/APhotoManager/blob/FDroid/app/src/main/java/de/k3b/android/util/ExifGps.java
public static boolean saveLatLon(File filePath, double latitude, double longitude) {
exif = new ExifInterface(filePath.getAbsolutePath());
debugExif(sb, "old", exif, filePath);
exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, convert(latitude));
exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, latitudeRef(latitude));
exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, convert(longitude));
exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, longitudeRef(longitude));
exif.saveAttributes();
}
/**
* convert latitude into DMS (degree minute second) format. For instance<br/>
* -79.948862 becomes<br/>
* 79/1,56/1,55903/1000<br/>
* It works for latitude and longitude<br/>
* #param latitude could be longitude.
* #return
*/
private static final String convert(double latitude) {
latitude=Math.abs(latitude);
int degree = (int) latitude;
latitude *= 60;
latitude -= (degree * 60.0d);
int minute = (int) latitude;
latitude *= 60;
latitude -= (minute * 60.0d);
int second = (int) (latitude*1000.0d);
StringBuilder sb = new StringBuilder(20);
sb.append(degree);
sb.append("/1,");
sb.append(minute);
sb.append("/1,");
sb.append(second);
sb.append("/1000");
return sb.toString();
}
private static StringBuilder createDebugStringBuilder(File filePath) {
return new StringBuilder("Set Exif to file='").append(filePath.getAbsolutePath()).append("'\n\t");
}
private static String latitudeRef(double latitude) {
return latitude<0.0d?"S":"N";
}
I'm following javacv Face Detection/Recognition code, there is confusion regarding face recognition.. What I'm doing is (Sorry if it sounds stupid but I'm stuck)
1) Detect Face crop it and save it to sdcard and place path in learn.txt file (Learning part)
2) Detect Face crop it and find it in existing faces whether it exists or not, but it always return nearest position even if the face doesn't exist in sample faces..
what I'm doing wrong?
// Method, I'm using to recognize face
public Integer recognizeFace(Bitmap face, Context context) {
Log.i(TAG, "===========================================");
Log.i(TAG, "recognizeFace (single face)");
float[] projectedTestFace;
float confidence = 0.0f;
int nearest = -1; // closest match -- -1 for nothing.
int iNearest;
if (trainPersonNumMat == null) {
return null;
}
Log.i(TAG, "NUMBER OF EIGENS: " + nEigens);
// project the test images onto the PCA subspace
projectedTestFace = new float[nEigens];
// Start timing recognition
long startTime = System.nanoTime();
testFaceImg = bmpToIpl(face);
// saveBmp(face, "blah");
// convert Bitmap it IplImage
//testFaceImg = IplImage.create(face.getWidth(), face.getHeight(),
// IPL_DEPTH_8U, 4);
//face.copyPixelsToBuffer(testFaceImg.getByteBuffer());
// project the test image onto the PCA subspace
cvEigenDecomposite(testFaceImg, // obj
nEigens, // nEigObjs
new PointerPointer(eigenVectArr), // eigInput (Pointer)
0, // ioFlags
null, // userData
pAvgTrainImg, // avg
projectedTestFace); // coeffs
// LOGGER.info("projectedTestFace\n" +
// floatArrayToString(projectedTestFace));
Log.i(TAG, "projectedTestFace\n" + floatArrayToString(projectedTestFace));
final FloatPointer pConfidence = new FloatPointer(confidence);
iNearest = findNearestNeighbor(projectedTestFace, new FloatPointer(pConfidence));
confidence = pConfidence.get();
// truth = personNumTruthMat.data_i().get(i);
nearest = trainPersonNumMat.data_i().get(iNearest); // result
// get endtime and calculate time recognition process takes
long endTime = System.nanoTime();
long duration = endTime - startTime;
double seconds = (double) duration / 1000000000.0;
Log.i(TAG, "recognition took: " + String.valueOf(seconds));
Log.i(TAG, "nearest = " + nearest + ". Confidence = " + confidence);
Toast.makeText(context, "Nearest: "+nearest+" Confidence: "+confidence, Toast.LENGTH_LONG).show();
//Save the IplImage so we can see what it looks like
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "/sdcard/saved_images/" + nearest + " " + String.valueOf(seconds) + " " + String.valueOf(confidence) + " " + n + ".jpg";
Log.i(TAG, "Saving image as: " + fname);
cvSaveImage(fname, testFaceImg);
return nearest;
} // end of recognizeFace
EDIT The confidence is always negative!
Thanks in advance