简体   繁体   中英

Why EditText.getText shows null in Android?

I have a very strange problem with EditText. I create a form in my app with Edit Texts and I get their content into string value but its empty and shows nothing.

XML code:

 <EditText
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center"
        android:id="@+id/name"
        style="@style/Edittext_form1"
        android:inputType="text"
        android:hint="@string/name"/>

java code:

 private EditText _name;

 public  static  String name;

        _name = (EditText) findViewById(R.id.name);
        name = _name.getText().toString().trim();

Toast.makeText(getApplicationContext(),name,Toast.LENGTH_LONG).show();;

Your problem is about to get the content of that resource before you set it.

Add this line to your Edittext tag:

android:text="some default text"

Take one EditText, Button and TextView and try this:


Main Activity:

    btnName.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            tvName.setText(etName.getText().toString());
        }
    });

activity_main3

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".extras.MainActivity">

<EditText
    android:id="@+id/et_name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="50dp"
    app:layout_constraintTop_toTopOf="parent"
    android:hint="Please enter your name"
    />

<Button
    android:id="@+id/btn_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="50dp"
    android:text="Click Here"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@id/et_name" />

<TextView
    android:id="@+id/tv_name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="50dp"
    app:layout_constraintTop_toBottomOf="@id/btn_name"
    />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM