Java .setOnClickListener 上的空指针异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28193552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:45:56  来源:igfitidea点击:

Null pointer Exception on .setOnClickListener

javaandroidnullpointerexceptiononclicklistener

提问by Hyman.Ramsden

I am having an issue with a click listener for a login modal submit button.

我遇到了登录模式提交按钮的单击侦听器问题。

This is the error.

这是错误。

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

I have a reasonable understanding of what a null pointer exception is and I have search thoroughly for an issue similar to mine. I have tried to reformat the click listener in several ways, made sure I have the correct view ID etc.

我对什么是空指针异常有一个合理的理解,并且我已经彻底搜索了与我类似的问题。我尝试以多种方式重新格式化点击侦听器,确保我拥有正确的视图 ID 等。

package...
import...
public class MainActivity extends ActionBarActivity implements     NavigationDrawerFragment.NavigationDrawerCallbacks {

    //Variables
    String currentPage = "";
    Stack<String> crumbs = new Stack<String>();
    //Fragment managing the behaviors, interactions and presentation of the navigation drawer.
    private NavigationDrawerFragment mNavigationDrawerFragment;
    // Used to store the last screen title. For use in {@link #restoreActionBar()}.
    public CharSequence mTitle;
    //temp
    AuthenticateUserTokenResult authenticateUserTokenResult;
    String loginErrorMessage = "";
    String loginErrorTitle = "";
    Boolean logonSuccessful = false;
    Dialog loginDialog;

    // Login EditTexts
    EditText Username;
    EditText CompanyID;
    EditText Password;
    Button Submit;

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

        mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();  // Set up the drawer.
        mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));

        if(authenticateUserTokenResult == null) {
            attemptLogin();
        }
    }

    public void attemptLogin() {
        loginDialog = new Dialog(this,android.R.style.Theme_Translucent_NoTitleBar);
        loginDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        loginDialog.setContentView(R.layout.login_modal);
        loginDialog.setCancelable(false);
        //loginDialog.setOnCancelListener(cancelListener);
        loginDialog.show();
        Submit = (Button)findViewById(R.id.Submit);
        Submit.setOnClickListener(new View.OnClickListener() // the error is on this line (specifically the .setOnClickListener)
        {
            @Override
            public void onClick(View v)
            {
                ClyxUserLogin user = new ClyxUserLogin();
                Username = (EditText)findViewById(R.id.Username);
                user.logon = Username.getText().toString();
                CompanyID = (EditText)findViewById(R.id.CompanyID);
                user.idCompany = Integer.parseInt(CompanyID.getText().toString());
                Password = (EditText)findViewById(R.id.Password);
                user.password = Password.getText().toString();
                user.idApplication = 142;
                authenticate(user);
            }
        });
    }

There is more, obviously, but not relevant to the topic I think. Here is the XML file for the dialog that has the button on it.

显然,还有更多,但与我认为的主题无关。这是带有按钮的对话框的 XML 文件。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#3366FF">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="#FFFFFF" >

        <TextView
            android:id="@+id/LoginTitle"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_marginTop="10dp"
            android:layout_marginStart="10dp"
            android:textColor="#000000"
            android:textSize="20sp"
            android:text="Login" />

        <EditText
            android:id="@+id/Username"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/LoginTitle"
            android:layout_margin="10dp"
            android:hint="Username" />

        <EditText
            android:id="@+id/CompanyID"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/Username"
            android:layout_alignStart="@+id/Username"
            android:inputType="number"
            android:hint="Company ID" />

        <EditText
            android:id="@+id/Password"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/CompanyID"
            android:layout_alignStart="@+id/Username"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:inputType="textPassword"
            android:hint="Password" />

        <Button
            android:id="@+id/Submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/Password"
            android:layout_marginBottom="10dp"
            android:layout_centerHorizontal="true"
            android:text="Login" />

    </RelativeLayout>

</RelativeLayout>

Any help would be greatly appreciated.

任何帮助将不胜感激。

采纳答案by 2Dee

Submitis nullbecause it is not part of activity_main.xml

Submitnull因为它不属于activity_main.xml

When you call findViewByIdinside an Activity, it is going to look for a Viewinside your Activity's layout.

当您findViewById在 an 内部调用时Activity,它会View在您的 Activity 布局中寻找 a 。

try this instead :

试试这个:

Submit = (Button)loginDialog.findViewById(R.id.Submit);

Another thing : you use

另一件事:你使用

android:layout_below="@+id/LoginTitle"

but what you want is probably

但你想要的可能是

android:layout_below="@id/LoginTitle"

See this questionabout the difference between @idand @+id.

这个问题有关的区别@id@+id

回答by ρяσ?ρ?я K

android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' 在一个空对象引用上

Because Submitbutton is inside login_modalso you need to use loginDialogview to access button:

因为Submit按钮在里面login_modal所以你需要使用loginDialog视图来访问按钮:

Submit = (Button)loginDialog.findViewById(R.id.Submit);

回答by BenJaminSila

Try giving your Button in your main.xml a more descriptive name such as:

尝试给 main.xml 中的 Button 一个更具描述性的名称,例如:

<Button
                android:id="@+id/buttonXYZ"

(use lowercase in your xml files, at least, the first letter)

(在您的 xml 文件中使用小写,至少是第一个字母)

And then in your MainActivity class, declare it as:

然后在您的 MainActivity 类中,将其声明为:

Button buttonXYZ;

Button buttonXYZ;

In your onCreate(Bundle savedInstanceState) method, define it as:

在您的 onCreate(Bundle savedInstanceState) 方法中,将其定义为:

buttonXYZ = (Button) findViewById(R.id.buttonXYZ);

Also, move the Buttons/TextViews outside and place them before the .setOnClickListener - it makes the code cleaner.

此外,将 Buttons/TextViews 移到外面并将它们放在 .setOnClickListener 之前 - 它使代码更清晰。

Username = (EditText)findViewById(R.id.Username);
CompanyID = (EditText)findViewById(R.id.CompanyID);

回答by Jose Kj

I too got similar error when i misplaced the code

当我放错代码时,我也遇到了类似的错误

text=(TextView)findViewById(R.id.text);// this line has to be below setcontentview
setContentView(R.layout.activity_my_otype);
//this is the correct place
text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            }
    });

I got it working on placing the code in right order as shown below

我开始按照正确的顺序放置代码,如下所示

setContentView(R.layout.activity_my_otype);
text=(TextView)findViewById(R.id.text);
 text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            }
    });