Pants
Pants

Reputation: 2782

EditText.getText().toString() returns hint. How to return empty String instead?

I've noticed that EditText.getText().toString() returns even the hint. Is there any way to not return the hint if the EditText field is empty?

Sure I can check if toString() returns the hint but that does not sound very reasonable.

Here is the XML of my EditText:

<EditText
    android:id="@+id/add_assignment_title_edittext"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/add_assignment_title_textview"
    android:layout_marginStart="50dp"
    android:gravity="center"
    android:hint="@string/title_hint"/>

This is how I use it:

EditText titleEditText = (EditText) view.findViewById(R.id.add_assignment_title_edittext);
// Then I access it with
String titleStr = titleEditText.getText().toString();

Upvotes: 1

Views: 2798

Answers (5)

Shreyash Karandikar
Shreyash Karandikar

Reputation: 51

This works

EditTextName.getEditableText()

Upvotes: 0

Sufian
Sufian

Reputation: 6555

As this answer states, hint will only be returned with editText.getHint().toString().

If you are doing neither of the following then the only thing you can try is to rebuild/clean build the project:

  1. editText.setText() in your Java code, nor
  2. android:text="@string/title_hint" in your XML.

Upvotes: 1

Nicola De Fiorenze
Nicola De Fiorenze

Reputation: 2128

Use editText.getText().toString()

Edit: Here some code, probably the error is in your xml

main_activity.xml:

<EditText
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Write here"/>

MainActivity.kt:

val editText = findViewById(R.id.text_view) as EditText
println("-> ${editText.text}")

Output without typing anything:

$ ->

Output typing 'hello':

$ -> hello

Only for completeness, MainActivity in java code:

EditText editText = findViewById(R.id.text_view);
Log.d(TAG,"-> "+ editText.getText());

Upvotes: 0

fe_araujo_
fe_araujo_

Reputation: 1869

Use this:

yourEditText.getText().toString();

You need the "getText()" method first.

Upvotes: 0

Firerazzer
Firerazzer

Reputation: 192

I don't know want you want to do with EditText.toString(). But if you want that toString() return something special the best way is to create a custom EditText.

Like :

import android.content.Context;
import android.util.AttributeSet;
import android.widget.EditText;


public class CustomEditText extends EditText {
    public CustomEditText(Context context) {
        super(context);
    }

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public String toString() {
        //return what you want
    }
}

Upvotes: 0

Related Questions