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 ?

1

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

1 Comment

can you give me any example of this
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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.