Hot questions for Using Android EditText in if statement

Question:

I really wish that you can help me. I my application in Android to clear or erase the the default string assigned to the editText object on the main Activity when clicking on it, only if the value is equal to this text "Enter a message here", which I assigned it in the R.java file as "R.string.editTextOnStart". Here's the code:

    public class MainActivity extends AppCompatActivity {

    private String text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView textView = (TextView) findViewById(R.id.textView);
        final EditText editText = (EditText) findViewById(R.id.editText);

        editText.setText(R.string.editTextOnStart);

        textView.setText(R.string.textViewString);

        //if(editText.getText().toString().equals(String.valueOf(R.string.editTextOnStart))) {

            editText.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    text = editText.getText().toString();

                    if(text.equals(R.string.editTextOnStart)) {
                        editText.getText().clear();
                    }
                }
            });
        //}
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                textView.setText(editText.getText().toString());
            }
        });
    }
}

Answer:

Instead of doing that, you can specify the following using hint

In your layout xml file , under your EditText, add this

android:hint="Enter your text here"

This will appear on your edit text when you start the activity and disappears when user have clicked on it

Question:

I have an app that has a spinner (spinner5) which, when the "Other" tab is selected, will show a series of editext. However, when I select the tab, the EditText do not appear. Any help is appreciated.

     a = (EditText) findViewById(R.id.editText34);
    a.setVisibility(View.GONE);
    b = (EditText) findViewById(R.id.editText35);
    b.setVisibility(View.GONE);
    c = (EditText) findViewById(R.id.editText36);
    c.setVisibility(View.GONE);


    if (spinner5.getSelectedItem().toString().equals("Other")) {
        a.setVisibility(View.VISIBLE);
        b.setVisibility(View.VISIBLE);
        c.setVisibility(View.VISIBLE);
    }

The following is my strings.xml

     <string-array name="site_location">
    <item>ETAK NC</item>
    <item>ETAK OH</item>
    <item>ETAK IL</item>
    <item>ETAK GA</item>
    <item>ETAK TX</item>
    <item>ETAK CA</item>
    <item>Left on site (CA)</item>
    <item> Other</item>
    <item>Transferring to other site</item>
</string-array>

Answer:

solved it right after i posted this lol. Rookie mistake, I realized that I didn' t have the if statement in the onItemSelected() method.

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    if (spinner5.getSelectedItem().toString().equals("Other")) {
        a.setVisibility(View.VISIBLE);
        b.setVisibility(View.VISIBLE);
        c.setVisibility(View.VISIBLE);
    }
}

Question:

I want my btnsave to work only when there is something in editText. First, when application launched, when there is not anything in editText my code works (btnsave does not work). But when i type something in editText I expect btnsave to be able to work. But no! It doesn't work. I think if statement only runs one time.

What is the problem? I want this code run permanently while the application is running.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnSave = (Button) findViewById(R.id.btnSave);
    editText = (EditText) findViewById(R.id.editText);

    if (!editText.getText().toString().matches(""))
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this,"H", Toast.LENGTH_SHORT).show();
            }
        });

}

In other words

btnAdd = (Button) findViewById(R.id.btnAdd);
editText = (EditText) findViewById(R.id.editText);

if (editText.getText().toString().matches(""))
    btnAdd.setEnabled(false);
else
    btnAdd.setEnabled(true);

When app launchs , btn is disabled(because editText is empty ) but when i type a text in editTextit is expected that btn gets enabled but it doesnt!

i think when i type sth in editText it doesnt recheck the conditions .WHY?


Answer:

editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().trim().length() > 0)  {
                    btnAdd.setEnabled(false);
                } else {
                    btnAdd.setEnabled(true);
                }
            }
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

Question:

I have 5 EditTexts, when I am clicking on the button, I want to check that all of them are not empty in order to take data from them and put it into the database, and start another activity. If all of them are empty, a message would be displayed that "You need to fill everything". However, when all EditTexts are empty and I press the button, application crashes. How can I solve this problem and what can I do to get the desired result? (The code is not ended yet.)

