Can't get my if statement to work? - java

I know this has got to be simple. But for the life of me i don't know why i can't get this right.
Ok so I want to go from a listview page (got that) then click a switch to make it go to the next page (also got that.) Then I want a int to tell me which position I am on form the last page (might be working?) now i can't get the If Else statement to work in the page.
public class NightmareParts extends Activity
{
public int current_AN_Number = NightmareList.AN_position_num;
private TextView edit_title;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.part_layout);
// isn't working here. Why?
// test_edit = (TextView)findViewById(R.id.directions_tv);
// test_edit.setText(R.string.directions_text_two);
// works without this being in here.
setDoneButtonListener();
}
//Set up the Done button to initialize intent and finish
private void setDoneButtonListener()
{
Button doneButton = (Button) findViewById(R.id.back_button);
doneButton.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v)
{
finish();
}
});
}
private void editTitle()
{
if (current_AN_Number = 1)
{
edit_title = (TextView)findViewById(R.id.part_title);
edit_title.setText(R.string.AN_title_1);
}
}
}
The current_AN_number is coming from the last page.

Your if statement is incorrect:
if (current_AN_Number = 1)
You've used the assignment operator, when you wanted to compare it with the == operator:
if (current_AN_Number == 1)

if (current_AN_Number = 1)
Should be
if (current_AN_Number == 1)
You're not setting current_AN_Number to be 1, you are comparing if it is equal to 1. So use ==.

test_edit = (TextView)findViewById(R.id.directions_tv);
is not working because test_edit is never declared.

Related

How to validate decimal input not allowing alone "." and empty field?

I'm writing a calculator on Android Studio, in Java, and the app crashes if the user call the result with a dot "." alone or let the EditText field in blank.
I'm looking for a solution for not allowing these two conditions happening, together or individualy, in each of the three fields.
I've already tried TextWatcher and if/else but without success.
The .xml file where the editText field are designed is already set for decimalNumber.
I've already tried this:
if(myfieldhere.getText().toString().equals(".")){myfieldhere.setText("0");}
For each "valor line" and else for the "finalresult" line if everything is fine. Both inside the setOnClickListener block. This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.peso_layout);
result = findViewById(R.id.layresult);
conc = findViewById(R.id.layconc);
dose = findViewById(R.id.laydose);
peso = findViewById(R.id.laypeso);
calc = findViewById(R.id.laycalcpeso);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float valor1 = Float.parseFloat(peso.getText().toString());
float valor2 = Float.parseFloat(conc.getText().toString());
float valor3 = Float.parseFloat(dose.getText().toString());
float finalresult = valor1 * valor2 * valor3;
result.setText("The result is: " + finalresult);
}
});
}
The ideal output should be the app not crashing if these two conditions happen and sending an error message to the user that input is invalid.
What i'm receiving is the app crashing.
Thank you very much. I'm very beginner in Java and I'm few days struggling with this.
Dear Friend, Your directly trying to convert string input into float and then after your check value but do your code like Below.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText edt1,edt2;
TextView txtans;
Button btnsum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt1=findViewById(R.id.edt1);
edt2=findViewById(R.id.edt2);
txtans=findViewById(R.id.txtans);
btnsum=findViewById(R.id.btnsum);
btnsum.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.btnsum){
float n1,n2;
String value1=edt1.getText().toString();
String value2=edt2.getText().toString();
if(value1.equals("") || value1.equals(".")){
n1=0;
}else {
n1= Float.parseFloat(value1);
}
if(value2.equals("")|| value2.equals(".")){
n2=0;
}else{
n2= Float.parseFloat(value2);
}
float ans=n1+n2;
txtans.setText(ans+"");
}
}
}
See In above code, First get value from edittext and then check wheather it contain null or "." inside it. if it contains then store 0.0 value in some variable. then after make sum and display in textbox.
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String myvalor = myfieldhere.getText().toString();
if(myvalor.equals(".") || myvalor.isEmpty())
{
// toast error : incorrect value
return;
}
try
{
float valor1 = Float.parseFloat(peso.getText().toString());
float valor2 = Float.parseFloat(conc.getText().toString());
float valor3 = Float.parseFloat(dose.getText().toString());
float finalresult = valor1 * valor2 * valor3;
result.setText("The result is: " + finalresult);
}
catch(Exception exp){// toast with exp.toString() as message}
}
});
use TextUtils for check empty String its better
if(TextUtils.isEmpty(peso.getText().toString())||
TextUtils.isEmpty(conc.getText().toString())||
TextUtils.isEmpty(dose.getText().toString())){
return;
}

how to take default value of an edittext as 0?

