java.lang.NullPointerException:尝试在空对象2017上调用虚拟方法'android.text.Editable android.widget.EditText.getText()'

时间:2017-03-27 04:32:02

标签: java android android-intent android-emulator

您好我对java和android开发的了解非常充分,但这个错误给我带来了大约三个星期的麻烦。我已经尝试了所有关于堆栈溢出的解决方案,比如我改变初始化editText变量的方式,但仍然没有运气。任何帮助都会非常感激,因为它似乎不应该有任何错误。

这是我的mainActivity类代码:

`public class MainActivity extends AppCompatActivity实现了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();
    }
}

这是logcat:

    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)

非常感谢任何帮助。谢谢。

4 个答案:

答案 0 :(得分:0)

你为什么一次又一次地使用这些线?

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

答案 1 :(得分:0)

错误消息表示您尝试在null对象上调用getText()。在MainActivity.java:202行之前检查emailedittext或passwordedittext是否为null。

答案 2 :(得分:0)

您是否有任何具体原因要添加以下行:

 EditText emailedittext = (EditText)MainActivity.this.findViewById(R.id.emailedittext);
 EditText passwordedittext = (EditText)MainActivity.this.findViewById(R.id.passwordedittext);

因为您已在OnCreate中初始化它们,所以不需要这些。这总是问题。它是否在您第一次启动应用程序时有效?如果它第一次工作并在暂停应用程序后崩溃,那么最好初始化OnResume中的所有视图。

答案 3 :(得分:0)

  1. 将所有ButtonEditTextTextView声明为全球。

    ............
    private EditText emailedittext;
    private EditText passwordedittext;
    private TextView mStatusTextView;
    private TextView mDetailTextView;
    private Button loginbutton;
    private Button signupbutton;
    private Button signoutbutton;
    .........
    ...............
    
  2. 将活动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);
        .................
        ......................
    }
    
  3. 将您的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);
    }
    }
    
  4. 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();
        }
     }
    
  5. 希望这会有所帮助!