public class Main2Activity extends AppCompatActivity {

DatabaseHelper myDB;
Button btnAdd;
EditText editText1,editText2,editText3,editText4,editText5;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    editText1 = (EditText) findViewById(R.id.name);
    editText2 = (EditText) findViewById(R.id.year);
    editText3 = (EditText) findViewById(R.id.month);
    editText4 = (EditText) findViewById(R.id.day);
    editText5 = (EditText) findViewById(R.id.price);



    btnAdd = (Button) findViewById(R.id.btn_add);
    myDB = new DatabaseHelper(this);




    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String name1 = editText1.getText().toString();
            String year2 = editText2.getText().toString();
            int year1 = Integer.parseInt(year2);
            String month2 = editText3.getText().toString();
            int month1 = Integer.parseInt(month2);
            String day2 = editText4.getText().toString();
            int day1 = Integer.parseInt(day2);
            String price2 = editText5.getText().toString();
            int price1 = Integer.parseInt(price2);


            if (name1.length() != 0 && year2.length() != 0 && month2.length() != 0 && day2.length() != 0 && price2.length() != 0) {

                AddData(name1, year1, month1, day1, price1);

                editText1.setText("");
                editText2.setText("");
                editText3.setText("");
                editText4.setText("");
                editText5.setText("");

                Intent intent = new Intent(Main2Activity.this, MainActivity.class);
                startActivity(intent);

            } else {

                Toast.makeText(Main2Activity.this, "You need to fill everything", Toast.LENGTH_LONG).show();
            }


        }
    });
}




public void AddData(String name1, int year1, int month1, int day1, int price1) {

    boolean insertData = myDB.addData(name1,year1,month1,day1,price1);

    if(insertData==true){
        Toast.makeText(this, "Data Successfully Inserted!", Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(this, "Something went wrong :(.", Toast.LENGTH_LONG).show();
        }
    }
}

Answer:

The crash happens here:

int year1 = Integer.parseInt(year2);

When EditText is empty, you are passing an empty string to Integer.parseInt, which results in NumberFormatException. To avoid this, move the parsing code into the validation block.

@Override
public void onClick(View v) {
    String name1 = editText1.getText().toString();
    String year2 = editText2.getText().toString();
    String month2 = editText3.getText().toString();
    String day2 = editText4.getText().toString();
    String price2 = editText5.getText().toString();

    if (name1.length() != 0 && year2.length() != 0 && month2.length() != 0 && day2.length() != 0 && price2.length() != 0) {

        // Move parsing code here
        int year1 = Integer.parseInt(year2);
        int month1 = Integer.parseInt(month2);
        int day1 = Integer.parseInt(day2);
        int price1 = Integer.parseInt(price2);
        AddData(name1, year1, month1, day1, price1);

        editText1.setText("");
        editText2.setText("");
        editText3.setText("");
        editText4.setText("");
        editText5.setText("");

        Intent intent = new Intent(Main2Activity.this, MainActivity.class);
        startActivity(intent);

    } else {

        Toast.makeText(Main2Activity.this, "You need to fill everything", Toast.LENGTH_LONG).show();
    }
}

Question:

I'm using this simple if/else statement to check which RadioButton is selected and set the text of a TextView regarding the selection. Well, for the first two cases (if rb1.isChecked() and if rb2.isChecked()) the code executes correctly and it just makes a calculation of two numbers. However, when the third case comes out (!rb1.isChecked() && !rb2.isChecked()) the application crashes. What is wrong?

        if (rb1.isChecked()) {
        int sum = x + y;
        String result = String.valueOf(sum);
        tv3.setText(result);
    } else if (rb2.isChecked()) {
        int rest = x - y;
        String result = String.valueOf(rest);
        tv3.setText(result);
    } else if (!rb1.isChecked() && !rb2.isChecked()){
        tv3.setText("Select an option!");
    }

UPDATE: The Manifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.logixor.advancedcalc">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

The MainActivity.java:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
public EditText et1,et2;
public TextView tv3;
public RadioButton rb1,rb2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    et1=(EditText)findViewById(R.id.et1);
    et2=(EditText)findViewById(R.id.et2);
    tv3=(TextView)findViewById(R.id.tv3);
    rb1=(RadioButton)findViewById(R.id.rb1);
    rb2=(RadioButton)findViewById(R.id.rb2);
}

public void calc(View view) {
    String valA = et1.getText().toString();
    String valB = et2.getText().toString();
    int x = Integer.parseInt(valA);
    int y =Integer.parseInt(valB);

    if (rb1.isChecked()) {
        int sum = x + y;
        String result = String.valueOf(sum);
        tv3.setText(result);
    } else if (rb2.isChecked()) {
        int rest = x - y;
        String result = String.valueOf(rest);
        tv3.setText(result);
    }

    if (!rb1.isChecked() && !rb2.isChecked()){
        tv3.setText("Select an option!");
    }
}
}

The activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.logixor.advancedcalc.MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/textNumber"
    android:id="@+id/tv2"
    android:layout_marginTop="27dp"
    android:layout_below="@+id/et1"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:id="@+id/et2"
    android:layout_below="@+id/tv2"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:hint="@string/writeHere" />

<RadioGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="29dp"
    android:padding="20dp"
    android:layout_below="@+id/et2"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:id="@+id/rg1">

    <RadioButton
        android:text="@string/sum"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/rb1"
        android:layout_weight="1" />

    <RadioButton
        android:text="@string/rest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/rb2"
        android:layout_weight="1" />

</RadioGroup>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/textNumber"
    android:layout_marginTop="25dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:id="@+id/tv1" />

<Button
    android:text="@string/calc"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:layout_alignBottom="@+id/rg1"
    android:layout_marginBottom="27dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_toRightOf="@+id/rg1"
    android:layout_toEndOf="@+id/rg1"
    android:onClick="calc" />

<TextView
    android:text="@string/result"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="19dp"
    android:id="@+id/tv3"
    android:textSize="24sp"
    android:layout_below="@+id/rg1"
    android:textAlignment="center" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:layout_marginTop="8dp"
    android:id="@+id/et1"
    android:hint="@string/writeHere"
    android:layout_below="@+id/tv1"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

</RelativeLayout>

The strings.xml:

<resources>
<string name="app_name">AdvancedCalc</string>
<string name="textNumber">Number</string>
<string name="writeHere">Write number here...</string>
<string name="result">Result</string>
<string name="calc">CALCULATE</string>
<string name="sum">Sum</string>
<string name="rest">Rest</string>
</resources>

The FATAL ERROR from the logcat:

E/AndroidRuntime: FATAL EXCEPTION: main 
Process: com.logixor.advancedcalc, PID: 23911
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4640)
at android.view.View$PerformClick.run(View.java:19425)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4640) 
at android.view.View$PerformClick.run(View.java:19425) 
at android.os.Handler.handleCallback(Handler.java:733) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:146) 
at android.app.ActivityThread.main(ActivityThread.java:5593) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:137)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:331)
at com.logixor.advancedcalc.MainActivity.calc(MainActivity.java:30)
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:4640) 
at android.view.View$PerformClick.run(View.java:19425) 
at android.os.Handler.handleCallback(Handler.java:733) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:146) 
at android.app.ActivityThread.main(ActivityThread.java:5593) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) 
at dalvik.system.NativeStart.main(Native Method) 

Answer:

Caused by: java.lang.NumberFormatException: Invalid int: "" means that text in EditText is empty, so you get the exception at Integer.parseInt() inside of the calc() function. Check if it's empty with TextUtils.isEmpty(). Additionally you might make use of TextUtils.isDigitsOnly().

EDIT

With the android:inputType="number" xml attribute of EditText you'll make it to accept only digits.

Question:

so what I am trying to accomplish is check a file to see if a word in the file matches the customers input.

I am attaching the code from when the button is clicked and what its supposed to do. Where its failing, or basically not doing it right, is where its supposed to check to see if it is in the list.