I am trying to make a simple android app in which 2 text fields are there.input range is 0 to 15. If the number is in range than addition is performed.
i have implemented input varification so now if the edit text is empty it shows empty field warning. but calculation is not done. what i want is if the field is empty is should show the error but also do the addition by take default value as 0.
here is my code
public class MainActivity extends AppCompatActivity {
private EditText check,check2;
private TextView textView;
private TextInputLayout checkLay,checkLay2;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeWidgets();
initializeListeners();
}
private void initializeWidgets(){
check=findViewById(R.id.check);
check2=findViewById(R.id.check2);
checkLay2=findViewById(R.id.checkLay2);
checkLay=findViewById(R.id.checkLay);
button=findViewById(R.id.button);
textView=findViewById(R.id.textView);
}
private void initializeListeners() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signUp();
}
});
}
private void signUp(){
boolean isVailed=true;
int a1,a2;
String one=check.getText().toString();
String two=check2.getText().toString();
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
isVailed=false;
}
else {
if (one.length() > 0)
{
a1=Integer.parseInt(one);
if(a1> 15){
checkLay.setError("quiz marks must be less than 15");
isVailed=false;
}
else if(a1 <=15)
{
checkLay.setErrorEnabled(false);
isVailed=true;
}
}
}
if(two.isEmpty()){
checkLay2.setError("You need to enter something");
isVailed=false;
}
else{
if (two.length() > 0)
{
a2=Integer.parseInt(two);
if(a2 > 15)
{ checkLay2.setError("quiz marks must be less than 15");
isVailed=false;
}
else
if(a2 <=15)
{
checkLay2.setErrorEnabled(false);
isVailed=true;
}
}
if(isVailed)
{
int total;
a1=Integer.parseInt(one);
a2=Integer.parseInt(two);
total=a1+a2;
textView.setText(String.valueOf(total));
}
}
I would do it differently but for your specific question
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
isVailed=false;
}
Change to
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
a1=0;
}
Same for the two.isEmpty()
If a field is empty you set isVailed to false and thus say not to add the numbers. Instead you want to set the corresponding number to zero and let isVailed be true:
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
a1 = 0;
}
and
if(two.isEmpty()){
checkLay2.setError("You need to enter something");
a2 = 0;
}
Also throw off the lines
a1=Integer.parseInt(one);
a2=Integer.parseInt(two);
You already convert inputs to a1 and a2 earlier.
A piece of advice: you have doubled code. It's better to use functions for such pieces of codes.
add this line in your initializeWidgets function
yourEditText.setText(0);
follow link for more help: duplicate
You can create a convenience method to get value from your edittext. The following code will return 0 if edittext is empty else the value from the edittext
private int getIntFromEditText(EditText editText) {
return editText.getText().length()>0 ? Integer.parseInt(editText.getText().toString()):0;
}
Call it by passing EditText as a parameter, e-g
a1=getIntFromEditText(check)

Dot in calculator android studio

I have been trying to build a simple calculator in android studio. Everything is fine but i have a problem, when i run the calculator and i press the dot button, it shows in the textview "." instead "0."
Also, i need to check the existence of two decimal points in a single numeric value.
here is an image:
it shows "."
and i want:
how can i change this??, here is my code:
private int cont=0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display=(TextView)findViewById(R.id.display);
text="";
}
public void numero1(View view){ /*when i press a number, this method executes*/
Button button = (Button) view;
text += button.getText().toString();
display.setText(text);
}
public void dot(View view){ /*This is not finished*/
display.setText{"0."}
}
I was thinking in creating another method for the dot button, but the content of the text value disappears when i press another button, how to fix this?
try this
public void numero1(View view){ /*when i press a number, this method executes*/
Button button = (Button) view;
text += button.getText().toString();
if(text.substring(0,1).equals("."))
text="0"+text;
display.setText(text);
}
try this way
public void dot(View view){ /*This is not finished*/
String str=display.getText().toString().trim();
if(str.length()>0){
display.seText(str+".")
}else{
display.setText("0.")
}
}
Use a string builder and append all the text entered to already existing string. Before display, just use the toString() method on the string builder.
Create a class that represents your character sequence to be displayed and process the incoming characters.
For example:
class Display {
boolean hasPoint = false;
StringBuilder mSequence;
public Display() {
mSequence = new StringBuilder();
mSequence.append('0');
}
public void add(char pChar) {
// avoiding multiple floating points
if(pChar == '.'){
if(hasPoint){
return;
}else {
hasPoint = true;
}
}
// avoiding multiple starting zeros
if(!hasPoint && mSequence.charAt(0) == '0' && pChar == '0'){
return;
}
// adding character to the sequence
mSequence.append(pChar);
}
// Return the sequence as a string
// Integer numbers get trailing dot
public String toShow(){
if(!hasPoint)
return mSequence.toString() + ".";
else
return mSequence.toString();
}
}
Set such a click listener to your numeric and "point/dot" buttons:
class ClickListener implements View.OnClickListener{
#Override
public void onClick(View view) {
// getting char by name of a button
char aChar = ((Button) view).getText().charAt(0);
// trying to add the char
mDisplay.add(aChar);
// displaying the result in the TextView
tvDisplay.setText(mDisplay.toShow());
}
}
Initialize the display in onCreate() of your activity:
mDisplay = new Display();
tvDisplay.setText(mDisplay.toShow());

How to update method to return updated information from textwatcher after pressing button

