【问题标题】:EditText.getText().toString() sometimes returns ""EditText.getText().toString() 有时会返回 ""
【发布时间】:2013-08-01 12:36:20
【问题描述】:

我在TextWatcheronTextChanged() 方法中得到EditText 的文本及其长度。
当我键入以添加字符时,它工作正常,但是从文本中删除字符时 getText() 即使文本不为空,也会给出空值。这会随机发生,而不是每次我删除字符时都会发生。我观察到这主要发生在文本中有 3-4 个字符并且我按退格键时。

奇怪的是这个问题只发生在设备上,而不是模拟器上。

布局文件:

<LinearLayout
    style="@style/create_trip_activity_components_style"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:gravity="center_vertical"
    android:orientation="horizontal" >

    <EditText
        android:id="@+id/from_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="5dp"
        android:ems="10"
        android:hint="@string/from_location_hint"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/use_current_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:onClick="useCurrentLocation"
        android:text="@string/use_current"
        android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>

代码:

fromLocation.addTextChangedListener(new TextWatcher() {
    @Override
    public void afterTextChanged(Editable s) {

    }

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

    }

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

        if (fromLocation == null) {
            Log.d(TAG, "fromLocation is null................");
        }

        Log.d(TAG, "fromLocation text : "
                    + fromLocation.getText().toString());
        Log.d(TAG, "fromLocation text length :  "
                    + fromLocation.getText().length());
        Log.d(TAG, "S : "
                    + s);
        Log.d(TAG, "S length :  "
                    + s.length());
    }
});

注意:我尝试使用afterTextChanged()beforeTextChanged() 方法。但这并没有解决问题。

【问题讨论】:

  • Editable 是一个 CharSequence,因此无需将其转换为 String 来调用 length()。只是在说。尝试在TextChanged(Editable s)之后注销。
  • @DoctororDrive 在afterTextChanged() 中尝试过。还是一样的问题。
  • 可以显示你如何删除字符?
  • @Sameer 使用软键盘的键。
  • @Akash 请在下面查看我的答案,如果对您没有帮助,请告诉我。

标签: android null android-edittext gettext


【解决方案1】:

我看不出有什么问题。 from_location 的文本应该会改变,它确实会改变。

当您在 TextWatcher 代码中时,为什么要“检查”EditText (from_location)。我不认为EditText 的值在变化时必须是“稳定的”。

可能发生的情况是,当您检查 from_location 中的 CharSequence 正在更新时,有时您会在更改的过程中发现它,有时是在更改之后。

您是否检查了(CharSequence s, int start, int before, int count) 是否返回了预期值?

正如我看到的这种情况。如果您想对文本进行任何更改,您应该对 afterTextChanged 方法的 String s 参数进行更改。

我编写这段代码是为了检查在更改EditText 的内容时发生了什么,也许它是任何的

    mEdtText.addTextChangedListener(new TextWatcher() {
        private static final String TAG = "TextWatcher";
        private static final boolean DEBUG = true;

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            if (DEBUG)
                Log.d(TAG,
                        "(onTextChanged) In \"" + s + "\" " + before
                                + " characters "
                                + " are being replaced at " + start
                                + " by " + count + " ("
                                + s.subSequence(start, start + count) + ")");
            if (DEBUG)
                Log.d(TAG,
                        "(onTextChanged) mEdtText: \"" + mEdtText.getText()
                                + "\"");
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            if (DEBUG)
                Log.d(TAG,
                        "(beforeTextChanged) In \"" + s + "\" " + count
                                + " characters ("
                                + s.subSequence(start, start + count)
                                + ") are about to be replaced at " + start
                                + " by " + after);
            if (DEBUG)
                Log.d(TAG,
                        "(beforeTextChanged) mEdtText: \""
                                + mEdtText.getText() + "\"");

        }
    }

如果您查看EditText 的源代码,您可以看到从TextView 继承getText 方法并返回CharSequence mText。您也可以定义另一个CharSequence mTransformed。在巨大的setText 方法中,有一个时刻mTextmTransformed 取代。可能当您致电from_locationgetText 时,您会得到mText,而在setText 启动后第二次这样做,您会得到mTransformed 作为答案。

如果你想检查这个就改变

CharSequence cs = from_location.getText();
Log.d(... + cs + ...); // no need to call toString as implicit call.
...
Log.d(... + cs.length() + ...);

