Search code examples
android-edittextdefaultgettext

How to make Numeric Edit Text default to blank and then use getText


Please Help!I have Edit Text field whose inputType is number. On the click of Submit button in the firstActivity I want to send the value via Bundle to next activity. I want to make the field compulsory. Before sending the value I am checking if the EditText is blank. if its blank I want to give a Toast message that "Please enter number". I am using below code line to get the numeric text

  editTextValue= (EditText) findViewById(R.id.edit_attendance);
  editTextValue.setText("0");
  var1 = Integer.valueOf((editTextValue.getText().toString()));

For this code to work I have to first set the default value to 0
But due to this when user is entering value in this EditText, he has to first erase 0 and then enter number. I dont want to set it to 0 value. Is there any other way to make this work.

Below is my Code in XML:

 <EditText
        android:id="@+id/edit_1"
        android:layout_marginLeft="5sp"
        android:layout_width="100sp"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:hint="0"
        android:textColor="@android:color/white" />

FirstActivity.java

onCreate(){
 editTextValue = (EditText) findViewById(R.id.edit_1);

 editTextValue.setText("0");


  btnSubmit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

        var1 = Integer.valueOf((editTextValue.getText()
                    .toString()));

         if (var1 == 0) // when no value is entered
                Toast.makeText(getApplicationContext(),
                        "Please enter value",
                        Toast.LENGTH_SHORT).show();
         else
         {
              Intent i = new Intent(getApplicationContext(),
                        SecondActivity.class);


                dataBundle.putInt(SecondActivity.VAR1,var1);
                i.putExtras(dataBundle);
                startActivity(i);

         }

}

Solution

  • The below code worked for me:

    // editTextValue.setText("0");
    
        editTextValue.setOnEditorActionListener(new OnEditorActionListener() {
    
            public boolean onEditorAction(TextView v, int actionId,
                    KeyEvent event) {
                // TODO Auto-generated method stub
                if (actionId == EditorInfo.IME_ACTION_DONE) {
    
                    var1 = Integer.valueOf((editTextValue
                            .getText().toString()));
    
                }
    
                return false;
            }
        });