好吧,NullPointerException
当我打电话findViewById()
访问一个按钮时,我得到一个提示。我想我理解为什么会收到此错误,但是我的脑海中还没有解决一些问题。好吧,我想收到这个错误是因为我将findViewById()
调用从onCreate()
方法内部移动到了所有方法之外的类范围。
因此,现在我在方法之外初始化Button
的和。好吧,如果我理解正确,就会发生这种情况(空错误),因为该方法在该方法之后被调用,所以这就是它引发异常的原因。EditText
onCreate()
setContentView()
findViewById()
但是我不明白的是,我在第二项活动中做过同样的事情,并且在没有任何空异常的情况下工作良好。而且我正在onCreate()
方法外初始化Buttons !
确实使我有些困惑。任何帮助清除我脑海中的问题,将不胜感激。
第一次活动
public class FirstActivity extends AppCompatActivity {
private Button signUpButton= findViewById(R.id.lo_signUpButton);
private Button loginButton = findViewById(R.id.lo_loginButton);
private EditText username= findViewById(R.id.lo_usernameText);
private EditText password= findViewById(R.id.lo_passwordText);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set view
setContentView(R.layout.activity_login);
Log.i(TAG,"Create "+formatter.format(new Date()));
//listeners
signUpButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
finish();
}
});
}
第二次活动
public class SecondActivity extends AppCompatActivity {
private EditText username = findViewById(R.id.su_username);
private EditText password = findViewById(R.id.su_password);
private TextView errorText= findViewById(R.id.su_error_msg);
private Button signUpButton=findViewById(R.id.su_signupButton);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set view
setContentView(R.layout.activity_signup);
Log.i(TAG,"Create");
//listeners
Button backButton = findViewById(R.id.su_backButton);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(SignUpActivity.this, LoginActivity.class));
Log.i(TAG,"Going Back ");
finish();
}
});
您不能使用以下初始化:
public class SecondActivity extends AppCompatActivity {
private Button signUpButton= findViewById(R.id.lo_signUpButton);
//....
}
用:
public class SecondActivity extends AppCompatActivity {
private Button signUpButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set view
setContentView(R.layout.activity_signup)
signUpButton= findViewById(R.id.lo_signUpButton);
//...
}
}
在第二个活动中,您正在做一些不同的事情:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
Button backButton = findViewById(R.id.su_backButton);
//...
}
并且它是正确的,因为您在调用之后backButton
用findViewById
方法内部声明和初始化。onCreate
setContentView
在第一个活动中,您正在使用设置侦听器,signUpButton.setOnClickListener
但未signUpButton
初始化(因为它在onCreate
方法之外)
同样在第二活动中,OnCreate
方法中未使用其他未正确初始化的按钮。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句