Alternative codeing instead of "if else" logic for Android - android

I create a script that displays the results depending on the selected options.
I need: A, B, C, D (0,1,-1)
int A = 0;
int B = 0;
int C = 0;
int D = 0;
Ansver will be one of 16 combination.
if A = 1 = A1;
if A = -1 = A2;
if B = 1 = B1;
if B = -1 B2;
if C = 1 = C1;
If C = -1 = C2;
If D = 1 = D1;
if D = -1 = D1;
A1;B1;C1;D1 = Nr1
A1;B1;C1;D2 = Nr2
A1;B1;C2;D1 = Nr3
A1;B1;C2;D2 = Nr4
A1;B2;C1;D1 = Nr5
A1;B2;C1;D2 = Nr6
A1;B2;C2;D1 = Nr7
A1;B2;C2;D2 = Nr8
A2;B1;C1;D1 = Nr9
A2;B1;C1;D2 = Nr10
A2;B1;C2;D1 = Nr11
A2;B1;C2;D2 = Nr12
A2;B2;C1;D1 = Nr13
A2;B2;C1;D2 = Nr14
A2;B2;C2;D1 = Nr15
A2;B2;C2;D2 = Nr16
I want to show the potential variants.
When you press the combination of: A1, B1 = "Nr1,Nr2,Nr3,Nr4"
When you press the combination of: A1, D1 = "Nr1,Nr3,Nr5,Nr7"
Later will be more variables E, F, G, H .... etc. But the answers will only 16th
What could be the logic, I'm a little stuck?
If / Else seems to be too long.
Example if/else:
if (A == 1) {
if (B == 1) {
if (C == 1) {
if (D == 1) {
scoreTeamA = "Nr1"; //A1,B1,C1,D1
} else if (D == -1) {
scoreTeamA = "Nr2"; //A1,B1,C1,D2
} else scoreTeamA = "Nr1, Nr2"; //A1,B1,C1
} else if (B == 1) {
if (D == 1) {
scoreTeamA = "Nr3"; //A1,B1,C1,D1
} else if (D == -1) {
scoreTeamA = "Nr4"; //A1,B1,C1,D2
} else scoreTeamA = "Nr3,Nr4"; //A1,B1,C2
} else scoreTeamA = "Nr1,Nr2,Nr3,Nr4"; //A1,B1
} else if (B == -1) {
scoreTeamA = "Nr5,Nr6,Nr7,Nr8";//A1,B2
} else
scoreTeamA = "Nr1,Nr2,Nr3,Nr4,Nr5,Nr6,Nr7,Nr8"; //A1
} else if (A == -1) {
scoreTeamA = "Nr9,Nr10,Nr11,Nr12,Nr13,Nr14,Nr15,Nr16"; //A2
}

Some of the alternatives that come to mind:
A long chain of if...else statements.
switch statements. This won't be much better than if...else, though.
A data structure, such as a Map.
A custom class hierarchy. Often a switch statement can be replaced by polymorphism. This is highly dependent on the specifics of what you are really doing.

For that you are using switch-case.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Related

Luxand API for similarity on android

