0

I want to check application versions to implement a force update feature from the server. I want to check values such as 1.1.5, 1.1.6 to see which is greater, I am getting this values as a string from the server and I'm getting a number format exception parsing that string to a float value before being able to compare. Here is my code:

String server_app_version = versionObj.getString("android");
String  version = info.versionName;    
float server_version = Float.parseFloat(server_app_version);
float current_version = Float.parseFloat(version);

How can i compare if server_version > current_version ?

Juan
  • 2,156
  • 18
  • 26
  • Possible duplicate of [How do you compare two version Strings in Java?](https://stackoverflow.com/questions/198431/how-do-you-compare-two-version-strings-in-java) – user3351605 Oct 11 '17 at 13:02

4 Answers4

2

try this method.

  public static int versionCompare(String str1, String str2) {
    String[] vals1 = str1.split("\\.");
    String[] vals2 = str2.split("\\.");
    int i = 0;
    // set index to first non-equal ordinal or length of shortest version string
    while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) {
      i++;
    }
    // compare first non-equal ordinal number
    if (i < vals1.length && i < vals2.length) {
        int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]));
        return Integer.signum(diff);
    }
    // the strings are equal or one string is a substring of the other
    // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4"
    return Integer.signum(vals1.length - vals2.length);
}

Alex Gitelman answers

Avinash Ajay Pandey
  • 1,497
  • 12
  • 19
0

Split the string by the '.' and cast and compare numbers from left to right

Gerard
  • 196
  • 6
0

try this aproach:

 var firstInput = "1.1.5";
var secondInput = "1.1.6";

var firstValues = firstInput.Split('.');
var secondValues = secondInput.Split('.');

// And then you compare one by une using a for loop
 // if Convert.ToInt32(firstValues[i]) >= Convert.ToInt32(secondsValues[i])
// Your logic is there

I hope it helps.

Juan

Juan
  • 2,156
  • 18
  • 26
0

Try this. it may help you.

Scanner s1 = new Scanner(str1);
Scanner s2 = new Scanner(str2);
s1.useDelimiter("\\.");
s2.useDelimiter("\\.");

while(s1.hasNextInt() && s2.hasNextInt()) {
    int v1 = s1.nextInt();
    int v2 = s2.nextInt();
    if(v1 < v2) {
        return -1;
    } else if(v1 > v2) {
        return 1;
    }
}

if(s1.hasNextInt()) return 1; //str1 has an additional lower-level version number
return 0;
Samir Bhatt
  • 3,041
  • 2
  • 25
  • 39