findViewById()以两个整数的总和返回null简单的应用程序[重复]

问题描述 投票:0回答:1

我是android的新手。我已经编写了两个整数的Sum代码。我收到NULLPointerException。 findViewById()方法返回null。有人可以帮我修复错误。

    <EditText
        android:id="@+id/firstInt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:hint="@string/InputHint"
        />


    <EditText
        android:id="@+id/secondInt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:hint="@string/InputHint"
        />

    <TextView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Result"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:textSize="18dp"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/add"
        android:layout_gravity="center"
        android:onClick="calculateAdd"/>

main activity.Java:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText e1 = (EditText)findViewById(R.id.firstInt);
        EditText e2 = (EditText)findViewById(R.id.secondInt);
        TextView tv = (TextView)findViewById(R.id.result);
    }

    public void calculateAdd(View view){

            int x = Integer.parseInt(e1.getText().toString());
            int y = Integer.parseInt(e2.getText().toString());

            int z = x + y;

        tv.setText(z);
    }

这是我编写的一个非常简单的程序。但是,面对这个问题。

我的堆栈跟踪错误:

java.lang.IllegalStateException: Could not execute method for android:onClick at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
android android-layout
1个回答
6
投票

你只是在EditText方法的范围内声明onCreate()

EditText e1, e2;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    e1 = (EditText)findViewById(R.id.firstInt);
    e2 = (EditText)findViewById(R.id.secondInt);
    tv = (TextView)findViewById(R.id.result);
}

public void calculateAdd(View view){   
    int x = Integer.parseInt(e1.getText().toString());
    int y = Integer.parseInt(e2.getText().toString());

    int z = x + y;
    tv.setText(z);
}  

愿这对你有所帮助。

如果您需要更多信息,请参阅此链接https://stackoverflow.com/a/51688200/5343866

© www.soinside.com 2019 - 2024. All rights reserved.