获取EditText上的空对象引用

huangapple go评论77阅读模式
英文:

Getting Null Object reference on Edittext

问题

我知道这个问题看起来与SO上的其他问题相似,但我已经尝试了其他相似问题中的所有建议,但没有取得任何成功。

我收到了以下错误:

2020-08-03 20:41:21.372 8916-8916/com.example.spacing E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.spacing, PID: 8916
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.spacing/com.example.spacing.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2843)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        ...

在这段代码上出现问题:

package com.example.spacing;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    public int firstValue;
    EditText first;
    String firstString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        first = (EditText)findViewById(R.id.firstNum);
        firstString = first.getText().toString();

        Button Go = (Button) findViewById(R.id.goButton);
        Go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                firstValue = Integer.parseInt(firstString);
                System.out.print(firstValue);
            }
        });
    }
}

这是XML布局:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <!-- 其他视图元素 -->

</androidx.constraintlayout.widget.ConstraintLayout>

我尝试过的建议:

  • 我尝试将EditText的初始化放在on-create之前和之后。
  • 我确保所有ID都是正确的,引用了正确的元素。

还有其他几种方法,我无法回忆起来,但当我尝试构建时,它们都没有起作用。

任何帮助都将不胜感激。

英文:

I know that this question looks similar to others on SO but i have tried all the suggestions in the other similar questions and haven't had any success.

I'm getting this error:

2020-08-03 20:41:21.372 8916-8916/com.example.spacing E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.spacing, PID: 8916
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.spacing/com.example.spacing.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method &#39;android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()&#39; on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2843)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method &#39;android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()&#39; on a null object reference
        at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:159)
        at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
        at android.content.Context.obtainStyledAttributes(Context.java:675)
        at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
        at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
        at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
        at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
        at com.example.spacing.MainActivity.&lt;init&gt;(MainActivity.java:15)
        at java.lang.Class.newInstance(Native Method)
        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
        at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1215)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2831)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)&#160;
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)&#160;
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)&#160;
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)&#160;
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)&#160;
        at android.os.Handler.dispatchMessage(Handler.java:106)&#160;
        at android.os.Looper.loop(Looper.java:193)&#160;
        at android.app.ActivityThread.main(ActivityThread.java:6669)&#160;
        at java.lang.reflect.Method.invoke(Native Method)&#160;
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)&#160;
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)&#160;
2020-08-03 20:41:21.411 8916-8916/com.example.spacing I/Process: Sending signal. PID: 8916 SIG: 9

on this code:

    package com.example.spacing;
    
    import androidx.appcompat.app.AlertDialog;
    import androidx.appcompat.app.AppCompatActivity;
    
    
    import android.content.Context;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    
    public class MainActivity extends AppCompatActivity {
        public int firstValue;
        EditText first;
        String firstString;
    
    
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            first = (EditText)findViewById(R.id.firstNum);
            firstString = first.getText().toString();
    
            Button Go = (Button) findViewById(R.id.goButton);
            Go.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                        firstValue = Integer.parseInt(firstString);
                        System.out.print(firstValue);
                }

        });
    }


}