【讨论】:

  • 那么要解决获取mText的问题,如你所说,在特定时间点可能为空,我该怎么办?
  • 顺便说一句,我尝试记录 CharSequence s,它返回的值与我的 EditText 相同。此外,我尝试在afterTextChanged() 方法中获取文本,如果问题是在替换文本时获取文本,该方法应该可以工作。但它仍然给出了空文本。即使我在beforeTextChanged() 方法中也面临同样的问题。
  • 所以,如果我理解正确的话。当删除您之前在EditText 中写入的单词的某些字符时,这些方法:beforeTextChangedonTextChangedafterTextChanged 在不应该返回空的CharSequence/Editable 时?例如。如果你有“你好”这个词并且你开始删除,会发生什么?删除两个或三个字符后会得到一个空序列,而应该得到“Hel”、“He”等。
  • 是的,你没看错。我有一些文本并开始删除它们。然后在某些时候,即使 EditText 中剩余的字符很少,我也会得到“”。
  • 所以你得到一个EditText,屏幕上有一些字符,而getText返回并为空CharSequence?这是“稳定的”吗,我的意思是,在你得到空文本后,它会一直返回空还是只发生在TextWatcher 的代码中?顺便说一句,您正在测试哪个版本的 android 和设备?并且,您可以在任何其他设备(虚拟机除外)中测试代码吗?我正在尝试复制您的结果,但没有成功...
【解决方案2】:

如果您正在使用调试模式,请记住它有两个存储值的位置。在我的例子中,EditText 有 mText(Spannable String Builder),它的子字段(也是 mText)是带有 ID 的字段。可跨字符串生成器将返回 .toString() 的值。另一个将返回 .getText() 的值。

【讨论】:

  • 听不懂你在说什么。
【解决方案3】:

尝试使用 onTextChange() 中的 CharSequence 应该与 fromLocation.getText() 返回的相同。

【讨论】:

  • s 也给出空字符串。
