Java.lang.NullPointerException: Try invoking the virtual method 'android.text.Editable android.widget.EditText.getText ()' on a null object 2017

advertisements

Hello I am fairly well informed with java and android developing, but this error has given me trouble for about three weeks. I have tried all of the solutions on stack overflow that I know of such as changing the way I initialize the editText variables, but still no luck. Any help would be much appreciated because it would seem as though there shouldn't be any error.

Here is my mainActivity class code:

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

} `

Here is the specific part that causes the error:

 @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();
    }
}

Here is the 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)

Any help would be much appreciated thank you.


  1. Declare all Button, EditText and TextView as Global.

    ............
    private EditText emailedittext;
    private EditText passwordedittext;
    private TextView mStatusTextView;
    private TextView mDetailTextView;
    private Button loginbutton;
    private Button signupbutton;
    private Button signoutbutton;
    .........
    ...............
    
    
  2. Update activity OnCreate() method as:

    @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. Update your updateUI() method as:

    @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. Update onClick() method as:

    @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();
        }
     }
    
    

Hope this will help!