*CODE*
btn1.setOnClickListener(new OnClickListener() {  // listen for when i click
        public void onClick(View v) {
            btn1.setText("yeah");
            theirpass = edt1.getText().toString().toLowerCase(); // set theirpass = to text boxs input

              System.out.println("before i read file theirpass =s "+ theirpass);
              System.out.println("before i read file checking =s "+ checking);

              readFile(); // read the accouts dude


             tv1.setText("i pressed the button");//  test to make sure button pressing works
             System.out.println("after reading. theirpass =s " + theirpass);
             System.out.println("after i read file. checking =s "+ checking);

        }// end on click


    }); //end listener


}// end oncreate


public void readFile() {
BufferedReader reader = null;
try {
    reader = new    BufferedReader(
        new.  InputStreamReader(getAssets().open("account.txt")));

    // do reading, usually  loop until end of file reading  
    String mLine =  reader.readLine();// reading each line.

    while (mLine != null) {
        //process line

        mLine =   reader.readLine();

        if. (mLine.matches(theirpass)) { // when an. account is found stop reading
             System.out.println("cheking mLine"+ mLine);
            checking  = theirpass; //trying to set vale of. checking to theirpass
              Log.d("if statement in mline",checking);
             mLine=null;// trying to stop the loop

        }//end if
    }// end loop

} catch (IOException e) {
    //log the exception
} finally {
    if (reader != null) {
        try {
             reader.close();
        } catch  (IOException e) {
            //log  the exception
                    Log.d("Catch buffer","i failed the catch  in finally for reading lines");
        }
    }

}//end buffer reader

Toast.makeText(this,checking,Toast.LENGTH_LONG).show(); //test to get. value of cheking, keeps coming up blank-  no text
if (checking == theirpass) {
    btn1.setText("its  there");//test to see if the if statment  works

    System.out.println("i just checked if its there");//another test
} 


  }

 } 

To help with code

![helping with code again][2]

new Code

     if (mLine.equals(theirpass)) { // when an account is found stop reading
            System.out.println("cheking mLine"+ mLine);
            checking.equals(theirpass); //trying to set vale of checking to theirpass
            Log.d("if statement in mline",checking);
            mLine=null;// trying to stop the loop

        }//end if


        mLine = reader.readLine();
    }  //end buffer reader

value of theirpass

     //the value if theirpass is shown     below it's in the onClick method
    theirpass = edt1.getText().toString().toLowerCase(); // set theirpass = to text boxs input

Answer:

Try printing the mLine value right after "mLine = reader.readLine();" to know what you read from the file.

But I guess your biggest problem is the misuse of the "matches" function. Matches uses reg ex (http://developer.android.com/reference/java/lang/String.html#matches(java.lang.String) ) . Instead you should use ".equals" or read this for a good use of string comparison.

You should also change your while loop the this:

 // do reading, usually  loop until end of file reading  
String mLine =  reader.readLine();// reading each line.

while (mLine != null) {
    //process line

    if. (mLine.matches(theirpass)) { // when an. account is found stop reading
         System.out.println("cheking mLine"+ mLine);
        checking  = theirpass; //trying to set vale of. checking to theirpass
          Log.d("if statement in mline",checking);
         mLine=null;// trying to stop the loop

    }//end if

    mLine =   reader.readLine();
}// end loop

Because you read a line, go into your while, read a new line and have now skipped the first line of the file.

Question:

I have four EditTexts in my App

and want to become uneditable all of other 3 edittexts as soon as we write in one of them ?

how can I Achieve it ?


Answer:

you need to add text watcher on all of the edit texts and in each watcher you need to disable other edit texts. you need four of this watcher

field1.addTextChangedListener(new TextWatcher() {

   public void afterTextChanged(Editable s) {
    // now check if text is not empty disable field 2, 3 ,4. 
   }

   public void beforeTextChanged(CharSequence s, int start,
     int count, int after) {
   }

   public void onTextChanged(CharSequence s, int start,
     int before, int count) {

   }
  });