Programmer
Programmer

Reputation: 59

Android EditText .setText("") not working

I am trying to clear the text in my edit text field but for some reason it is not working.

I have declared an edit text field in the xml of my view:

 <EditText
        android:id="@+id/enterGlucoseLevel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/mySimpleXYPlot"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="numberDecimal" />

I have used the attribute onClick to link my button to the enterGlucoseAction() method in my MainActivity class:

<Button
    android:id="@+id/enterGlucoseButton"
    android:clickable="true"
    android:onClick= "enterGlucoseAction"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/enterGlucoseLevel"
    android:layout_centerHorizontal="true"
    android:text="@string/enterGlucoseLvlButton" />

Here is that method:

public void enterGlucoseAction(View v) {
    glucoseField.setText("");

     Toast.makeText(v.getContext(), "You clicked the button", Toast.LENGTH_SHORT).show();
}

I get the toast pop up but my edit text field is not being cleared.

Here is my on create and instance variables in case the problem lies there.

private XYPlot plot;
private Button addGlucoseLevel;
private EditText glucoseField;
private XYSeries currentSeries;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addGlucoseLevel = (Button) findViewById(R.id.enterGlucoseButton);
    glucoseField = (EditText) findViewById(R.id.enterGlucoseLevel);                     

    currentSeries = new SimpleXYSeries(Arrays.asList(new Number[] { 7200, 8, 54000, 2, 64800, 4 }), 
            SimpleXYSeries.ArrayFormat.XY_VALS_INTERLEAVED,
            "Glucose Level");

    //Create an series of numbers to plot.
    createGraph(currentSeries);
}

Thanks in advance.

And sorry, I know this has been asked before but I can't find a solution to my problem specifically.

Upvotes: 0

Views: 3158

Answers (4)

Stefano Mader
Stefano Mader

Reputation: 1

((EditText)findViewById(R.id.yourEditTextId)).getText().clear();

anything else crashed.

Upvotes: 0

questioner
questioner

Reputation: 2293

To clear your EditText which accepts numbers use clear() method:

glucoseField.getText().clear();

You can try setting it this way:

((EditText)findViewById(R.id.enterGlucoseLevel)).getText().clear();

Upvotes: 3

Priya Singhal
Priya Singhal

Reputation: 1291

You should use

setText("\b");

As we can use escape sequence

Upvotes: 0

Harsh Dattani
Harsh Dattani

Reputation: 2129

Alternatively you can use getText().clear(); just replace glucoseField.setText(""); with glucoseField.getText().clear();

Upvotes: 0

Related Questions