I'm going to use Luxand api for detect persons.
Scenario:
1- At the first on register activity persons sit in front of the camera and take pictures and templates save on sqlite database. also personal information will be save;
2- After that On detect activity one of them sit in front of the camera and take Auto detection and find same temp and show person information.(similarity is 96%)
my problem:Unfortunately too times detection is wrong and two different people’s templates will be recognized as the same person.
My Code:
1- Register activity for register form
for (int i = 0; i < MAX_FACES; ++i) {
if (rects[i] != null && rects[i].x1 <= x && x <= rects[i].x2 && rects[i].y1 <= y && y <= rects[i].y2 + 30) {
mTouchedID = IDs[i];
mTouchedIndex = i;
temp = (byte[]) ImageFrameFaceIDTemps.get(mTouchedID);
if (mPreview != null) {
onTouchMode = true;
try {
requesting name on tapping the face
if (faceSelected != null) {
faceSelected.Selected(temp, data);
}
} finally {
onTouchMode = false;
}
}
break;
}
2- Detection activity for match form
public int RetrievePersonDetection(byte[] template, float[] maxSimilarity_UnderAccepted, float[] maxSimilarityArray) {
if (IDTemps == null || IDTemps.size() == 0) {
return 0;
}
int person = 0;
FSDK_FaceTemplate currentFaceTemp = new FSDK_FaceTemplate();
currentFaceTemp.template = template;
float[] similarityArray = new float[1];
float maxSimilarity = 0;
float MatchingThreshold[] = new float[1];
FSDK.GetMatchingThresholdAtFRR(LocalSetting.MIN_ACCEPTED_SIMILAITY, MatchingThreshold);
for (int i = 0; i < IDTemps.size(); i++) {
long key = IDTemps.keyAt(i);
FSDK_FaceTemplate faceTemp = (FSDK_FaceTemplate) IDTemps.get(key);
int result = FSDK.MatchFaces(currentFaceTemp, faceTemp, similarityArray);
if (result == 0) {
if (maxSimilarity < similarityArray[0] && similarityArray[0] >= MatchingThreshold[0]) {
maxSimilarity = similarityArray[0];
person = (int) key;
maxSimilarityArray[0] = similarityArray[0];
FSDK_FaceTemplate currentFaceTemp2 = new FSDK_FaceTemplate();
}
else if (maxSimilarity_UnderAccepted[0] < similarityArray[0]) {
maxSimilarity_UnderAccepted[0] = similarityArray[0];
}
}
}
return person;
}
I don't no what's my problem? why return wrong person and 2 person similarity is 96%

Comparison of app version

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

get the button color inside a function

I want to get the background color of a button inside a function. I want to check the equality of the color to perform some action. I use PaintDrawer but its not working.. app crashing... this is my function
void moves(Button bn)
{
if(flag==1)
{
// Toast.makeText(getApplicationContext(),"Exception",Toast.LENGTH_LONG).show();
if (bn.getText().equals("RED") && plyr==1 && mov==0|| mov==1 && bn.getText().equals("RED"))
{
rembr = bn;
Toast.makeText(getApplicationContext(),"Exception"+rembr.getText(),Toast.LENGTH_LONG).show();
mov = 1;
}
else if (bn.getText().equals("GREEN") && plyr == 2 && mov == 0 || mov==1 && bn.getText().equals("GREEN"))
{
Toast.makeText(getApplicationContext(),"Exception GREEN",Toast.LENGTH_LONG).show();
rembr = bn;
mov = 1;
}
else if (mov == 1 && bn.getText() != "RED" && bn.getText() != "GREEN")
{
/*check
adjsnt(lbl, rembr);
end check*/
falsemov=adjsnt(bn, rembr);
if (falsemov == 1)
{
falsemov = 0;
}
else
{
mov = 0;
PaintDrawable drawable = (PaintDrawable) rembr.getBackground();
int temp = drawable.getPaint().getColor();
bn.setBackgroundColor(temp);
bn.setText(rembr.getText());
rembr.setBackgroundColor(Color.LTGRAY);
if (plyr == 1)
{
plyr = 2;
t1.setBackgroundColor(Color.LTGRAY);
t2.setBackgroundColor(Color.GREEN);
}
else
{
plyr = 1;
t2.setBackgroundColor(Color.LTGRAY);
t1.setBackgroundColor(Color.RED);
}
}
}
}
}
Any help would be highly appretiated.
use Color Drawable class instead of paint
ColorDrawable buttonColor = (ColorDrawable) button.getBackground();
int colorId = buttonColor.getColor();

Android EditText handling String.valueOf(double) always give NaN when input equals " "

There are 3 EditText, 1st Price input,2nd Percentage, 3rd Result. I am trying to calculate EditText inputs using onFocusChangeListener.
The Code:
etPercen.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
OnFocusChangedPercenCalculator();
}
}
});
etresult.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
OnFocusChangedResultCalculator();
}
}
});
and
public void OnFocusChangedPercenCalculator() {
String text1 = String.valueOf(etPrice.getNumericValue()).toString();
String text2 = etPercen.getText().toString();
String text3 = String.valueOf(etresult.getNumericValue()).toString();
double input1 = 0;
double input2 = 0;
int i = 0;
if (text1.length() > 0 || text2.length() > 0 || text3.length() > 0)
input1 = Double.parseDouble(text1);
input2 = Double.parseDouble(text2);
if (text1.length() != 0 ){
if(text2.length() != 0) {
double output = (input1 * input2) / 100;
e = String.valueOf(output);
etresult.setText("" + e);
} else if (text2.length() ==0 || text2.matches("")){
etresult.setText(i+"");
}
}else if(text1.length() == 0){
if(text2.length() != 0) {
etresult.setText(i+"");
} else if (text2.length() ==0 || text2.matches("")){
etresult.setText(i+"");
}
}
}
public void OnFocusChangedResultCalculator() {
String text1 = String.valueOf(etPrice.getNumericValue()).toString();
String text2 = etPercen.getText().toString();
String text3 = String.valueOf(etresult.getNumericValue()).toString();
double input1 = 0;
double input3 = 0;
int i = 0;
if (text1.length() > 0 || text2.length() > 0 || text3.length() > 0)
input1 = Double.parseDouble(text1);
input3 = Double.parseDouble(text3);
if (text1.length() != 0 ){
if(text3.length() != 0) {
double output = (input3 / input1) * 100;
e = String.valueOf(output);
etPercen.setText("" + e);
} else if (text3.length() ==0 || text3.matches("")){
etPercen.setText(i);
}
}else if(text1.length() == 0){
if(text3.length() != 0) {
etPercen.setText(i);
} else if (text3.length() ==0 || text3.matches("")){
etPercen.setText(i);
}
}else if (input3 > input1){
etPercen.setText(100);
}
}
What i want to do is 2nd and 3rd EditTexts looking each other. I mean when the user change focus from 2nd/3rd editText then the calculation will begin in an instant. The idea is to make the 2nd one calculate and put the result on the 3rd and make the 3rd one calculate and put the result on 2nd. It depends on the user if he/she wants to change fill/change the value (lets say the price is 10000, the user want to know whats the 20% of it, or the user want the other way around, whats the % of 20000 from 10000). Thats my expectation, but when we emptied the 1st and 3rd edittext the output of the 2nd one will be NaN. How to handle this? i mean avoid the result become NaN?
Ok, I refactored the second method to illustrate what I was talking about. Should be working.
public void OnFocusChangedResultCalculator() {
String text1 = etPrice.getText().toString().trim();
String text2 = etPercen.getText().toString().trim();
String text3 = etresult.getText().toString().trim();
double input1 = text1.length()>0 ? Double.parseDouble(text1) : 0;
double input3 = text3.length()>0 ? Double.parseDouble(text3) : 0;
if (input3 > input1){
etPercen.setText(100);
return;
}
double output = (input3 / input1) * 100;
etPercen.setText(output);
}
UPDATE
public void OnFocusChangedResultCalculator() {
String text1 = String.valueOf(etPrice.getNumericValue()).toString().trim();
String text2 = etPercen.getText().toString().trim();
String text3 = String.valueOf(etresult.getNumericValue()).toString().trim();
double input1 = text1.length()>0 ? Double.parseDouble(text1) : 0;
double input3 = text3.length()>0 ? Double.parseDouble(text3) : 0;
if (input3 > input1){
etPercen.setText(Integer.toString(100));
etresult.setText(Double.toString(input1));
return;
}
double output = (input3 / input1) * 100;
etPercen.setText(Double.toString(output));
}
The NaN error is just Not-a-Number.
I think you need to change your condition
From
if (text1.length() != 0 )
To
if (text1.length() > 0 )
If length is -1 or 1 your if condition will still be satisfied.
By using the operator > instead of != you will be assured that
text1 is not empty.
You are getting NaN because "" and " " are not a number
Instead of using
if (text1.length() != 0 )
use
if(!TextUtils.isEmpty(text1.toString().trim()))
This is an android String utility to perform null and empty check on any String.
Also you probably should to mention in your layout xml that your inputType is number