【解决方案4】:
public void afterTextChanged(Editable s) {
           if(s.length()>=6)
           {

           }
           else{

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

          }

【讨论】:

    【解决方案5】:

    这可能是您需要的。这是我在项目中用于搜索字符串的一些代码。我有一个名为 mySearchMethod 的方法,不用担心。但是在文本更改后,我在方法上得到了我的编辑文本字符串..

     public void search(){
        // Notice I used a final edittext
        final EditText editText = (EditText) findViewById(R.id.search);
    
    
        // create the TextWatcher
        TextWatcher textWatcher = new TextWatcher() {
    
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    
            }
    
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    
            }
    
            @Override
            public void afterTextChanged(Editable editable) {
    
    
                  String searchQuery = editText.getText().toString();
    
                  // This method is just something I did with the string I got
                  MySearchMethod(searchQuery);
    
    
    
    
            }
        };
    
        //we must add the textWatcher to our EditText
        editText.addTextChangedListener(textWatcher);
    
    }
    

    在你的 on create 中调用方法 search() 来初始化它。

    【讨论】:

    • 尝试使用afterTextChanged。同样的问题。也试过beforeTextChanged
    • 只需复制我的代码调用方法在您的创建...确保更改 R ids
    • 复制了你的方法。同样的问题。
    【解决方案6】:

    什么是 fromLocation ? 您应该使用 CharSequence ,如下所示。

    试试这个......

    @Override
     public void onTextChanged(CharSequence s, int start, int before,
                int count) {
    
    // if(fromLocation == null) {
    //         Log.e(TAG, "fromLocation is null.");
    //  }
    
    Log.e(TAG, "fromLocation text : " + s.toString());
    Log.e(TAG, "fromLocation text length :  " + s.toString().length()); 
    
    // Log.e(TAG, "fromLocation id : " + fromLocation.getId());
    // Log.e(TAG, "fromLocation text : " + fromLocation.getText().toString());
    // Log.e(TAG, "fromLocation text length :  " +    //fromLocation.getText().toString().length());            
    }
    

    【讨论】:

    • 已经试过了。不工作。 CharSequence 也有同样的问题。
    【解决方案7】:

    试试这个它会工作的......

    final EditText from_location = (EditText) findViewById(R.id.from_location);
    
        from_location.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub              
            }
    
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub              
            }
    
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
    
                if(from_location == null) {
                    Log.v("", "fromLocation is null.");
            }
    
            Log.v("", "fromLocation id : " + from_location.getId());
            Log.v("", "fromLocation text : " + from_location.getText().toString());
            Log.v("", "fromLocation text length :  " + from_location.getText().toString().length());            
    
            }
        });
    

    【讨论】:

      【解决方案8】:

      我正在根据用户在 First EditText 上的输入更新其他 Second EditText 值,反之亦然。

      所以,对于 First EditText,我添加了如下所示的 TextWatche,它永远不会崩溃,也永远不会陷入任何错误或异常。你可以试试类似的东西。

      final EditText from_location = (EditText) findViewById(R.id.from_location);
      
       from_location.addTextChangedListener(new TextWatcher() {
              @Override
              public void onTextChanged(CharSequence s, int start, int before, int count) {
                  if(!(from_location.getText().toString().equals(""))) {
                      Log.e(TAG, "fromLocation id : " + fromLocation.getId());
                      Log.e(TAG, "fromLocation text : " + fromLocation.getText().toString());
                      Log.e(TAG, "fromLocation text length :  " + fromLocation.getText().toString().length());
                  }else{
                       Log.e(TAG, "fromLocation is null.");
                  }
              }
      
              @Override
              public void beforeTextChanged(CharSequence s, int start, int count,
                      int after) {}
              @Override
              public void afterTextChanged(Editable s) {
      
              }
          });
      

      希望这会对您有所帮助。如果 nits 对您没有帮助,请告诉我。

      享受编码...... :)

      【讨论】:

      • 这只是我的问题。我刚刚更新了我的问题代码以包含所有被覆盖的方法。
      • @Akash 你为什么不试试我的代码?它可以随心所欲地工作。或者让我知道您的实际要求。
      【解决方案9】:

      好了,解决方法就到这里,不用getText获取文本,只需将charSequence传递给

      onTextChanged(CharSequence s, int start, int before,
                          int count)
      

      使用s.toString()回调

      我的示例类如下所示

      package com.peshal.texttest;
      
      import android.app.Activity;
      import android.os.Bundle;
      import android.text.Editable;
      import android.text.TextWatcher;
      import android.util.Log;
      import android.widget.EditText;
      
      public class MainActivity extends Activity {
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          EditText  fromLocation = (EditText) findViewById(R.id.editText1);
          fromLocation.addTextChangedListener(new TextWatcher(){
      
              @Override
              public void afterTextChanged(Editable arg0) {
                  // TODO Auto-generated method stub
      
              }
      
              @Override
              public void beforeTextChanged(CharSequence s, int start, int count,
                      int after) {
                  // TODO Auto-generated method stub
      
              }
      
              @Override
              public void onTextChanged(CharSequence s, int start, int before,
                      int count) {
              Log.d("Current String is :" ,s.toString());
      
              }
      
            });
        }
      
      
       }
      

      【讨论】:

      • 我的代码,如果你看到的话,已经有Log.d(TAG, "S : " + s);。你认为现在做s.toString() 会有什么不同吗?
      【解决方案10】:

      我确实有同样的问题。我的代码在大多数设备上运行良好,但在装有 Android 4.1.2 的 Motorola Razr i 上它随机返回一个空字符串。

      我做了以下解决方法:

      // TextWatcher Methods
      @Override
      public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3)
      {
      }
      
      @Override
      public void onTextChanged(CharSequence charSequence, int i, int i2, int i3)
      {
          fromLocation.post(new Runnable()
          {
      
              @Override
              public void run()
              {
                  Editable text = fromLocation.getText();
                  //... now the string is not empty anymore
              }
          });
      
      }
      
      @Override
      public void afterTextChanged(Editable editable)
      {
      }
      

      虽然我不知道为什么会出现问题 - 将其发布在 Runnable 中(可能延迟)修复了它。并且不影响其他设备上的行为。

      在您的情况下,您可能需要对 fromLocation 进行一些额外的 != null 检查 - 在我的情况下,它永远不会为空。

      【讨论】:

        猜你喜欢
        • 2017-06-07
        • 2013-05-13
        • 1970-01-01
        • 1970-01-01
        • 2015-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-22
        相关资源
        最近更新 更多