I have declared my variable, 'changed' too null so that I can check if it changes when the edittext is changed,
The problem I think is, when I press either the save button or the cancel button, it will always produce the value null, as upon clicking the button it is still null. However, I thought that the textwatcher would listen to the EditText and even if nothing was changed in the EditText it would by default change the SetChanged() to false as it provided "live updates", however clearly this isn't the case, am I doing something wrong? or am I supposed to approach it in a different way?, is there some way of refreshing it?
Advise would be greatly appreciated.
(P.S Some code was deleted to reduce the size and make it look easy on the eye, so excuse me for any missing braces. Furthermore, the activity does run properly as it shows the layout.However upon pressing any of the buttons it causes it to crash.)
public class EditNewItemActivity extends AppCompatActivity{
private Boolean changed = null;
private TextView title,content;
private Button saveBtn,cancelBtn;
private String date;
private int id;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_item);
title = (TextView) findViewById(R.id.editItemTitle);
content = (TextView) findViewById(R.id.editItemDescription);
saveBtn = (Button) findViewById(R.id.editItemSaveBtn);
cancelBtn = (Button) findViewById(R.id.editItemCancelBtn);
Bundle extras = getIntent().getExtras();
title.setText(extras.getString("title"));
content.setText(extras.getString("content"));
date = extras.getString("date");
id = extras.getInt("id");
GenericTextWatcher textWatcher = new GenericTextWatcher();
title.addTextChangedListener(textWatcher);
content.addTextChangedListener(textWatcher);
ClickEvent clickEvent = new ClickEvent();
saveBtn.setOnClickListener(clickEvent);
cancelBtn.setOnClickListener(clickEvent);
}
private class ClickEvent implements View.OnClickListener{
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.editItemSaveBtn:
save();
break;
case R.id.editItemCancelBtn:
cancel();
break;
}
}
}
private void cancel() {
if (getChanged() == null){
//This was used to simply verify that getchanged was still null.
}
if (title.getText().toString() != "" || content.getText().toString() != ""){
if (getChanged() == false) {
// if nothing has been changed let it cancel etc
}else {
}
}
}
private void save() {
if (tempTitle != "" || tempContent != "") {
if(getChanged() == true){
}
}
public Boolean getChanged() {
return changed;
}
public void setChanged(Boolean changed) {
this.changed = changed;
}
private class GenericTextWatcher implements TextWatcher{
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Log.v("Beforetext:", s.toString());
EditNewItemActivity editItem = new EditNewItemActivity();
editItem.setChanged(false);
}
#Override
public void afterTextChanged(Editable s) {
Log.v("afterTextChanged:", s.toString());
EditNewItemActivity editItem = new EditNewItemActivity();
editItem.setChanged(true);
Log.v("Status:", editItem.getChanged().toString());
}
}
You had change the changed. But which you changed is in your new EditNewItemActivity not in your current page.
This is where you made mistake (beforeTextChanged and afterTextChanged in your GenericTextWatcher):
EditNewItemActivity editItem = new EditNewItemActivity();
editItem.setChanged(false); //or true
You should just call:
setChanged(false); // or true
In fact, you should not new an activity yourself, activity must be create by the Android Framework so that it can be managed by the system.

Compare the result of two TextViews Java/Android

I'm making a simple very simple android math game. But I cant manage to compare two TextViews to let the user know if they calculated correct or not???
Im not comparing them correctly as my if/else statement is only giving me the else output??
public class PlayActivity extends AppCompatActivity {
EditText number1;
EditText number2;
TextView result;
Button addNumbers;
TextView equalW;
TextView equalL;
TextView generate;
double num1,num2,sum;
Random r = new Random();
public View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
generate = (TextView)findViewById(R.id.textViewGenerate);
int generated = r.nextInt(101);
generate.setText(Integer.toString(generated));
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
number1 = (EditText)findViewById(R.id.editTextNumber1);
number2 = (EditText)findViewById(R.id.editTextNumber2);
result = (TextView)findViewById(R.id.textViewSum);
addNumbers = (Button)findViewById(R.id.buttonAdd);
equalL = (TextView)findViewById(R.id.textViewLose);
equalW = (TextView)findViewById(R.id.textViewWin);
Button buttonGenerate = (Button)findViewById(R.id.buttonGenerate);
buttonGenerate.setOnClickListener(listener);
addNumbers.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
num1 = Double.parseDouble(number1.getText().toString());
num2 = Double.parseDouble(number2.getText().toString());
sum = num1 + num2;
result.setText(Double.toString(sum));
if (generate.getText().toString().equals(result))
{
equalW.setText("Answer is correct");
}
else {
equalL.setText("lose");
}
}
});
}
You have one obvious problem and another lurking problem.
The obvious one: You have to compare a String with a String and not with a TextView. Hence replace if (generate.getText().toString().equals(result)) with if (generate.getText().toString().equals(result.getText().toString())).
The lurking one: If you see closely, sum is set as String in result and generated is set as String in generate. sum is of data type double and generate is of data type int. Comparing both will cause problem. This is like comparing "10".equals("10.0"). This is error prone. You need to set both these fields to a common data type.
Change if condition as:
if (generate.getText().toString().equals(result.getText().toString()))
{
}
Because result is view so call getText method for comparing String values.
result is textview so you have to write
if (generate.getText().toString().equals(result.getText().toString))

Categories

Resources