I'm trying to get the int value from a textView, the value inside will always be a number just in string, I set it like this
int randomNumber = rng.nextInt(6) + 1;
switch (randomNumber) {
case 1:
imageViewDice.setImageResource(R.drawable.dice1);
textView.setText("Tiraste un 1!");
if (player1.getText().equals("")) {
player1.setText("1");
} else {
player2.setText("1");
}
break;
//rest of cases 2, 3, 4, 5, & 6
I need the int value of this to be able to compare then to see which player (1 or 2) has the highest number, something like this
//this doesnt work
int value1 = Integer.parseInt(player1.getText().toString());
int value2 = Integer.parseInt(player2.getText().toString());
if (value1 > value2) {
result.setText("Jugador 1");
} else if (value1 < value2) {
result.setText("Jugador 2");
} else {
result.setText("Empate!");
}
What is the correct way to get the value so that the comparison can be made?
if you set static, you can very easily read in various classes:
player1.setText(Fraction.getP1()+"");
player2.setText(Fraction.getP2()+"");
if(Fraction.getP1()>Fraction.getP2())
result.setText("Jugador 1");
new class
public class Fraction {
private static int p1=0;
private static int p2=0;
public static int getP1(){
return p1;
}
public static int getP2(){
return p2;
}
public static void setP1(int p1fraction){
Fraction.p1 = p1fraction; //Fraction is your class name
}
public static void setP2(int p2fraction){
p2 = p2fraction;
}
}
I'm new to Android. I'm trying to develop my first calculator. My calculator output is good, but I'm trying to make some changes to it. Please suggest. My output is 2+2=4.0 How can I get 4 if I put 2+2 and 4.0 when I put 2.8+1.2.
Also, please help me out in trying to figure out how can i keep on adding till i press =.
My code that I'm looking at is below:
private View.OnClickListener buttonClickListerner = new
View.OnClickListener() {
float r;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.clear:
screen.setText("");
operator.setText("");
FirstNum= 0;
showtext.setText("");
break;
case R.id.buttonAdd:
mMath("+");
operator.setText("+");
showtext.setText(String.valueOf(FirstNum));
break;
case R.id.buttonMinus:
mMath("-");
operator.setText("-");
break;
case R.id.buttonMul:
mMath("*");
operator.setText("*");
break;
case R.id.buttonequal:
mResult();
break;
case R.id.buttonDiv:
mMath("/");
operator.setText("/");
break;
case R.id.buttonPercent:
mMath("%");
r = FirstNum / 100;
showtext.setText("[" + String.valueOf(FirstNum) + "%" + "]");
screen.setText(String.valueOf(r));
break;
default:
String num = ((Button) v).getText().toString();
getKeyboard(num);
break;
}
}
};
public void mMath(String str){
FirstNum = Float.parseFloat(screen.getText().toString());
operation = str;
screen.setText("");
}
public void getKeyboard(String str){
String CurrentScreen = screen.getText().toString();
if(CurrentScreen.equals("0"))
CurrentScreen = "";
CurrentScreen = CurrentScreen + str;
screen.setText(CurrentScreen);
String ExScreen = CurrentScreen;
screen.setText(ExScreen);
}
public void mResult(){
float SecondNum = Float.parseFloat(screen.getText().toString());
float ThirdNum = Float.parseFloat(screen.getText().toString());
float result = 0;
//float exresult = result;
if(operation.equals("+")){
result = FirstNum + SecondNum;
// exresult = result + ThirdNum;
}
if(operation.equals("-")){
result = FirstNum - SecondNum;
//exresult = result - ThirdNum;
}
if(operation.equals("*")){
result = FirstNum * SecondNum;
//exresult = result * ThirdNum;
}
if(operation.equals("/")){
result = FirstNum / SecondNum;
//exresult = result / ThirdNum;
}
screen.setText(String.valueOf(result));
//screen.setText(String.valueOf(exresult));
showtext.setText(String.valueOf(FirstNum + operation + SecondNum));
//showtext.setText(String.valueOf(FirstNum + operation + SecondNum +
operation + ThirdNum));
}
}
I guess you should do your calculations as double and then before setting the output to TextView (or whatever you are using), check for the output if int or not and then decide which form of output to set to the TextView.
if ((variable == Math.floor(variable)) && !Double.isInfinite(variable)) {
// integral type
}
See this
Edit:
The idea is to check that fractional part of the number is 0 (i.e.) the number is integer.
You may also Use these conditions [if true then variable is an Integer]
// check if
variable == Math.ceil(variable)
or
// check if
variable == Math.round(variable)
Also Math.round(float f) will return the interger form of the number!
To add multiple item first set up an array with a size of how long the user can input and then loop through each array adding them equivalently... i know this is a vague answer but you can ask me if anything is unclear and also an up vote would be nice. you got the right idea for the cases just try the following code
// array to sum
int[] numbers = new int[]{ 10, 10, 10, 10};
int sum = 0;
for (int i=0; i < numbers.length ; i++) {
sum = sum + numbers[i];
}
System.out.println("Sum value of array elements is : " + sum);
}
So I have a Custom ListView I made for Xamarin-Android that takes data from a list of employee shifts and turns them into rows. Some of the data is being reported incorrectly right away, (showing shifts they dont have), and when scrolling around the data is changing periodically.
Essentially I pass the adapter a List of Employees, each having a List type that holds a start and end time. The adapter loops through each shift, uses a switch to route whatever day it is for to the right TextViews, then pastes the data. For some reason the data is not displaying correctly for some of the rows, but others are fine. And when you click into the row (I have a separate view for editing the data) the data comes up correctly reflecting what it is supposed to. I have tried to step through and figure out what is going on but when stepping it is showing that the rows are being returned correctly.
On top of the data not displaying correctly, when scrolling up and down, when a row goes off screen it is sometimes coming back with different data.
Here is the adapter code:
using System;
using System.Collections.Generic;
using Android.Content;
using Android.Views;
using Android.Widget;
namespace MaydSchedulerApp
{
class ScheduleAdapter : BaseAdapter<EmployeeScheduleWrapper>
{
private List<EmployeeScheduleWrapper> mItems;
private Context mContext;
private bool sun = false, mon = false, tue = false, wed = false, thu = false, fri = false, sat = false;
public ScheduleAdapter(Context context, List<EmployeeScheduleWrapper> items)
{
mItems = items;
mContext = context;
}
public override int Count
{
get
{
return mItems.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public override EmployeeScheduleWrapper this[int position]
{
get
{
return mItems[position];
}
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if (row == null)
{
row = LayoutInflater.From(mContext).Inflate(Resource.Layout.ScheduleListView, null, false);
}
TextView txtName = row.FindViewById<TextView>(Resource.Id.txtScheduleName);
txtName.Text = mItems[position].lName + ", " + mItems[position].fName;
TextView txtPosition = row.FindViewById<TextView>(Resource.Id.txtSchedulePosition);
txtPosition.Text = CoreSystem.GetPositionName(mItems[position].position);
TextView txtSunday = row.FindViewById<TextView>(Resource.Id.txtSun);
TextView txtMonday = row.FindViewById<TextView>(Resource.Id.txtMon);
TextView txtTuesday = row.FindViewById<TextView>(Resource.Id.txtTue);
TextView txtWednesday = row.FindViewById<TextView>(Resource.Id.txtWed);
TextView txtThursday = row.FindViewById<TextView>(Resource.Id.txtThu);
TextView txtFriday = row.FindViewById<TextView>(Resource.Id.txtFri);
TextView txtSaturday = row.FindViewById<TextView>(Resource.Id.txtSat);
for (int i = 0; i < mItems[position].shiftList.Count; i++)
{
switch (mItems[position].shiftList[i].date)
{
case DayOfWeek.Sunday:
txtSunday.Text = mItems[position].shiftList[i].startShift.ToString() + "00 - " + mItems[position].shiftList[i].endShift.ToString() + "00";
sun = true;
break;
case DayOfWeek.Monday:
txtMonday.Text = mItems[position].shiftList[i].startShift.ToString() + "00 - " + mItems[position].shiftList[i].endShift.ToString() + "00";
mon = true;
break;
case DayOfWeek.Tuesday:
txtTuesday.Text = mItems[position].shiftList[i].startShift.ToString() + "00 - " + mItems[position].shiftList[i].endShift.ToString() + "00";
tue = true;
break;
case DayOfWeek.Wednesday:
txtWednesday.Text = mItems[position].shiftList[i].startShift.ToString() + "00 - " + mItems[position].shiftList[i].endShift.ToString() + "00";
wed = true;
break;
case DayOfWeek.Thursday:
txtThursday.Text = mItems[position].shiftList[i].startShift.ToString() + "00 - " + mItems[position].shiftList[i].endShift.ToString() + "00";
thu = true;
break;
case DayOfWeek.Friday:
txtFriday.Text = mItems[position].shiftList[i].startShift.ToString() + "00 - " + mItems[position].shiftList[i].endShift.ToString() + "00";
fri = true;
break;
case DayOfWeek.Saturday:
txtSaturday.Text = mItems[position].shiftList[i].startShift.ToString() + "00 - " + mItems[position].shiftList[i].endShift.ToString() + "00";
sat = true;
break;
}
}
if (!sun)
txtSunday.Text = "Off";
if (!mon)
txtMonday.Text = "Off";
if (!tue)
txtTuesday.Text = "Off";
if (!wed)
txtWednesday.Text = "Off";
if (!thu)
txtThursday.Text = "Off";
if (!fri)
txtFriday.Text = "Off";
if (!sat)
txtSaturday.Text = "Off";
return row;
}
}
}
And here is the code for the EmployeeScheduleWrapper
using System;
using System.Collections;
using System.Collections.Generic;
namespace MaydSchedulerApp
{
public class EmployeeScheduleWrapper
{
public string lName, fName;
public int employee;
public int position;
public int hourTarget;
public int skill;//This is to minimize callbacks to the main emp later
public int scheduledHours;
//The availability is copied onto this so that it can be modified without effecting the set availability in the employee type
public Availability availability = new Availability();
public bool availabilityModified = false;
public List<Shift> shiftList = new List<Shift>();
public EmployeeScheduleWrapper() { }
public EmployeeScheduleWrapper(Employee emp)
{
lName = emp.empLastName;
fName = emp.empFirstName;
employee = emp.empID;
position = emp.position;
skill = emp.skillLevel;
hourTarget = emp.hourTarget;
scheduledHours = 0;
//availability = emp.availability;//Dont init this unless its changed and needs to be saved
availabilityModified = false;
}
public void SetTempAvailability(Availability avail)//TODO add check for when avail last changed to warn user if availability is no longer useful
{
availability = avail;
availabilityModified = true;
}
public void PermanentAvailabilityChange(Availability avail)
{
availability = avail;
availabilityModified = false;//since were using the permanent change
EmployeeStorage.GetEmployee(employee).availability = avail;
}
public Availability GetEntireAvail()
{
if (availabilityModified)
return availability;
else
{//This fixes the direct memory interaction when modifying temp availability
availability = new Availability(EmployeeStorage.GetEmployee(employee).availability);
return availability;
}
}
public bool GetAvailability(int day)
{
if (availabilityModified)
{
switch (day)
{
case 0:
return availability.sunday.available;
case 1:
return availability.monday.available;
case 2:
return availability.tuesday.available;
case 3:
return availability.wednesday.available;
case 4:
return availability.thursday.available;
case 5:
return availability.friday.available;
case 6:
return availability.saturday.available;
default:
Console.WriteLine("Invalid case chosen! :: EmployeeManagement/Employee.cs :: GetAvailability(int day): Invalid Value for Day Thrown! :: Returning false!");
break;
}
return false;
}
else
{
return EmployeeStorage.GetEmployee(employee).GetAvailability(day);
}
}
}
}
You need to reset the view to empty data.
That is, the list view will re use the convertview to optimise memory. During that time, the listview will give back the previously used convert view which contains previous data. So you need to reset the data in the getView()
That is :
txtSunday.Text = "";
txtMonday.Text = "";
txtTuesday.Text = "";
txtWednesday.Text = "";
txtThursday.Text = "";
txtFriday.Text = "";
txtSaturday.Text = "";
after the switch case statement
How to Create Password Strength checker with seekbar in android ?
You can use https://github.com/VenomVendor/Password-Strength-Checker for your requirement
or use TextWatcher for checking EditText length .Like this way
public void afterTextChanged(Editable s)
{
if(s.length()==0)
textViewPasswordStrengthIndiactor.setText("Not Entered");
else if(s.length()<6)
textViewPasswordStrengthIndiactor.setText("EASY");
else if(s.length()<10)
textViewPasswordStrengthIndiactor.setText("MEDIUM");
else if(s.length()<15)
textViewPasswordStrengthIndiactor.setText("STRONG");
else
textViewPasswordStrengthIndiactor.setText("STRONGEST");
if(s.length()==20)
textViewPasswordStrengthIndiactor.setText("Password Max Length Reached");
}
};
Demo Help .
afterTextChanged (Editable s) - This method is called when the text
has been changed. Because any changes you make will cause this method
to be called again recursively, you have to be watchful about
performing operations here, otherwise it might lead to infinite loop.
create a rule engine for password strength, may be a simple function which returns strength when you pass a string to it.
use a TextWatcher on your password edit text and pass any string entered through your rules.
Use returned strength value from your rule engine to set progress value and progress color of your progress bar.
https://github.com/yesterselga/password-strength-checker-android
is a really good example. I changed the code not to use string values. Instead of it I am using values from 0-4. here is the code
public enum PasswordStrength
{
WEAK(0, Color.RED), MEDIUM(1, Color.argb(255, 220, 185, 0)), STRONG(2, Color.GREEN), VERY_STRONG(3, Color.BLUE);
//--------REQUIREMENTS--------
static int REQUIRED_LENGTH = 6;
static int MAXIMUM_LENGTH = 6;
static boolean REQUIRE_SPECIAL_CHARACTERS = true;
static boolean REQUIRE_DIGITS = true;
static boolean REQUIRE_LOWER_CASE = true;
static boolean REQUIRE_UPPER_CASE = true;
int resId;
int color;
PasswordStrength(int resId, int color)
{
this.resId = resId;
this.color = color;
}
public int getValue()
{
return resId;
}
public int getColor()
{
return color;
}
public static PasswordStrength calculateStrength(String password)
{
int currentScore = 0;
boolean sawUpper = false;
boolean sawLower = false;
boolean sawDigit = false;
boolean sawSpecial = false;
for (int i = 0; i < password.length(); i++)
{
char c = password.charAt(i);
if (!sawSpecial && !Character.isLetterOrDigit(c))
{
currentScore += 1;
sawSpecial = true;
}
else
{
if (!sawDigit && Character.isDigit(c))
{
currentScore += 1;
sawDigit = true;
}
else
{
if (!sawUpper || !sawLower)
{
if (Character.isUpperCase(c))
sawUpper = true;
else
sawLower = true;
if (sawUpper && sawLower)
currentScore += 1;
}
}
}
}
if (password.length() > REQUIRED_LENGTH)
{
if ((REQUIRE_SPECIAL_CHARACTERS && !sawSpecial) || (REQUIRE_UPPER_CASE && !sawUpper) || (REQUIRE_LOWER_CASE && !sawLower) || (REQUIRE_DIGITS && !sawDigit))
{
currentScore = 1;
}
else
{
currentScore = 2;
if (password.length() > MAXIMUM_LENGTH)
{
currentScore = 3;
}
}
}
else
{
currentScore = 0;
}
switch (currentScore)
{
case 0:
return WEAK;
case 1:
return MEDIUM;
case 2:
return STRONG;
case 3:
return VERY_STRONG;
default:
}
return VERY_STRONG;
}
}
and how to use it:
if(PasswordStrength.calculateStrength(mViewData.mRegisterData.password). getValue() < PasswordStrength.STRONG.getValue())
{
message = "Password should contain min of 6 characters and at least 1 lowercase, 1 uppercase and 1 numeric value";
return null;
}
you may use PasswordStrength.VERY_STRONG.getValue() as alternative. or MEDIUM
i have 2 android project.
first project--> custom edit text that i made with custom regular expresion like this
private static final String QUANTITY_REGEX = "^\\d{0,4}(\\,\\d{0,3})?$";
second project --> project that use custom edit text from first project.
after that, i exported the first class to be a library on second project as a custom edittext.
the problem is :
as you can see the regular expression on first project only allowing 4 number to be written first, and 2 digit after "," symbol on edit text. but i want to make the custom edit text to be like this
isFocused: 1234,56
!isFocused : 1.234,56
how to make it possible. thx
Change your regex to ^\d{0,4}(.\d{0,4})?(,\d{0,2})?$
private static final String QUANTITY_REGEX ="^\\d{0,4}(.\\d{0,4})?(,\\d{0,2})?$";
The matches will be
1234
1234.5678
1234.5678,12
here what i`ve figure out... hope can usefull for other programmer
the concept :
1 edit text
when user focused on edittext (txt1), user only can write 4 number , a comma (",") and 3 another number after comma (",") --> 1234,567
when (txt1) onFocused = false (user click to another editText) txt1 show the number like this 1.234,567
here the code
VALIDATION CLASS
public class Validation {
// Regular Expression
// you can change the expression based on your need
private static final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
private static final String PHONE_REGEX = "\\d{3}-\\d{7}";
private static final String CURRENCY_REGEX = "^\\d{0,8}(\\,\\d{0,2})?$";
public String maxLength = Quantity.maxLengthFront;
public String QUANTITY_REGEX = null;
// Error Messages
private static final String REQUIRED_MSG = "required";
private static final String EMAIL_MSG = "invalid email";
private static final String PHONE_MSG = "###-#######";
private static final String CURRENCY_MSG = "invalid currency";
private static final String QUANTITY_MSG = "invalid quantity";
// call this method when you need to check email validation
public static boolean isEmailAddress(EditText editText, boolean required) {
return isValid(editText, EMAIL_REGEX, EMAIL_MSG, required);
}
// call this method when you need to check phone number validation
public static boolean isPhoneNumber(EditText editText, boolean required) {
return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}
// call this method when you need to check currency validation
public static boolean isCurrency(EditText editText, boolean required) {
return isValid(editText, CURRENCY_REGEX, CURRENCY_MSG, required);
}
public boolean isQuantity(EditText editText, boolean required){
return isValid(editText, QUANTITY_REGEX, QUANTITY_MSG, required);
}
// return true if the input field is valid, based on the parameter passed
public static boolean isValid(EditText editText, String regex, String errMsg, boolean required) {
String text = editText.getText().toString().trim();
// clearing the error, if it was previously set by some other values
editText.setError(null);
// text required and editText is blank, so return false
if ( required && !hasText(editText) ) return false;
// pattern doesn't match so returning false
if (required && !Pattern.matches(regex, text)) {
editText.setError(errMsg);
return false;
};
// pattern doesn't match so returning false
if (!required && !Pattern.matches(regex, text)) {
editText.setError(errMsg);
return false;
};
return true;
}
// check the input field has any text or not
// return true if it contains text otherwise false
public static boolean hasText(EditText editText) {
String text = editText.getText().toString().trim();
editText.setError(null);
// length 0 means there is no text
if (text.length() == 0) {
editText.setError(REQUIRED_MSG);
return false;
}
return true;
}
}
QUANTITY CLASS
public class Quantity extends EditText {
public static String maxLength;
public static String maxLengthFront = "4";
public static String regexCustom;
public boolean statusFocused = false;
public boolean allowBlank;
public String decimalPlaces;
String oldText;
Validation validation = new Validation();
public Quantity(Context context) {
super(context);
}
public Quantity(Context context, AttributeSet attrs) {
super(context, attrs);
// --- Additional custom code --
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.Quantity);
final int N = a.getIndexCount();
for (int i = 0; i < N; ++i) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.Quantity_decimalPlaces_quantity:
decimalPlaces = a.getString(attr);
// ...do something with delimiter...
break;
case R.styleable.Quantity_maxLength_quantity:
maxLength = "5";
// ...do something with fancyText...
doSetMaxLength();
break;
case R.styleable.Quantity_allowBlank_quantity:
allowBlank = a.getBoolean(attr, false);
// ...do something with fancyText...
break;
}
}
a.recycle();
this.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
this.setKeyListener(DigitsKeyListener.getInstance("1234567890-.,"));
this.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (statusFocused == true) {
maxLengthFront = "4";
if (validation.isQuantity(Quantity.this, false)) {
// Toast.makeText(getContext(), "Validation True", Toast.LENGTH_SHORT).show();
} else {
// Toast.makeText(getContext(), "Validation False",Toast.LENGTH_SHORT).show();
Quantity.this.setText(oldText);
Quantity.this.setSelection(Quantity.this.getText().length(), Quantity.this.getText().length());
}
} else {
maxLengthFront = "5";
}
validation.QUANTITY_REGEX = "^\\d{0," + maxLengthFront + "}(\\,\\d{0,3})?$";
}
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
oldText = s.toString();
// Toast.makeText(getContext(), "Before change : " + s, Toast.LENGTH_SHORT).show();
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
this.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean gainFocus) {
// onFocus
String s;
if (gainFocus) {
maxLengthFront = "4";
validation.QUANTITY_REGEX = "^\\d{0," + maxLengthFront + "}(\\,\\d{0,3})?$";
s = Quantity.this.getText().toString().replace(".", "");
Quantity.this.setText(s);
statusFocused = true;
}
// onBlur
else {
maxLengthFront = "5";
validation.QUANTITY_REGEX = "^\\d{0," + maxLengthFront + "}(\\.\\d{0,3})?$";
Double number = Double.parseDouble(Quantity.this.getText().toString());
DecimalFormatSymbols symbol = DecimalFormatSymbols.getInstance();
symbol.setGroupingSeparator('.');
symbol.setDecimalSeparator(',');
DecimalFormat formatter = new DecimalFormat("###,###.###", symbol);
Quantity.this.setText(formatter.format(number));
statusFocused = false;
}
}
});
}
public Quantity(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// --- Additional custom code --
}
// #Override
// protected void onTextChanged(CharSequence text, int start,
// int lengthBefore, int lengthAfter) {
// // TODO Auto-generated method stub
// super.onTextChanged(text, start, lengthBefore, lengthAfter);
// Toast.makeText(getContext(), this.getText() + " - " + text.toString(),
// Toast.LENGTH_SHORT).show();
// }
public void doSetMaxLength() {
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(Integer.parseInt(maxLength, 10));
this.setFilters(FilterArray);
}
}