【问题标题】:Get int Value Of EditText获取 EditText 的 int 值
【发布时间】:2023-03-14 20:35:01
【问题描述】:

我无法在 Androis Studio 中获取 EditText 的 int 值 我用Int FirstValue = Integer.parseInt(FirstInput.getText().toString()); 但是当我使用它时,我的应用程序将在 Evulator 中停止! 此问题适用于我所有的 Android Studio 应用程序

【问题讨论】:

  • 它是int firstValue = Integer.parseInt(FirstInput.getText().toString());。在将字符串解析为 int 之前,还要确保 FirstInput 不为空。
  • 我怎么知道 firstInput 是否为空?
  • if (FirstInput != null)

标签: java android


【解决方案1】:

首先,确保您的 EditText 在您的布局文件中有一个id

<EditText 
android:id="@+id/FirstInput" 
android:width="220px" />

接下来,在您的活动中,确保您有以下代码,它不必在您的 onCreate() 方法中,因为 EditText 将有一个空值。但同样的基本原则也适用;

EditText FirstInput;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);

    FirstInput   = (EditText)findViewById(R.id.FirstInput);
    try{
    int firstValue = Integer.parseInt(FirstInput.getText().toString());
    }catch(Exception e){
     // Do something to handle the error;
    }
}

【讨论】:

    【解决方案2】:

    这是

    if(!FirstInput.getText().toString().equals(""){
    int firstValue = Integer.parseInt(FirstInput.getText().toString());
    } else {
     //Display a toast for handling null value in EditText or something.
    }
    

    【讨论】:

    • 请分享崩溃日志猫?
    【解决方案3】:

    这仍然是崩溃的意思,您没有使用 EditText 的有效 id 或者您正在尝试转换不是数字的整数(作为字符串)。

    尝试为上面的代码块设置一些 try catch 块并查看。 仍然如果您看不到数字格式异常,肯定是 EditText 的 id 或者您正在使用的布局中可能不存在 edittext(例如:edittext 存在于 layout-large 但不存在布局目录布局文件中)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      相关资源
      最近更新 更多