-3

I am getting the file size in my android app which is on a remote machine by the following line:

long fileLengthOnServer = connection.getContentLength();

The problem is sometimes the value of fileLengthOnServer is a negative value. As I read in some posts a long variable should be initialized by a value with L at the end, but I dont know in my case how to add it. If I cast it to long solves the problem?

Thanks in advance

Rafa
  • 467
  • 4
  • 18
  • Possible duplicate of [android url connection getContentLength() returning negative value](http://stackoverflow.com/questions/5428639/android-url-connection-getcontentlength-returning-negative-value) – DontKnowMuchBut Getting Better Mar 27 '17 at 04:40

2 Answers2

0

Assuming your connection is a URLConnection, use the getContentLengthLong() function:

https://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#getContentLengthLong()

muzzlator
  • 742
  • 4
  • 10
  • Thanks for the reply! I use this method in android studio the application crashes stating that the method is not available while android studio does not complain about it. Then I used the method in Intellij, it works with no problem! any idea – Rafa Mar 27 '17 at 05:13
  • My guess is you're compiling for a target SDK lower than 7.0? while your IDE might be using JDK 7.0 or higher (The reference above says "Since 7.0" for that method) – muzzlator Mar 27 '17 at 06:43
  • See http://stackoverflow.com/questions/24510219/what-is-the-difference-between-min-sdk-version-target-sdk-version-vs-compile-sd for details – muzzlator Mar 27 '17 at 06:45
0

You can read your file size from the length.


long size = file.length();

   /**
     * @param size file.length
     * @return file size in string
     */
    private String getReadableFileSize(long size) {
        try {
            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];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

Just call this method and pass the file length

Log.d(LOG_TAG, String.format("BitmapSize : %s", getReadableFileSize(imageFile.length())));
Waheed Nazir
  • 584
  • 7
  • 11