Skip to content

Instantly share code, notes, and snippets.

@RobGThai
Created June 21, 2013 07:26
Show Gist options
  • Save RobGThai/5829503 to your computer and use it in GitHub Desktop.
Save RobGThai/5829503 to your computer and use it in GitHub Desktop.
Version checking basic
/**
* Use this method to compare if the latest version is newer than current version or not.
* @param currentVersion current version
* @param latestVersion latest version
* @return true if newer
*/
public boolean isNewerVersion(String currentVersion, String latestVersion){
boolean result = false;
if(currentVersion == null){
currentVersion = "0";
}
if(latestVersion == null){
latestVersion = "0";
}
int cPos = currentVersion.indexOf(".");
String curr = null;
if(cPos < 0){
curr = currentVersion;
}else{
curr = currentVersion.substring(0, cPos);
}
int lPos = latestVersion.indexOf(".");
String latest = null;
if(lPos < 0){
latest = latestVersion;
}else{
latest = latestVersion.substring(0, lPos);
}
int c = Integer.parseInt(curr);
int l = Integer.parseInt(latest);
if(c < l){
return true;
}else if(c == l && (cPos > 0 || lPos > 0)){
String cNext = (cPos > 0 ? currentVersion.substring(cPos+1): null);
String lNext = (lPos > 0 ? latestVersion.substring(lPos+1): null);
result = isNewerVersion(cNext, lNext);
}
return result;
}
public static void main(String[] args) throws Exception{
Utils u = new Utils();
System.out.println("true: " + u.isNewerVersion("1.0", "1.0.2"));
System.out.println("true: " + u.isNewerVersion("1.0", "1.0.5"));
System.out.println("true: " + u.isNewerVersion("1.0.2", "1.0.3"));
System.out.println("true: " + u.isNewerVersion("1.0.5", "1.0.10"));
System.out.println("true: " + u.isNewerVersion("1.2", "1.12"));
System.out.println("false: " + u.isNewerVersion("1.2", "1.1"));
System.out.println("false: " + u.isNewerVersion("1.2.1", "1.2.1"));
System.out.println("false: " + u.isNewerVersion("1.1", "1.0.10"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment