Android - String comparison between two android version names

newVersion = 1.2.1 -> 121 -> 121

oldVersion = 1.2 -> 12 -> 120

121 > 120 ?

return true


newVersion = 1.5.15 -> 1515 -> 1515

oldVersion = 2.0 -> 20 -> 2000

1515 > 2000 ?

return false

public static boolean checkForUpdate(String existingVersion, String newVersion) {
    if (existingVersion.isEmpty() || newVersion.isEmpty()) {
        return false;
    }

    existingVersion = existingVersion.replaceAll("\\.", "");
    newVersion = newVersion.replaceAll("\\.", "");

    int existingVersionLength = existingVersion.length();
    int newVersionLength = newVersion.length();

    StringBuilder versionBuilder = new StringBuilder();
    if (newVersionLength > existingVersionLength) {
        versionBuilder.append(existingVersion);
        for (int i = existingVersionLength; i < newVersionLength; i++) {
            versionBuilder.append("0");
        }
        existingVersion = versionBuilder.toString();
    } else if (existingVersionLength > newVersionLength){
        versionBuilder.append(newVersion);
        for (int i = newVersionLength; i < existingVersionLength; i++) {
            versionBuilder.append("0");
        }
        newVersion = versionBuilder.toString();
    }

    return Integer.parseInt(newVersion) > Integer.parseInt(existingVersion);
}

You can get the 'int form' of Android versions using

 Build.VERSION.SDK_INT

Anyway, if all you have is version names in 'dot notation', you can split the strings by '.' char, and iterate to compare part by part. Off the top of my head, it'd look something like.-

public int compareVersionNames(String oldVersionName, String newVersionName) {
    int res = 0;

    String[] oldNumbers = oldVersionName.split("\\.");
    String[] newNumbers = newVersionName.split("\\.");

    // To avoid IndexOutOfBounds
    int maxIndex = Math.min(oldNumbers.length, newNumbers.length);

    for (int i = 0; i < maxIndex; i ++) {
        int oldVersionPart = Integer.valueOf(oldNumbers[i]);
        int newVersionPart = Integer.valueOf(newNumbers[i]);

        if (oldVersionPart < newVersionPart) {
            res = -1;
            break;
        } else if (oldVersionPart > newVersionPart) {
            res = 1;
            break;
        }
    }

    // If versions are the same so far, but they have different length...
    if (res == 0 && oldNumbers.length != newNumbers.length) {
        res = (oldNumbers.length > newNumbers.length)?1:-1;
    }

    return res;
}

Just wrote without trying it, so sure can be optimized, but it's a start.

Tags:

Android