【问题标题】:Null pointer Exception on .setOnClickListener.setOnClickListener 上的空指针异常
【发布时间】:2015-03-27 10:18:43
【问题描述】:

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

这是错误。

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

我对什么是空指针异常有一个合理的理解,并且我已经彻底搜索了一个与我类似的问题。我尝试以多种方式重新格式化点击监听器,确保我有正确的视图 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);
            }
        });
    }

显然还有更多,但与我认为的主题无关。 这是带有按钮的对话框的 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>

任何帮助将不胜感激。

【问题讨论】:

  • 差不多一年后回到这里,感觉很好,我已经改进了很多,并且从像这样的愚蠢错误中吸取了教训。每个人都从某个地方开始,我喜欢 Stack 会支持你的每一步。
  • 我仍然有这个问题,只是我的按钮不在Login Dialog 中。 @Jack.Ramsden 我该如何解决?

标签: java android nullpointerexception onclicklistener


【解决方案1】:

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

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

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

【讨论】:

  • 哇,我怎么没看到。我认为这是因为异常指向下面的行。感谢您的帮助
  • 如果我的按钮不在login_modal 内,但我仍然得到同样的错误,@ρяσѕρєя K,怎么办? ?
【解决方案2】:

Submitnull,因为它不是 activity_main.xml 的一部分

当您在Activity 中调用findViewById 时,它会在您的活动布局中查找View

试试这个:

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

另一件事:你使用

android:layout_below="@+id/LoginTitle"

但你想要的可能是

android:layout_below="@id/LoginTitle"

请参阅this question 了解@id@+id 之间的区别。

【讨论】:

  • 谢谢你,养成一个好习惯,而不是复制粘贴其他ID。我之前不明白 + 的意义。从来没想过要调查它。 (添加为已接受以获得稍微完善的答案和一些额外的帮助)
  • 我有类似的问题,但是我的按钮不在对话框窗口中。我该如何纠正它,@2Dee?
  • @DerryckDX 没有看到你的代码很难知道,我们不应该在 cmets 部分这样做。请在检查重复项后发布新问题。不要忘记包含所有相关代码和错误堆栈跟踪。
【解决方案3】:

尝试在 main.xml 中为您的 Button 指定一个更具描述性的名称,例如:

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

(在您的 xml 文件中至少使用小写字母)

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

Button buttonXYZ;

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

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

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

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

【讨论】:

    【解决方案4】:

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

    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) {
                }
        });
    

    我让它按如下所示的正确顺序放置代码

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

    【讨论】:

      猜你喜欢
      • 2019-07-18
      • 2012-03-09
      • 1970-01-01
      • 2015-10-29
      • 2021-01-19
      • 2013-08-12
      • 2019-12-09
      • 1970-01-01
      相关资源
      最近更新 更多