Check for Empty EditText fails

I've tried everything from matching strings, to using TextUtils.isEmpty. No matter what I do, b is always true (even when edittext is purposely left blank) which allows the code to proceed to the next steps (this is a Madlib app).
If anybody can see why the code isn't properly checking for blank edittext's and displaying the Please Fill In All Fields" toast when one is blank, it would be very appreciated. Thanks. Sorry for the messy code.
public class Madlibs extends Fragment {
switch (((MainActivity) getActivity()).getStory()) {
case 0:
output.setText(Stories[0]);
title = Titles[0];
actionBar.setTitle(title);
editTextNumber = 12;
addEdit = new BootstrapEditText[editTextNumber];
for (int i = 0; i < addEdit.length; i++) {
addEdit[i] = new BootstrapEditText(getActivity());
l_layout.addView(addEdit[i]);
params.setMargins(0, 20, 0, 20);
addEdit[i].setLayoutParams(params);
addEdit[i].setId(i);
}
addEdit[0].setHint("Name of Sickness");
addEdit[1].setHint("Adjective");
addEdit[2].setHint("Name of Boy");
addEdit[3].setHint("Body Part");
addEdit[4].setHint("Color");
addEdit[5].setHint("Animal");
addEdit[6].setHint("Article of Clothing");
addEdit[7].setHint("Relative");
addEdit[8].setHint("Adjective");
addEdit[9].setHint("Article of Clothing");
addEdit[10].setHint("Body Part");
addEdit[11].setHint("Number");
break;
case 1:
// fragment = new Madlibs();
break;
case 2:
// fragment = new MadlibsSaved();
}
convert = (BootstrapButton) view.findViewById(R.id.convert);
convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i;
String s;
for (i = 0; i < addEdit.length; i++) {
s = addEdit[i].getText().toString().trim();
if (s.isEmpty() || s.length() == 0 || s.equals("") || s == null) {
b = false;
}
else
{
b = true;
}
}
if (b = true) {
gather();
postIt();
outputText = output.getText().toString();
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Please Fill In All Fields", Toast.LENGTH_LONG)
.show();
}
}
});
Your problem is here
if (b = true) { // HERE
gather();
postIt();
outputText = output.getText().toString();
}
You are using b = true which sets b to true, and since you are able to do this successfully, the conditional evaluates to true every time. What you want instead is the comparison operator ==
if (b == true) {
gather();
postIt();
outputText = output.getText().toString();
}
or even better, since the variable you are comparing is a boolean, you could just use
if (b) {} //This is "if b is true..."
if (!b) {} //This is "if b is false..."
You can see another one of my answers about this here.
for (i = 0; i < addEdit.length; i++) {
s = addEdit[i].getText().toString().trim();
if (s.isEmpty() || s.length() == 0 || s.equals("") || s == null) {
b = false;
}
else {
b = true;
}
}
For Loop ends here and the following is outside the For Loop :
if (b = true) {
gather();
postIt();
outputText = output.getText().toString();
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Please Fill In All Fields", Toast.LENGTH_LONG)
.show();
}
Problem 1 :
if(b == true) {
}
Problem 2 :
Now, suppose edittext 1 is empty, b is set to true but then it'll straightaway move ahead in the loop to edittext 2 to the last edittext which are not empty hence it'll set b to false again. You'll need to put the check inside the for loop.

Categories

Resources