java.lang.NullPointerException:尝试在空对象 2017 上调用虚拟方法 'android.text.Editable android.widget.EditText.ge
Posted
技术标签:
【中文标题】java.lang.NullPointerException:尝试在空对象 2017 上调用虚拟方法 \'android.text.Editable android.widget.EditText.getText()\'【英文标题】:java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object 2017java.lang.NullPointerException:尝试在空对象 2017 上调用虚拟方法 'android.text.Editable android.widget.EditText.getText()' 【发布时间】:2017-08-19 15:56:22 【问题描述】:您好,我对 java 和 android 开发非常了解,但是这个错误给我带来了大约三周的麻烦。我已经尝试了所有我知道的关于堆栈溢出的解决方案,例如更改初始化 editText 变量的方式,但仍然没有运气。任何帮助都将不胜感激,因为它似乎不应该有任何错误。
这是我的 mainActivity 类代码:
`public class MainActivity extends AppCompatActivity implements View.OnClickListener
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
public String email;
public String password;
private EditText emailedittext;
private EditText passwordedittext;
private TextView mStatusTextView;
private TextView mDetailTextView;
private static final String TAG = "EmailPassword";
SharedPreferences sharedpref;
private SharedPreferences.Editor loginStateEditor;
ProgressDialog progressdialog;
Handler handler = new Handler();
int status = 0;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig));
setContentView(R.layout.activity_main);
EditText emailedittext = (EditText)findViewById(R.id.emailedittext);
EditText passwordedittext = (EditText)findViewById(R.id.passwordedittext);
final TextView mStatusTextView = (TextView) findViewById(R.id.mStatus);
TextView mDetailTextView = (TextView) findViewById(R.id.mDetail);
Button loginbutton = (Button)findViewById(R.id.login);
Button signupbutton = (Button)findViewById(R.id.signup);
Button signoutbutton = (Button)findViewById(R.id.signout);
findViewById(R.id.login).setOnClickListener(this);
findViewById(R.id.signup).setOnClickListener(this);
findViewById(R.id.signout).setOnClickListener(this);
CreateProgressDialog();
sharedpref = getSharedPreferences("myPref", Context.MODE_PRIVATE);
loginStateEditor = sharedpref.edit();
if (sharedpref.getBoolean("success_login", false))
// Start Your Menu Activity
Intent i = new Intent(MainActivity.this, Menu.class);
i.putExtra(EXTRA_MESSAGE, email);
i.putExtra(EXTRA_MESSAGE, password);
startActivity(i);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener()
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth)
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null)
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
Intent i = new Intent(MainActivity.this, Menu.class);
i.putExtra(EXTRA_MESSAGE, email);
i.putExtra(EXTRA_MESSAGE, password);
startActivity(i);
else
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
updateUI(user);
;
@SuppressLint("StringFormatInvalid")
private void updateUI(FirebaseUser user)
final TextView mStatusTextView = (TextView) findViewById(R.id.mStatus);
TextView mDetailTextView = (TextView) findViewById(R.id.mDetail);
Button loginbutton = (Button)findViewById(R.id.login);
Button signupbutton = (Button)findViewById(R.id.signup);
Button signoutbutton = (Button)findViewById(R.id.signout);
findViewById(R.id.login).setOnClickListener(this);
findViewById(R.id.signup).setOnClickListener(this);
findViewById(R.id.signout).setOnClickListener(this);
hideProgressDialog();
if (user != null)
mStatusTextView.setText(getString(R.string.emailpassword_status_fmt, user.getEmail()));
mDetailTextView.setText(getString(R.string.firebase_status_fmt, user.getUid()));
this.findViewById(R.id.login).setVisibility(View.GONE);
this.findViewById(R.id.signup).setVisibility(View.GONE);
this.findViewById(R.id.mStatus).setVisibility(View.GONE);
this.findViewById(R.id.mDetail).setVisibility(View.GONE);
this.findViewById(R.id.signout).setVisibility(View.VISIBLE);
else
mStatusTextView.setText(R.string.signed_out);
mDetailTextView.setText(null);
this.findViewById(R.id.login).setVisibility(View.VISIBLE);
this.findViewById(R.id.signup).setVisibility(View.VISIBLE);
this.findViewById(R.id.mStatus).setVisibility(View.GONE);
this.findViewById(R.id.mDetail).setVisibility(View.GONE);
this.findViewById(R.id.signout).setVisibility(View.GONE);
private void createAccount(final String email, final String password)
Log.d(TAG, "createAccount:" + email);
if (!validateForm())
return;
showProgressDialog();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
@Override
public void onComplete(@NonNull Task<AuthResult> task)
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful())
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
loginStateEditor.putBoolean("success_login", true);
loginStateEditor.commit();
Intent i = new Intent(MainActivity.this, Menu.class);
i.putExtra(EXTRA_MESSAGE, email);
i.putExtra(EXTRA_MESSAGE, password);
startActivity(i);
hideProgressDialog();
loginStateEditor.putBoolean("success_login", true);
loginStateEditor.commit();
Intent i = new Intent(MainActivity.this, Menu.class);
startActivity(i);
);
private void hideProgressDialog()
progressdialog.dismiss();
private boolean validateForm()
boolean valid = true;
String email = emailedittext.getText().toString();
if (TextUtils.isEmpty(email))
emailedittext.setError("Required.");
valid = false;
else
emailedittext.setError(null);
String password = passwordedittext.getText().toString();
if (TextUtils.isEmpty(password))
passwordedittext.setError("Required.");
valid = false;
else
passwordedittext.setError(null);
return valid;
public void showProgressDialog()
status = 0;
new Thread(new Runnable()
@Override
public void run()
while(status < 100)
status +=1;
try
Thread.sleep(200);
catch(InterruptedException e)
e.printStackTrace();
handler.post(new Runnable()
@Override
public void run()
progressdialog.setProgress(status);
if(status == 100)
progressdialog.dismiss();
);
).start();
@Override
public void onClick(View v)
EditText emailedittext = (EditText)MainActivity.this.findViewById(R.id.emailedittext);
EditText passwordedittext = (EditText)MainActivity.this.findViewById(R.id.passwordedittext);
int i = v.getId();
try
if (i == R.id.signup && emailedittext.getText() != null && passwordedittext.getText() != null)
createAccount(emailedittext.getText().toString(), passwordedittext.getText().toString());
String email = emailedittext.getText().toString();
String password = passwordedittext.getText().toString();
else if (i == R.id.login && emailedittext.getText() != null && passwordedittext.getText() != null)
signIn(emailedittext.getText().toString(), passwordedittext.getText().toString());
String email = emailedittext.getText().toString();
String password = passwordedittext.getText().toString();
else if (i == R.id.signout)
signOut();
catch(Exception e)
e.printStackTrace();
public void CreateProgressDialog()
progressdialog = new ProgressDialog(MainActivity.this);
progressdialog.setIndeterminate(false);
progressdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressdialog.setCancelable(true);
progressdialog.setMax(100);
progressdialog.show();
private void signIn(final String email, final String password)
Log.d(TAG, "signIn:" + email);
if (!validateForm())
return;
showProgressDialog();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(MainActivity.this, new OnCompleteListener<com.google.firebase.auth.AuthResult>()
@Override
public void onComplete(@NonNull Task<AuthResult> task)
Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful())
onSuccess();
Log.w(TAG, "signInWithEmail", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
loginStateEditor.putBoolean("success_login", true);
loginStateEditor.commit();
Intent i = new Intent(MainActivity.this, Menu.class);
i.putExtra(EXTRA_MESSAGE, email);
i.putExtra(EXTRA_MESSAGE, password);
startActivity(i);
if (!task.isSuccessful())
mStatusTextView.setText(R.string.auth_failed);
hideProgressDialog();
);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null)
// Name, email address, and profile photo Url
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getToken() instead.
String uid = user.getUid();
private void signOut()
mAuth.signOut();
updateUI(null);
@Override
protected void onStart()
super.onStart();
@Override
protected void onStop()
super.onStop();
public void onSuccess()
sharedpref.getBoolean("success_login", true);
loginStateEditor.commit();
Intent i = new Intent(MainActivity.this, Menu.class);
i.putExtra(EXTRA_MESSAGE, email);
i.putExtra(EXTRA_MESSAGE, password);
startActivity(i);
`
这是导致错误的具体部分:
@Override
public void onClick(View v)
EditText emailedittext = (EditText)MainActivity.this.findViewById(R.id.emailedittext);
EditText passwordedittext = (EditText)MainActivity.this.findViewById(R.id.passwordedittext);
int i = v.getId();
try
if (i == R.id.signup && emailedittext.getText() != null && passwordedittext.getText() != null)
createAccount(emailedittext.getText().toString(), passwordedittext.getText().toString());
String email = emailedittext.getText().toString();
String password = passwordedittext.getText().toString();
else if (i == R.id.login && emailedittext.getText() != null && passwordedittext.getText() != null)
signIn(emailedittext.getText().toString(), passwordedittext.getText().toString());
String email = emailedittext.getText().toString();
String password = passwordedittext.getText().toString();
else if (i == R.id.signout)
signOut();
catch(Exception e)
e.printStackTrace();
这里是日志:
ittouch W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
03-26 16:15:57.401 5772-5772/com.example.littouchinc.littouch W/System.err: at com.example.littouchinc.littouch.MainActivity.validateForm(MainActivity.java:202)
03-26 16:15:57.401 5772-5772/com.example.littouchinc.littouch W/System.err: at com.example.littouchinc.littouch.MainActivity.createAccount(MainActivity.java:153)
03-26 16:15:57.402 5772-5772/com.example.littouchinc.littouch W/System.err: at com.example.littouchinc.littouch.MainActivity.onClick(MainActivity.java:242)
03-26 16:15:57.402 5772-5772/com.example.littouchinc.littouch W/System.err: at android.view.View.performClick(View.java:5610)
03-26 16:15:57.402 5772-5772/com.example.littouchinc.littouch W/System.err: at android.view.View$PerformClick.run(View.java:22265)
03-26 16:15:57.402 5772-5772/com.example.littouchinc.littouch W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
03-26 16:15:57.402 5772-5772/com.example.littouchinc.littouch W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
03-26 16:15:57.402 5772-5772/com.example.littouchinc.littouch W/System.err: at android.os.Looper.loop(Looper.java:154)
03-26 16:15:57.402 5772-5772/com.example.littouchinc.littouch W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6077)
03-26 16:15:57.402 5772-5772/com.example.littouchinc.littouch W/System.err: at java.lang.reflect.Method.invoke(Native Method)
03-26 16:15:57.402 5772-5772/com.example.littouchinc.littouch W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
03-26 16:15:57.402 5772-5772/com.example.littouchinc.littouch W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
任何帮助将不胜感激,谢谢。
【问题讨论】:
使用emailedittext
而不是EditText emailedittext
因为你已经在类中声明了同名的EdiText。无需在 onClick
方法中再次创建它。对passwordedittext
做同样的事情
【参考方案1】:
将所有Button
、EditText
和TextView
声明为全局。
............
private EditText emailedittext;
private EditText passwordedittext;
private TextView mStatusTextView;
private TextView mDetailTextView;
private Button loginbutton;
private Button signupbutton;
private Button signoutbutton;
.........
...............
更新活动OnCreate()
方法为:
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
...................
......................
emailedittext = (EditText) findViewById(R.id.emailedittext);
passwordedittext = (EditText) findViewById(R.id.passwordedittext);
mStatusTextView = (TextView) findViewById(R.id.mStatus);
mDetailTextView = (TextView) findViewById(R.id.mDetail);
loginbutton = (Button) findViewById(R.id.login);
signupbutton = (Button) findViewById(R.id.signup);
signoutbutton = (Button) findViewById(R.id.signout);
loginbutton .setOnClickListener(this);
signupbutton .setOnClickListener(this);
signoutbutton .setOnClickListener(this);
.................
......................
将您的 updateUI()
方法更新为:
@SuppressLint("StringFormatInvalid")
private void updateUI(FirebaseUser user)
hideProgressDialog();
if (user != null)
mStatusTextView.setText(getString(R.string.emailpassword_status_fmt, user.getEmail()));
mDetailTextView.setText(getString(R.string.firebase_status_fmt, user.getUid()));
loginbutton.setVisibility(View.GONE);
signupbutto.setVisibility(View.GONE);
mStatusTextView.setVisibility(View.GONE);
mDetailTextView.setVisibility(View.GONE);
signoutbutton.setVisibility(View.VISIBLE);
else
mStatusTextView.setText(R.string.signed_out);
mDetailTextView.setText(null);
loginbutton.setVisibility(View.VISIBLE);
signupbutton.setVisibility(View.VISIBLE);
mStatusTextView.setVisibility(View.GONE);
mStatusTextView.setVisibility(View.GONE);
signoutbutton.setVisibility(View.GONE);
更新onClick()
方法为:
@Override
public void onClick(View v)
int i = v.getId();
try
if (i == R.id.signup && emailedittext.getText() != null && passwordedittext.getText() != null)
createAccount(emailedittext.getText().toString(), passwordedittext.getText().toString());
String email = emailedittext.getText().toString();
String password = passwordedittext.getText().toString();
else if (i == R.id.login && emailedittext.getText() != null && passwordedittext.getText() != null)
signIn(emailedittext.getText().toString(), passwordedittext.getText().toString());
String email = emailedittext.getText().toString();
String password = passwordedittext.getText().toString();
else if (i == R.id.signout)
signOut();
catch(Exception e)
e.printStackTrace();
希望这会有所帮助!
【讨论】:
你是个天才!我不知道为什么,但是如果您已经在 onCreate 方法和全局变量中初始化了小部件,再次初始化它会使参数为空。非常感谢您提供此解决方案,因为我已经坚持了大约三周。谢谢【参考方案2】:你为什么一次又一次地使用这些行?
EditText emailedittext = (EditText)findViewById(R.id.emailedittext);
EditText passwordedittext = (EditText)findViewById(R.id.passwordedittext);
EditText emailedittext,passworditext 已经被声明为变量。 所以,只需使用
emailedittext = (EditText)findViewById(R.id.emailedittext);
passwordedittext = (EditText)findViewById(R.id.passwordedittext);
另外,从 onCreate() 中删除这些行。你不需要在这里定义它们,因为它们已经在 OnCreate() 中定义了
EditText emailedittext = (EditText)MainActivity.this.findViewById(R.id.emailedittext);
EditText passwordedittext = (EditText)MainActivity.this.findViewById(R.id.passwordedittext);
【讨论】:
【参考方案3】:错误消息说您尝试在空对象上调用 getText()。在 MainActivity.java:202 行之前检查 emailedittext 或 passwordedittext 是否为空。
【讨论】:
【参考方案4】:您是否有任何具体原因要添加以下行:
EditText emailedittext = (EditText)MainActivity.this.findViewById(R.id.emailedittext);
EditText passwordedittext = (EditText)MainActivity.this.findViewById(R.id.passwordedittext);
这些不是必需的,因为您已在 OnCreate 中对其进行了初始化。是不是一直有问题。它在您第一次启动应用程序时有效吗?如果它第一次工作并在暂停应用程序后崩溃,那么最好在 OnResume 中初始化所有视图。
【讨论】:
以上是关于java.lang.NullPointerException:尝试在空对象 2017 上调用虚拟方法 'android.text.Editable android.widget.EditText.ge的主要内容,如果未能解决你的问题,请参考以下文章
亲測,Eclipse报"An error has occurred,See error log for more details. java.lang.NullPointerExce