java - Android Studio 打印 EditText 返回 null

标签 java android

我创建了一个简单的应用程序,用户输入他们的姓名和分数(只能是整数),然后通过单击按钮,它应该将这两个 EditText 框中的数据打印到日志中。问题是我的名称为 Null,分数为零。

//主要

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    Button SaveDataButton;
    EditText TextName, TextScore;
    String Name;
    int Score;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();

                SaveDataButton = (Button) findViewById(R.id.button);
                TextName = (EditText) findViewById(R.id.editText1);
                TextScore = (EditText) findViewById(R.id.editText2);
                Name = TextName.getText().toString();
                Score = Integer.parseInt(TextScore.getText().toString());

            }
        });
    }


    public void SaveDataOnClick (View view){
        System.out.println(Name);
        System.out.println(Score);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

//布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.capstoneproject.module08courseproject_datastorage.MainActivity"
    tools:showIn="@layout/activity_main">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/textView3"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="31dp"
        android:weightSum="1">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Name"
            android:id="@+id/textView" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText1"
            android:layout_gravity="center_horizontal" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Score"
            android:id="@+id/textView2" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText2"
            android:layout_gravity="center_horizontal" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Save Data"
            android:id="@+id/button"
            android:layout_gravity="center_horizontal"
            android:onClick="SaveDataOnClick" />

    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Name and Score Data Storage"
        android:id="@+id/textView3"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

//输出

11-29 22:07:01.846 3192-3192/? I/System.out: null
11-29 22:07:01.846 3192-3192/? I/System.out: 0

最佳答案

编辑,因为我错过了这样一个事实:您将匿名 onClickListener 中的小部件连接到您的 FloatingActionButton。进行以下更改来修复它:

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
  setSupportActionBar(toolbar);

  FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
  fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
      Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
        .setAction("Action", null).show();

      // remove all the widget stuff and move it outside
    }
  });

  SaveDataButton = (Button) findViewById(R.id.button);
  TextName = (EditText) findViewById(R.id.editText1);
  TextScore = (EditText) findViewById(R.id.editText2);
  //Name = TextName.getText().toString();
  //Score = Integer.parseInt(TextScore.getText().toString());

}

您编写的方式是,只有单击 float 操作按钮( Material 设计应用程序右下角的圆形按钮)时,才会执行上面的最后 5 行代码。我认为这不是您的预期行为。相反,您希望获取小部件引用并在 Activity 管理器调用 onCreate() 时保留它们。

我注释掉了最后两行,因为此时两个编辑文本中的值为空。这对于名称来说毫无用处,并且会导致分数出现数字格式异常(无法将 null 转换为数字)。

最后,我认为您希望在用户单击“SAVE DATA”按钮时获取实际值,因此请修改您的 SaveDataOnClick 方法。请记住,每次单击/点击按钮时都会调用此方法,因此它将获取编辑文本字段中的当前值。像这样的事情:

public void SaveDataOnClick (View view){
  Name = TextName.getText().toString();
  Score = Integer.parseInt(TextScore.getText().toString());
  System.out.println(Name);
  System.out.println(Score);
}

我进行了这些更改,这是我的日志输出:

11-29 22:44:22.696 20997-20997/? I/System.out: bobby
11-29 22:44:22.696 20997-20997/? I/System.out: 123

关于java - Android Studio 打印 EditText 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33990903/

相关文章:

安卓通话录音功能

java - 如何在进度条上显示进度(Retrofit 下载)

java - 当有多个 quartz 线程时,让 quartz 只在一个线程中执行作业

java - Spring Security 角色层次结构@Secured JavaConfig

java - 来自 Java 插件的 Gradle 任务测试的 JVM 分支选项

Android、Open GL ES、裁剪和缩放纹理

java - 我可以使用什么库来解析 Java 中的 Schedule String

java - Eclipse 中的自动激活

java - 自定义字符串分隔符 stringtemplate-4

android - Scrollview 只能托管一个直接子级