Вопрос

I would like to know the Total Internal Memory and write it in a Preference so I wrote this code:

 File path = Environment.getDataDirectory();
 StatFs stat = new StatFs(path.getPath());
 long blockSize = stat.getBlockSize();
 long totalBlocks = stat.getBlockCount();
 long Size = totalBlocks * blockSize/1073741824;

 memory = (Preference) this.findPreference("free");
 memory.setSummary(Long.toString(Size)+" GB");

1073741824 corresponds to 1024*1024*1024 for obtaining teh GigaByte. Now, the problem is, why the result is an integer? For example, in the Preference is written "5" but if I do the calculation and divide the variable size for 1024/1024 i get 5393 and which is divided again by 1024 is 5,26, but since then I receive only 5 as outpout? How can I fix this?

Это было полезно?

Решение

long variables can only hold long integers. You have to use a floating point type instead. For example:

double size = totalBlocks * blockSize / 1073741824d;

Another point to make sure is that at least one of the operands in your calculation is also a floating point type (see the d suffix to the constant). Otherwise Java will calculate an integer value and assign it to the double variable.

Furthermore, by convention, your variables should not start with a capital letter. This style is reserved for type names.

Другие советы

Do the division declaring the GB long as a float

long Size = totalBlocks * blockSize/1073741824f;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top