How to compare app version in android
I got latest version code and current version code , but the problem is
current version is 1.0
and latest version is 1.0.0
so how to compare that float value in android
I have written a small Android library for comparing version numbers: https://github.com/G00fY2/version-compare
What it basically does is this:
public int compareVersions(String versionA, String versionB) {
String[] versionTokensA = versionA.split("\\.");
String[] versionTokensB = versionB.split("\\.");
List<Integer> versionNumbersA = new ArrayList<>();
List<Integer> versionNumbersB = new ArrayList<>();
for (String versionToken : versionTokensA) {
versionNumbersA.add(Integer.parseInt(versionToken));
}
for (String versionToken : versionTokensB) {
versionNumbersB.add(Integer.parseInt(versionToken));
}
final int versionASize = versionNumbersA.size();
final int versionBSize = versionNumbersB.size();
int maxSize = Math.max(versionASize, versionBSize);
for (int i = 0; i < maxSize; i++) {
if ((i < versionASize ? versionNumbersA.get(i) : 0) > (i < versionBSize ? versionNumbersB.get(i) : 0)) {
return 1;
} else if ((i < versionASize ? versionNumbersA.get(i) : 0) < (i < versionBSize ? versionNumbersB.get(i) : 0)) {
return -1;
}
}
return 0;
}
This snippet doesn't offer any error checks or handling. Beside that my library also supports suffixes like "1.2-rc" > "1.2-beta".
I am a bit late to the party but I have a great solution for all of you!
1. Use this class:
public class VersionComparator implements Comparator {
public boolean equals(Object o1, Object o2) {
return compare(o1, o2) == 0;
}
public int compare(Object o1, Object o2) {
String version1 = (String) o1;
String version2 = (String) o2;
VersionTokenizer tokenizer1 = new VersionTokenizer(version1);
VersionTokenizer tokenizer2 = new VersionTokenizer(version2);
int number1, number2;
String suffix1, suffix2;
while (tokenizer1.MoveNext()) {
if (!tokenizer2.MoveNext()) {
do {
number1 = tokenizer1.getNumber();
suffix1 = tokenizer1.getSuffix();
if (number1 != 0 || suffix1.length() != 0) {
// Version one is longer than number two, and non-zero
return 1;
}
}
while (tokenizer1.MoveNext());
// Version one is longer than version two, but zero
return 0;
}
number1 = tokenizer1.getNumber();
suffix1 = tokenizer1.getSuffix();
number2 = tokenizer2.getNumber();
suffix2 = tokenizer2.getSuffix();
if (number1 < number2) {
// Number one is less than number two
return -1;
}
if (number1 > number2) {
// Number one is greater than number two
return 1;
}
boolean empty1 = suffix1.length() == 0;
boolean empty2 = suffix2.length() == 0;
if (empty1 && empty2) continue; // No suffixes
if (empty1) return 1; // First suffix is empty (1.2 > 1.2b)
if (empty2) return -1; // Second suffix is empty (1.2a < 1.2)
// Lexical comparison of suffixes
int result = suffix1.compareTo(suffix2);
if (result != 0) return result;
}
if (tokenizer2.MoveNext()) {
do {
number2 = tokenizer2.getNumber();
suffix2 = tokenizer2.getSuffix();
if (number2 != 0 || suffix2.length() != 0) {
// Version one is longer than version two, and non-zero
return -1;
}
}
while (tokenizer2.MoveNext());
// Version two is longer than version one, but zero
return 0;
}
return 0;
}
// VersionTokenizer.java
public static class VersionTokenizer {
private final String _versionString;
private final int _length;
private int _position;
private int _number;
private String _suffix;
private boolean _hasValue;
VersionTokenizer(String versionString) {
if (versionString == null)
throw new IllegalArgumentException("versionString is null");
_versionString = versionString;
_length = versionString.length();
}
public int getNumber() {
return _number;
}
String getSuffix() {
return _suffix;
}
public boolean hasValue() {
return _hasValue;
}
boolean MoveNext() {
_number = 0;
_suffix = "";
_hasValue = false;
// No more characters
if (_position >= _length)
return false;
_hasValue = true;
while (_position < _length) {
char c = _versionString.charAt(_position);
if (c < '0' || c > '9') break;
_number = _number * 10 + (c - '0');
_position++;
}
int suffixStart = _position;
while (_position < _length) {
char c = _versionString.charAt(_position);
if (c == '.') break;
_position++;
}
_suffix = _versionString.substring(suffixStart, _position);
if (_position < _length) _position++;
return true;
}
}
}
2. create this function
private fun isNewVersionAvailable(currentVersion: String, latestVersion: String): Boolean {
val versionComparator = VersionComparator()
val result: Int = versionComparator.compare(currentVersion, latestVersion)
var op = "=="
if (result < 0) op = "<"
if (result > 0) op = ">"
System.out.printf("%s %s %s\n", currentVersion, op, latestVersion)
return if (op == ">" || op == "==") {
false
} else op == "<"
}
3. and just call it by
e.g. isNewVersionAvailable("1.2.8","1.2.9") where 1.2.8 is your current version here and 1.2.9 is the latest version, which returns true!
Why overcomplicate this so much?
Just scale the major, minor, patch version and you have it covered:
fun getAppVersionFromString(version: String): Int { // "2.3.5"
val versions = version.split(".") // [2, 3, 5]
val major = versions[0].toIntOrDefault(0) * 10000 // 20000
val minor = versions[1].toIntOrDefault(0) * 1000 // 3000
val patch = versions[2].toIntOrDefault(0) * 100 // 500
return major + minor + patch // 2350
}
That way when you compare e.g 9.10.10 with 10.0.0 the second one is greater.
Use the following method to compare the versions number:
Convert float to String first.
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);
}
Refer the following SO question : Efficient way to compare version strings in Java
Related
This question already has answers here:
Convert String to operator(+*/-) in java
(5 answers)
Closed 4 years ago.
How I convert String containing Mathematic arithmetic operation's like "10 + 20 - 25", I am getting String from EditText,I want to convert get the Result of operation.
Here is my code to resolve your problem:
public class ExecuteHandler {
private static Character[] OPERATORS = { '/', '*', '+', '-' };
private static final String REGEXOPERATORS = "[/+,-,/*,//,-]";
private static final String REGEXDIGITS = "(\\d+)";
private ArrayList<Character> operators = new ArrayList<>();
private ArrayList<Integer> digits = new ArrayList<>();
public String execute(String math) {
StringBuilder result = new StringBuilder();
try {
getDigits(math);
getOperators(math);
getNextOperator(operators);
for (Integer digit : digits) {
result.append(String.valueOf(digit));
}
} catch (ArithmeticException | IndexOutOfBoundsException e) {
return "ERROR";
}
return result.toString().isEmpty() ? "ERROR" : result.toString();
}
public void clear() {
operators.clear();
digits.clear();
}
private void getNextOperator(ArrayList<Character> operators) {
for (Character op : OPERATORS) {
for (int i = 0; i < operators.size(); i++) {
if (operators.get(i) == '/') {
operators.remove(i);
digits.set(i, (digits.get(i) / digits.get(i + 1)));
digits.remove(i + 1);
i -= 1;
}
}
for (int i = 0; i < operators.size(); i++) {
if (operators.get(i) == '*') {
operators.remove(i);
digits.set(i, (digits.get(i) * digits.get(i + 1)));
digits.remove(i + 1);
i -= 1;
}
}
for (int i = 0; i < operators.size(); i++) {
if (operators.get(i) == '+') {
operators.remove(i);
digits.set(i, (digits.get(i) + digits.get(i + 1)));
digits.remove(i + 1);
i -= 1;
}
}
for (int i = 0; i < operators.size(); i++) {
if (operators.get(i) == '-') {
operators.remove(i);
digits.set(i, (digits.get(i) - digits.get(i + 1)));
digits.remove(i + 1);
i -= 1;
}
}
}
}
private void getDigits(String math) {
Pattern r = Pattern.compile(REGEXDIGITS);
Matcher m = r.matcher(math);
while (m.find()) {
int t = Integer.parseInt(math.substring(m.start(), m.end()));
digits.add(t);
}
}
private void getOperators(String math) {
Pattern r = Pattern.compile(REGEXOPERATORS);
Matcher m = r.matcher(math);
while (m.find()) {
operators.add(math.charAt(m.start()));
}
}
}
Call method execute with input is string like "10 + 20 - 25:", the result will be a string of value (if success) or ERROR (if any syntax error).
Is there any pdf text extractor api that extract arabic text from pdf.
I am using itextpdf api it works fine in extract English but it doesn't extract arabic text.
This is my code for extract text in pdf:
private String extractPDF(String path) throws IOException {
String parsedText = "";
PdfReader reader = new PdfReader(path);
int n = reader.getNumberOfPages();
for (int page = 0; page < n; page++) {
parsedText = parsedText + PdfTextExtractor.getTextFromPage(reader, page + 1).trim() + "\n"; //Extracting the content from the different pages
}
reader.close();
return parsedText;
}
and this is the input pdf :arabic.pdf
Update :
i able to extract arabic text but it doesn't preserves the order of the lines , and this is my code:
private String extractPDF(String name) throws IOException {
PdfReader reader = new PdfReader(name);
StringBuilder text = new StringBuilder();
for (int i=1;i<=reader.getNumberOfPages();i++){
String data = PdfTextExtractor.getTextFromPage(reader,i,new SimpleTextExtractionStrategy());
text.append(Bidi.BidiText(data,1).getText());
}
return text.toString();
}
pdf text is :
بسم الله الرحمن الرحيم
السلام عليكم ورحمة الله وبركاته
سبحان الله
the output is :
سبحان الله
السلام عليكم ورحمة الله وبركاته
بسم الله الرحمن الرحيم
this is my code for method BidiText:
public static BidiResult BidiText(String str, int startLevel)
{
boolean isLtr = true;
int strLength = str.length();
if (strLength == 0)
{
return new BidiResult(str, false);
}
// get types, fill arrays
char[] chars = new char[strLength];
String[] types = new String[strLength];
String[] oldtypes = new String[strLength];
int numBidi = 0;
for (int i = 0; i < strLength; ++i)
{
chars[i] = str.charAt(i);
char charCode = str.charAt(i);
String charType = "L";
if (charCode <= 0x00ff)
{
charType = BaseTypes[charCode];
}
else if (0x0590 <= charCode && charCode <= 0x05f4)
{
charType = "R";
}
else if (0x0600 <= charCode && charCode <= 0x06ff)
{
charType = ArabicTypes[charCode & 0xff];
}
else if (0x0700 <= charCode && charCode <= 0x08AC)
{
charType = "AL";
}
if (charType.equals("R") || charType.equals("AL") || charType.equals("AN"))
{
numBidi++;
}
oldtypes[i] = types[i] = charType;
}
if (numBidi == 0)
{
return new BidiResult(str, true);
}
if (startLevel == -1)
{
if ((strLength / numBidi) < 0.3)
{
startLevel = 0;
}
else
{
isLtr = false;
startLevel = 1;
}
}
int[] levels = new int[strLength];
for (int i = 0; i < strLength; ++i)
{
levels[i] = startLevel;
}
String e = IsOdd(startLevel) ? "R" : "L";
String sor = e;
String eor = sor;
String lastType = sor;
for (int i = 0; i < strLength; ++i)
{
if (types[i].equals("NSM"))
{
types[i] = lastType;
}
else
{
lastType = types[i];
}
}
lastType = sor;
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (t.equals("EN"))
{
types[i] = (lastType.equals("AL")) ? "AN" : "EN";
}
else if (t.equals("R") || t.equals("L") || t.equals("AL"))
{
lastType = t;
}
}
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (t.equals("AL"))
{
types[i] = "R";
}
}
for (int i = 1; i < strLength - 1; ++i)
{
if (types[i].equals("ES") && types[i - 1].equals("EN") && types[i + 1].equals("EN"))
{
types[i] = "EN";
}
if (types[i].equals("CS") && (types[i - 1].equals("EN") || types[i - 1].equals("AN")) && types[i + 1] == types[i - 1])
{
types[i] = types[i - 1];
}
}
for (int i = 0; i < strLength; ++i)
{
if (types[i].equals("EN"))
{
// do before
for (int j = i - 1; j >= 0; --j)
{
if (!types[j].equals("ET"))
{
break;
}
types[j] = "EN";
}
// do after
for (int j = i + 1; j < strLength; --j)
{
if (!types[j].equals("ET"))
{
break;
}
types[j] = "EN";
}
}
}
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (t.equals("WS") || t.equals("ES") || t.equals("ET") || t.equals("CS"))
{
types[i] = "ON";
}
}
lastType = sor;
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (t.equals("EN"))
{
types[i] = (lastType.equals("L")) ? "L" : "EN";
}
else if (t.equals("R") || t.equals("L"))
{
lastType = t;
}
}
for (int i = 0; i < strLength; ++i)
{
if (types[i].equals("ON"))
{
int end = FindUnequal(types, i + 1, "ON");
String before = sor;
if (i > 0)
{
before = types[i - 1];
}
String after = eor;
if (end + 1 < strLength)
{
after = types[end + 1];
}
if (!before.equals("L"))
{
before = "R";
}
if (!after.equals("L"))
{
after = "R";
}
if (before == after)
{
SetValues(types, i, end, before);
}
i = end - 1; // reset to end (-1 so next iteration is ok)
}
}
for (int i = 0; i < strLength; ++i)
{
if (types[i].equals("ON"))
{
types[i] = e;
}
}
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (IsEven(levels[i]))
{
if (t.equals("R"))
{
levels[i] += 1;
}
else if (t.equals("AN") || t.equals("EN"))
{
levels[i] += 2;
}
}
else
{
if (t.equals("L") || t.equals("AN") || t.equals("EN"))
{
levels[i] += 1;
}
}
}
int highestLevel = -1;
int lowestOddLevel = 99;
int ii = levels.length;
for (int i = 0; i < ii; ++i)
{
int level = levels[i];
if (highestLevel < level)
{
highestLevel = level;
}
if (lowestOddLevel > level && IsOdd(level))
{
lowestOddLevel = level;
}
}
for (int level = highestLevel; level >= lowestOddLevel; --level)
{
int start = -1;
ii = levels.length;
for (int i = 0; i < ii; ++i)
{
if (levels[i] < level)
{
if (start >= 0)
{
chars = ReverseValues(chars, start, i);
start = -1;
}
}
else if (start < 0)
{
start = i;
}
}
if (start >= 0)
{
chars = ReverseValues(chars, start, levels.length);
}
}
String result = "";
ii = chars.length;
for (int i = 0; i < ii; ++i)
{
char ch = chars[i];
if (ch != '<' && ch != '>')
{
result += ch;
}
}
return new BidiResult(result, isLtr);
}
Your example PDF does not contain any text at all, it merely contains an embedded bitmap image of text.
When talking about "text extraction from PDFs" (and "text extractor APIs" and PdfTextExtractor classes etc.), one usually means finding text drawing instructions in the PDF (for which a PDF viewer uses a font program either embedded in the PDF or available on the system at hand to display the text) and determining their text content from their string arguments and font encoding definitions.
As in your case there are no such text drawing instructions, merely a bitmap drawing instruction and the bitmap itself, text extraction from your document will return an empty string.
To retrieve the text displayed in your document, you have to look for OCR (optical character recognition) solutions. PDF libraries (like iText) can help you to extract the embedded bitmap image to forward to the OCR solution if the OCR solution does not directly support PDF but only bitmap formats.
If you also have PDF documents which display Arabic text using text drawing instructions with sufficient encoding information instead of bitmaps, you may need to post-process the text extraction output of iText with a method like Convert as proposed in this answer as pointed out by Amedee in a comment to your question. (Yes, it is written in C# but it is pretty easy to port to Java.)
I want to Justify text inside Android TextView. With copy and share function and can accept spannable string. Can someone help me. It's so important for me. Thank you in advance
I have a solution for the text-justify in Android.
I have created a Custom Textview class, with this you can solve the justification issue in Android.
<com.trailcreator.util.JustifyCustomTextView
android:id="#+id/yourTextViewID"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Here is the class
public class JustifyCustomTextView extends android.support.v7.widget.AppCompatTextView {
//Object that helps us to measure the words and characters like spaces.
private Paint mPaint;
//Thin space (Hair Space actually) character that will fill the spaces
private String mThinSpace = "\u200A";
//String that will storage the text with the inserted spaces
private String mJustifiedText = "";
//Float that represents the actual width of a sentence
private float mSentenceWidth = 0;
//Integer that counts the spaces needed to fill the line being processed
private int mWhiteSpacesNeeded = 0;
//Integer that counts the actual amount of words in the sentence
private int mWordsInThisSentence = 0;
//ArrayList of Strings that will contain the words of the sentence being processed
private ArrayList<String> mTemporalLine = new ArrayList<String>();
//StringBuilder that will hold the temporal chunk of the string to calculate word index.
private StringBuilder mStringBuilderCSequence = new StringBuilder();
//List of SpanHolder class that will hold the spans within the giving string.
private List<SpanHolder> mSpanHolderList = new ArrayList<>();
//StringBuilder that will store temp data for joining sentence.
private StringBuilder sentence = new StringBuilder();
private int mViewWidth;
private float mThinSpaceWidth;
private float mWhiteSpaceWidth;
//Default Constructors!
public JustifyCustomTextView(Context context) {
super(context);
}
public JustifyCustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public JustifyCustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (mJustifiedText.replace(" ", "")
.replace("", mThinSpace)
.equals(this.getText().toString().replace(" ", "").replace("", mThinSpace))) {
return;
}
ViewGroup.LayoutParams params = this.getLayoutParams();
CharSequence charSequence = this.getText();
mSpanHolderList.clear();
String[] words = this.getText().toString().split(" ");
//Get spans within the string and adds the instance references into the
//SpanHolderList to be applied once the justify process has been performed.
SpannableString s = SpannableString.valueOf(charSequence);
if ((charSequence instanceof SpannedString)) {
for (int i = 0; i < this.getText().length() - 1; i++) {
CharacterStyle[] spans =
((SpannedString) charSequence).getSpans(i, i + 1, CharacterStyle.class);
if (spans != null && spans.length > 0) {
for (CharacterStyle span : spans) {
int spaces =
charSequence.toString().substring(0, i).split(" ").length + charSequence.toString()
.substring(0, i)
.split(mThinSpace).length;
SpanHolder spanHolder =
SpanHolder.getNewInstance(spans, s.getSpanStart(span), s.getSpanEnd(span), spaces);
mStringBuilderCSequence.setLength(0);
for (int j = 0; j <= words.length - 1; j++) {
mStringBuilderCSequence.append(words[j]);
mStringBuilderCSequence.append(" ");
if (mStringBuilderCSequence.length() > i) {
if (words[j].trim().replace(mThinSpace, "").length() == 1) {
spanHolder.setWordHolderIndex(j);
} else {
spanHolder.setWordHolderIndex(j);
spanHolder.setTextChunkPadded(true);
}
break;
}
}
mSpanHolderList.add(spanHolder);
}
}
}
}
mPaint = this.getPaint();
mViewWidth = this.getMeasuredWidth() - (getPaddingLeft() + getPaddingRight());
//This class won't justify the text if the TextView has wrap_content as width
//And won't repeat the process of justify text if it's already done.
//AND! won't justify the text if the view width is 0
if (params.width != ViewGroup.LayoutParams.WRAP_CONTENT
&& mViewWidth > 0
&& words.length > 0
&& mJustifiedText.isEmpty()) {
mThinSpaceWidth = mPaint.measureText(mThinSpace);
mWhiteSpaceWidth = mPaint.measureText(" ");
for (int i = 0; i <= words.length - 1; i++) {
boolean containsNewLine = (words[i].contains("\n") || words[i].contains("\r"));
if (containsNewLine) {
String[] splitted = words[i].split("(?<=\\n)");
for (String splitWord : splitted) {
processWord(splitWord, splitWord.contains("\n"));
}
} else {
processWord(words[i], false);
}
}
mJustifiedText += joinWords(mTemporalLine);
}
//Apply the extra spaces to the items of the SpanList that were added due
//the justifying process.
SpannableString spannableString = SpannableString.valueOf(mJustifiedText);
for (SpanHolder sH : mSpanHolderList) {
int spaceCount = 0, wordCount = 0;
boolean isCountingWord = false;
int j = 0;
while (wordCount < (sH.getWordHolderIndex() + 1)) {
if (mJustifiedText.charAt(j) == ' ' || mJustifiedText.charAt(j) == ' ') {
spaceCount++;
if (isCountingWord) {
wordCount++;
}
isCountingWord = false;
} else {
isCountingWord = true;
}
j++;
}
sH.setStart(
sH.getStart() + spaceCount - sH.getCurrentSpaces() + (sH.isTextChunkPadded() ? 1 : 0));
sH.setEnd(
sH.getEnd() + spaceCount - sH.getCurrentSpaces() + (sH.isTextChunkPadded() ? 1 : 0));
}
//Applies spans on Justified String.
for (SpanHolder sH : mSpanHolderList) {
for (CharacterStyle cS : sH.getSpans())
spannableString.setSpan(cS, sH.getStart(), sH.getEnd(), 0);
}
if (!mJustifiedText.isEmpty()) this.setText(spannableString);
}
private void processWord(String word, boolean containsNewLine) {
if ((mSentenceWidth + mPaint.measureText(word)) < mViewWidth) {
mTemporalLine.add(word);
mWordsInThisSentence++;
mTemporalLine.add(containsNewLine ? "" : " ");
mSentenceWidth += mPaint.measureText(word) + mWhiteSpaceWidth;
if (containsNewLine) {
mJustifiedText += joinWords(mTemporalLine);
resetLineValues();
}
} else {
while (mSentenceWidth < mViewWidth) {
mSentenceWidth += mThinSpaceWidth;
if (mSentenceWidth < mViewWidth) mWhiteSpacesNeeded++;
}
if (mWordsInThisSentence > 1) {
insertWhiteSpaces(mWhiteSpacesNeeded, mWordsInThisSentence, mTemporalLine);
}
mJustifiedText += joinWords(mTemporalLine);
resetLineValues();
if (containsNewLine) {
mJustifiedText += word;
mWordsInThisSentence = 0;
return;
}
mTemporalLine.add(word);
mWordsInThisSentence = 1;
mTemporalLine.add(" ");
mSentenceWidth += mPaint.measureText(word) + mWhiteSpaceWidth;
}
}
//Method that resets the values of the actual line being processed
private void resetLineValues() {
mTemporalLine.clear();
mSentenceWidth = 0;
mWhiteSpacesNeeded = 0;
mWordsInThisSentence = 0;
}
//Function that joins the words of the ArrayList
private String joinWords(ArrayList<String> words) {
sentence.setLength(0);
for (String word : words) {
sentence.append(word);
}
return sentence.toString();
}
//Method that inserts spaces into the words to make them fix perfectly in the width of the view. I know I'm a genius naming stuff :)
private void insertWhiteSpaces(int whiteSpacesNeeded, int wordsInThisSentence,
ArrayList<String> sentence) {
if (whiteSpacesNeeded == 0) return;
if (whiteSpacesNeeded == wordsInThisSentence) {
for (int i = 1; i < sentence.size(); i += 2) {
sentence.set(i, sentence.get(i) + mThinSpace);
}
} else if (whiteSpacesNeeded < wordsInThisSentence) {
for (int i = 0; i < whiteSpacesNeeded; i++) {
int randomPosition = getRandomEvenNumber(sentence.size() - 1);
sentence.set(randomPosition, sentence.get(randomPosition) + mThinSpace);
}
} else if (whiteSpacesNeeded > wordsInThisSentence) {
//I was using recursion to achieve this... but when you tried to watch the preview,
//Android Studio couldn't show any preview because a StackOverflow happened.
//So... it ended like this, with a wild while xD.
while (whiteSpacesNeeded > wordsInThisSentence) {
for (int i = 1; i < sentence.size() - 1; i += 2) {
sentence.set(i, sentence.get(i) + mThinSpace);
}
whiteSpacesNeeded -= (wordsInThisSentence - 1);
}
if (whiteSpacesNeeded == 0) return;
if (whiteSpacesNeeded == wordsInThisSentence) {
for (int i = 1; i < sentence.size(); i += 2) {
sentence.set(i, sentence.get(i) + mThinSpace);
}
} else if (whiteSpacesNeeded < wordsInThisSentence) {
for (int i = 0; i < whiteSpacesNeeded; i++) {
int randomPosition = getRandomEvenNumber(sentence.size() - 1);
sentence.set(randomPosition, sentence.get(randomPosition) + mThinSpace);
}
}
}
}
//Gets a random number, it's part of the algorithm... don't blame me.
private int getRandomEvenNumber(int max) {
Random rand = new Random();
// nextInt is normally exclusive of the top value,
return rand.nextInt((max)) & ~1;
}
}
public class SpanHolder {
private CharacterStyle[] spans;
private int start;
private int end;
private boolean textChunkPadded =false;
private int wordHolderIndex;
private int currentSpaces;
public SpanHolder(CharacterStyle[] spans, int start, int end, int spaces){
this.setSpans(spans);
this.setStart(start);
this.setEnd(end);
this.setCurrentSpaces(spaces);
}
public static SpanHolder getNewInstance(CharacterStyle[] spans, int start, int end, int spaces){
return new SpanHolder(spans,start,end,spaces);
}
public boolean isTextChunkPadded() {
return textChunkPadded;
}
public void setTextChunkPadded(boolean textChunkPadded) {
this.textChunkPadded = textChunkPadded;
}
public int getWordHolderIndex() {
return wordHolderIndex;
}
public void setWordHolderIndex(int wordHolderIndex) {
this.wordHolderIndex = wordHolderIndex;
}
public CharacterStyle[] getSpans() {
return spans;
}
public void setSpans(CharacterStyle[] spans) {
this.spans = spans;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public int getCurrentSpaces() {
return currentSpaces;
}
public void setCurrentSpaces(int currentSpaces) {
this.currentSpaces = currentSpaces;
}
}
GOOD LUCK! (Y)
I am using proto3 for an Android app and I am having a problem with object equality, which makes it really hard on testing, especially for verify methods
Here is a unit-test representing the problem:
#Test
public void test_equal () {
PlayerCards playerCards1 = new PlayerCards();
playerCards1.playerId = 1;
playerCards1.cards = new int[]{2};
PlayerCards playerCards2 = new PlayerCards();
playerCards2.playerId = 1;
playerCards2.cards = new int[]{2};
assertThat(playerCards1.toString(), is(playerCards2.toString())); // pass
assertThat(PlayerCards.toByteArray(playerCards1),
is(PlayerCards.toByteArray(playerCards2))); // pass
assertThat(playerCards1, is(playerCards2)); // <----- fail
}
It is quite clear that the method equals is not working properly, checking the produced code (attached at the bottom) no equals, hashcode are generated.
I can workaround the assertThat by using .toString method but I cannot find any other way for verifications,
eg. verify(anyMock).anyMethod(playerCards)
I am afraid that this may also affect my runtime if am not extremely careful on checks.
Is there any way to generate equals, hashcode?
If not, can I at least extend, override verify so as to use toString when checking against proto-generated objects?
code-snippets:
My proto file is:
syntax = "proto3";
option java_multiple_files = true;
option optimize_for = LITE_RUNTIME; // existing or not has no effect.
option java_package = "com.package.my";
option java_outer_classname = "Proto";
option objc_class_prefix = "ABC";
package com.package.protos;
message PlayerCards {
int64 playerId = 1;
repeated int32 cards = 2;
}
I generate the files through gradle build and use the following properties
buildscript {
// ...
dependencies {
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.0'
}
}
apply plugin: 'com.google.protobuf'
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.1.0'
}
generateProtoTasks {
all().each { task ->
task.builtins {
remove java
javanano {
// Options added to --javanano_out
option 'ignore_services=true'
option 'enum_style=java'
option 'generate_intdefs=true'
}
}
}
}
}
dependencies {
// ...
compile 'io.grpc:grpc-protobuf-nano:1.0.2'
}
The generated output:
// Generated by the protocol buffer compiler. DO NOT EDIT!
package com.package.my.nano;
#SuppressWarnings("hiding")
public final class PlayerCards extends
com.google.protobuf.nano.MessageNano {
private static volatile PlayerCards[] _emptyArray;
public static PlayerCards[] emptyArray() {
// Lazily initializes the empty array
if (_emptyArray == null) {
synchronized (
com.google.protobuf.nano.InternalNano.LAZY_INIT_LOCK) {
if (_emptyArray == null) {
_emptyArray = new PlayerCards[0];
}
}
}
return _emptyArray;
}
// optional int64 playerId = 1;
public long playerId;
// repeated int32 cards = 2;
public int[] cards;
public PlayerCards() {
clear();
}
public PlayerCards clear() {
playerId = 0L;
cards = com.google.protobuf.nano.WireFormatNano.EMPTY_INT_ARRAY;
cachedSize = -1;
return this;
}
#Override
public void writeTo(com.google.protobuf.nano.CodedOutputByteBufferNano output)
throws java.io.IOException {
if (this.playerId != 0L) {
output.writeInt64(1, this.playerId);
}
if (this.cards != null && this.cards.length > 0) {
for (int i = 0; i < this.cards.length; i++) {
output.writeInt32(2, this.cards[i]);
}
}
super.writeTo(output);
}
#Override
protected int computeSerializedSize() {
int size = super.computeSerializedSize();
if (this.playerId != 0L) {
size += com.google.protobuf.nano.CodedOutputByteBufferNano
.computeInt64Size(1, this.playerId);
}
if (this.cards != null && this.cards.length > 0) {
int dataSize = 0;
for (int i = 0; i < this.cards.length; i++) {
int element = this.cards[i];
dataSize += com.google.protobuf.nano.CodedOutputByteBufferNano
.computeInt32SizeNoTag(element);
}
size += dataSize;
size += 1 * this.cards.length;
}
return size;
}
#Override
public PlayerCards mergeFrom(
com.google.protobuf.nano.CodedInputByteBufferNano input)
throws java.io.IOException {
while (true) {
int tag = input.readTag();
switch (tag) {
case 0:
return this;
default: {
if (!com.google.protobuf.nano.WireFormatNano.parseUnknownField(input, tag)) {
return this;
}
break;
}
case 8: {
this.playerId = input.readInt64();
break;
}
case 16: {
int arrayLength = com.google.protobuf.nano.WireFormatNano
.getRepeatedFieldArrayLength(input, 16);
int i = this.cards == null ? 0 : this.cards.length;
int[] newArray = new int[i + arrayLength];
if (i != 0) {
java.lang.System.arraycopy(this.cards, 0, newArray, 0, i);
}
for (; i < newArray.length - 1; i++) {
newArray[i] = input.readInt32();
input.readTag();
}
// Last one without readTag.
newArray[i] = input.readInt32();
this.cards = newArray;
break;
}
case 18: {
int length = input.readRawVarint32();
int limit = input.pushLimit(length);
// First pass to compute array length.
int arrayLength = 0;
int startPos = input.getPosition();
while (input.getBytesUntilLimit() > 0) {
input.readInt32();
arrayLength++;
}
input.rewindToPosition(startPos);
int i = this.cards == null ? 0 : this.cards.length;
int[] newArray = new int[i + arrayLength];
if (i != 0) {
java.lang.System.arraycopy(this.cards, 0, newArray, 0, i);
}
for (; i < newArray.length; i++) {
newArray[i] = input.readInt32();
}
this.cards = newArray;
input.popLimit(limit);
break;
}
}
}
}
public static PlayerCards parseFrom(byte[] data)
throws com.google.protobuf.nano.InvalidProtocolBufferNanoException {
return com.google.protobuf.nano.MessageNano.mergeFrom(new PlayerCards(), data);
}
public static PlayerCards parseFrom(
com.google.protobuf.nano.CodedInputByteBufferNano input)
throws java.io.IOException {
return new PlayerCards().mergeFrom(input);
}
}
Proved a missing documentation.
Googling around I noticed the following property in a pom (!?) file generate_equals=true.
After adding this to gradle generation options the methods equals, hashcode generated!
ie.
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.1.0'
}
generateProtoTasks {
all().each { task ->
task.builtins {
remove java
javanano {
// Options added to --javanano_out
option 'ignore_services=true'
option 'enum_style=java'
option 'generate_intdefs=true'
option 'generate_equals=true' // <--- this one
}
}
}
}
}
In my application i want to check whether the user have entered valid card number for that i have used LUHN algorithm.I have created it as method and called in the mainactivity. But even if i give valid card number it shows invalid.While entering card number i have given spaces in between i didn't know because of that its not validating properly. Please help me in finding the mistake.
CreditcardValidation.java
public class CreditcardValidation {
String creditcard_validation,msg;
//String mobilepattern;
public static boolean isValid(long number) {
int total = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number);
if ((total % 10 == 0) && (prefixMatched(number, 1) == true) && (getSize(number)>=16 ) && (getSize(number)<=19 )) {
return true;
} else {
return false;
}
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int) (number / 10);
return firstDigit + secondDigit;
}
}
public static int sumOfOddPlace(long number) {
int result = 0;
while (number > 0) {
result += (int) (number % 10);
number = number / 100;
}
return result;
}
public static int sumOfDoubleEvenPlace(long number) {
int result = 0;
long temp = 0;
while (number > 0) {
temp = number % 100;
result += getDigit((int) (temp / 10) * 2);
number = number / 100;
}
return result;
}
public static boolean prefixMatched(long number, int d) {
if ((getPrefix(number, d) == 5)
|| (getPrefix(number, d) == 4)
|| (getPrefix(number, d) == 3)) {
if (getPrefix(number, d) == 4) {
System.out.println("\nVisa Card ");
} else if (getPrefix(number, d) == 5) {
System.out.println("\nMaster Card ");
} else if (getPrefix(number, d) == 3) {
System.out.println("\nAmerican Express Card ");
}
return true;
} else {
return false;
}
}
public static int getSize(long d) {
int count = 0;
while (d > 0) {
d = d / 10;
count++;
}
return count;
}
public static long getPrefix(long number, int k) {
if (getSize(number) < k) {
return number;
} else {
int size = (int) getSize(number);
for (int i = 0; i < (size - k); i++) {
number = number / 10;
}
return number;
}
}
public String creditcardvalidation(String creditcard)
{
Scanner sc = new Scanner(System.in);
this.creditcard_validation= creditcard;
long input = 0;
input = sc.nextLong();
//long input = sc.nextLong();
if (isValid(input) == true) {
Log.d("Please fill all the column","valid");
msg="Valid card number";
}
else{
Log.d("Please fill all the column","invalid");
msg="Please enter the valid card number";
}
return msg;
}
}
MainActivity.java
addcard.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(v.getId()==R.id.btn_add)
{
creditcard= card_number.getText().toString();
cv = new CreditcardValidation();
String mob = cv.creditcardvalidation(creditcard);
Toast.makeText(getActivity(), mob, 1000).show();``
refer code below
EditText cardNumber=(EditText)findViewById(R.id.cardNumber);
String CreditCardType = "Unknown";
/// Remove all spaces and dashes from the passed string
String CardNo ="9292304336";///////cardNumber.getText().toString();
CardNo = CardNo.replace(" ", "");//removing empty space
CardNo = CardNo.replace("-", "");//removing '-'
twoDigit=Integer.parseInt(CardNo.substring(0, 2));
System.out.println("----------twoDigit--"+twoDigit);
fourDigit=Integer.parseInt(CardNo.substring(0, 4));
System.out.println("----------fourDigit--"+fourDigit);
oneDigit=Integer.parseInt(Character.toString(CardNo.charAt(0)));
System.out.println("----------oneDigit--"+oneDigit);
boolean cardValidation=false;
// 'Check that the minimum length of the string isn't <14 characters and -is- numeric
if(CardNo.length()>=14)
{
cardValidation=cardValidationMethod(CardNo);
}
boolean cardValidationMethod(String CardNo)
{
//'Check the first two digits first,for AmericanExpress
if(CardNo.length()==15 && (twoDigit==34 || twoDigit==37))
return true;
else
//'Check the first two digits first,for MasterCard
if(CardNo.length()==16 && twoDigit>=51 && twoDigit<=55)
return true;
else
//'None of the above - so check the 'first four digits collectively
if(CardNo.length()==16 && fourDigit==6011)//for DiscoverCard
return true;
else
if(CardNo.length()==16 || CardNo.length()==13 && oneDigit==4)//for VISA
return true;
else
return false;
}
also u can refer this demo project
Scanner.nextLong() will stop reading as spaces (or other non-digit characters) are encountered.
For instance, if the input is 1234 567 .. then nextLong() will only read 1234.
However, while spaces in the credit-card will [likely] cause it to fail LUHN validation with the above code, I make no guarantee that removing the spaces would make it pass - I'd use a more robust (and well-tested) implementation from the start. There is no need to rewrite such code.