Here is the XML:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    tools:context=&quot;.MainActivity&quot;&gt;


    &lt;Button
        android:id=&quot;@+id/goButton&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/buttonName&quot;
        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintHorizontal_bias=&quot;0.498&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot;
        app:layout_constraintVertical_bias=&quot;0.898&quot; /&gt;

    &lt;TextView
        android:id=&quot;@+id/FirstAttribute&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/spacedMaterial&quot;
        app:layout_constraintBottom_toTopOf=&quot;@+id/goButton&quot;
        app:layout_constraintEnd_toStartOf=&quot;@+id/firstNum&quot;
        app:layout_constraintHorizontal_bias=&quot;0.457&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot;
        app:layout_constraintVertical_bias=&quot;0.043&quot; /&gt;

    &lt;EditText
        android:id=&quot;@+id/firstNum&quot;
        android:layout_width=&quot;165dp&quot;
        android:layout_height=&quot;40dp&quot;
        android:ems=&quot;10&quot;
        android:hint=&quot;@string/inMM&quot;
        android:importantForAutofill=&quot;no&quot;
        android:inputType=&quot;number&quot;
        app:layout_constraintBottom_toBottomOf=&quot;@+id/FirstAttribute&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintHorizontal_bias=&quot;0.934&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;@+id/FirstAttribute&quot;
        app:layout_constraintVertical_bias=&quot;0.476&quot; /&gt;



    &lt;TextView
        android:id=&quot;@+id/secondAttribute&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/amount&quot;
        app:layout_constraintBottom_toTopOf=&quot;@+id/goButton&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintHorizontal_bias=&quot;0.073&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot;
        app:layout_constraintVertical_bias=&quot;0.131&quot; /&gt;

    &lt;EditText
        android:id=&quot;@+id/secondNumber&quot;
        android:layout_width=&quot;165dp&quot;
        android:layout_height=&quot;40dp&quot;
        android:ems=&quot;10&quot;
        android:hint=&quot;@string/number&quot;
        android:importantForAutofill=&quot;no&quot;
        android:inputType=&quot;number&quot;
        app:layout_constraintBottom_toBottomOf=&quot;@+id/secondAttribute&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintHorizontal_bias=&quot;0.934&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;@+id/secondAttribute&quot; /&gt;

    &lt;TextView
        android:id=&quot;@+id/thirdAttribute&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/areaWidth&quot;
        app:layout_constraintBottom_toTopOf=&quot;@+id/goButton&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintHorizontal_bias=&quot;0.068&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot;
        app:layout_constraintVertical_bias=&quot;0.218&quot; /&gt;

    &lt;EditText
        android:id=&quot;@+id/thirdNumber&quot;
        android:layout_height=&quot;40dp&quot;
        android:layout_width=&quot;165dp&quot;
      android:ems=&quot;10&quot;
        android:hint=&quot;@string/inMM&quot;
        android:inputType=&quot;number&quot;
        app:layout_constraintBottom_toBottomOf=&quot;@+id/thirdAttribute&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintHorizontal_bias=&quot;0.934&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;@+id/thirdAttribute&quot;
        app:layout_constraintVertical_bias=&quot;0.476&quot;
        android:importantForAutofill=&quot;no&quot; /&gt;

&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

Suggestions i have tried:

I have tried changing the init for the edit text to before and after on-create.
I have made sure that all ids are correct and are referencing the right thing.

And about 5 other things that i cant recall but none of them worked when i tried to build.

Any help is appreciated.

答案1

得分: 0

问题是:
您试图在单击监听器之外初始化“firstString”变量,并且在创建Activity时立即进行初始化,这意味着该变量将始终是一个空对象,因为您实际上没有在EditText中写入任何内容。

只需在ClickListener内部初始化String!

package com.example.spacing;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    public int firstValue;
    EditText first;
    String firstString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        first = (EditText)findViewById(R.id.firstNum);

        Button Go = (Button) findViewById(R.id.goButton);
        Go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                firstString = first.getText().toString();
                firstValue = Integer.parseInt(firstString);
                System.out.print(firstValue);
            }
        });
    }
}
英文:

Problem is:
you are trying to initialize the "firstString" variable OUTSIDE of the click listener and as soon as the Activity is created, which means the variable will always be a null object because you did not actually write something in the EditText.

Simply initialize the String inside the ClickListener!

` package com.example.spacing;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;


import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    public int firstValue;
    EditText first;
    String firstString;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        first = (EditText)findViewById(R.id.firstNum);
        

        Button Go = (Button) findViewById(R.id.goButton);
        Go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    firstString = first.getText().toString();
                    firstValue = Integer.parseInt(firstString);
                    System.out.print(firstValue);
            }

    });
}

}`

huangapple
  • 本文由 发表于 2020年8月4日 20:13:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63246657.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定