-1

I am trying to pass through a username (EMAIL) into the createLoginSession within my SharedPreferencesManagement class. When I try to execute this on the login i'm getting an error which states that "createLoginSession(java.lang.String) on a null object reference".

public class SessionManagement {
// Shared Preferences
SharedPreferences pref;

// Editor for Shared preferences
Editor editor;

// Context
Context _context;

// Shared pref mode
int PRIVATE_MODE = 0;

// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";

// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";


// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";

// Constructor
public SessionManagement(Context context){
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

/**
 * Create login session
 * */
public void createLoginSession(String email){
    // Storing login value as TRUE
    editor.putBoolean(IS_LOGIN, true);

    // Storing email in pref
    editor.putString(KEY_EMAIL, email);

    // commit changes
    editor.commit();
}

/**
 * Check login method wil check user login status
 * If false it will redirect user to login page
 * Else won't do anything
 * */
public void checkLogin(){
    // Check login status
    if(!this.isLoggedIn()){
        // user is not logged in redirect him to Login Activity
        Intent i = new Intent(_context, ActivityLogin.class);
        // Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Staring Login Activity
        _context.startActivity(i);
    }

}



/**
 * Get stored session data
 * */
public HashMap<String, String> getUserDetails(){
    HashMap<String, String> user = new HashMap<String, String>();

    // user email id
    user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));

    // return user
    return user;
}

/**
 * Clear session details
 * */
public void logoutUser(){
    // Clearing all data from Shared Preferences
    editor.clear();
    editor.commit();

    // After logout redirect user to Loing Activity
    Intent i = new Intent(_context, ActivityLogin.class);
    // Closing all the Activities
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    // Add new Flag to start new Activity
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    // Staring Login Activity
    _context.startActivity(i);
}

/**
 * Quick check for login
 * **/
// Get Login State
public boolean isLoggedIn(){
    return pref.getBoolean(IS_LOGIN, false);
}

The code for the Activity Login is as follows:

package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatTextView;
import android.util.Log;
import android.view.View;

import com.example.myapplication.R;
import com.example.myapplication.InputValidation;
import com.example.myapplication.DatabaseHelper;

public class ActivityLogin extends AppCompatActivity implements 
View.OnClickListener {
private final AppCompatActivity activity = ActivityLogin.this;

private NestedScrollView nestedScrollView;

private TextInputLayout textInputLayoutEmail;
private TextInputLayout textInputLayoutPassword;

private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;

private AppCompatButton appCompatButtonLogin;

private AppCompatTextView textViewLinkRegister;

private InputValidation inputValidation;
private DatabaseHelper databaseHelper;

public String email;

//Session Manager Class
SessionManagement session;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    getSupportActionBar().hide();

    initViews();
    initListeners();
    initObjects();
}

/**
 * This method is to initialize views
 */
private void initViews() {

    nestedScrollView = (NestedScrollView) findViewById(R.id.nestedScrollView);

    textInputLayoutEmail = (TextInputLayout) 
findViewById(R.id.textInputLayoutEmail);
    textInputLayoutPassword = (TextInputLayout) 
findViewById(R.id.textInputLayoutPassword);

    textInputEditTextEmail = (TextInputEditText) 
findViewById(R.id.textInputEditTextEmail);
    textInputEditTextPassword = (TextInputEditText) 
findViewById(R.id.textInputEditTextPassword);

    appCompatButtonLogin = (AppCompatButton) 
findViewById(R.id.appCompatButtonLogin);

    textViewLinkRegister = (AppCompatTextView) 
findViewById(R.id.textViewLinkRegister);

   ;

}

/**
 * This method is to initialize listeners
 */
private void initListeners() {
    appCompatButtonLogin.setOnClickListener(this);
    textViewLinkRegister.setOnClickListener(this);
}

/**
 * This method is to initialize objects to be used
 */
private void initObjects() {
    databaseHelper = new DatabaseHelper(activity);
    inputValidation = new InputValidation(activity);

}

/**
 * This implemented method is to listen the click on view
 *
 * @param v
 */
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.appCompatButtonLogin:
            verifyFromSQLite();

            break;
        case R.id.textViewLinkRegister:
            // Navigate to RegisterActivity
            Intent intentRegister = new Intent(getApplicationContext(), 
RegisterActivity.class);
            startActivity(intentRegister);
            break;
    }
}

/**
 * This method is to validate the input text fields and verify login 
credentials from SQLite
 */
private void verifyFromSQLite() {
    if (!inputValidation.isInputEditTextFilled(textInputEditTextEmail, 
textInputLayoutEmail, getString(R.string.error_message_email))) {
        return;
    }
    if (!inputValidation.isInputEditTextEmail(textInputEditTextEmail, 
textInputLayoutEmail, getString(R.string.error_message_email))) {
        return;
    }
    if (!inputValidation.isInputEditTextFilled(textInputEditTextPassword, 
textInputLayoutPassword, getString(R.string.error_message_email))) {
        return;
    }

    if 
(databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim()
            , textInputEditTextPassword.getText().toString().trim())) {

        email = textInputEditTextEmail.getText().toString().trim();
        Intent accountsIntent = new Intent(activity, MainMenuActivity.class);
        accountsIntent.putExtra("EMAIL", 
textInputEditTextEmail.getText().toString().trim());
        session.createLoginSession(email);
        emptyInputEditText();
        startActivity(accountsIntent);



    } else {
        // Snack Bar to show success message that record is wrong
        Snackbar.make(nestedScrollView, 
getString(R.string.error_valid_email_password), Snackbar.LENGTH_LONG).show();
    }
}

/**
 * This method is to empty all input edit text
 */
private void emptyInputEditText() {
    textInputEditTextEmail.setText(null);
    textInputEditTextPassword.setText(null);
}

}

The error is on the line "session.createLoginSession("EMAIL");" as this is being passed in as a null value.

  • please post the whole Activity in which you perform the Login. As AlexTa has already mentioned in his answer your session object is null when you try to create the session. – BrickTop Apr 07 '17 at 18:20
  • I have updated the class now. Thanks – user3629216 Apr 07 '17 at 18:33
  • The problem is that you don't instantiate your SessionManagement object anywhere in your Activity. Implement this statement in your initObjects method `session = SessionManagement(this);`. – BrickTop Apr 07 '17 at 18:58
  • Please also see about [mcve] and always give the logcat in your Android questions – OneCricketeer Apr 09 '17 at 19:16

1 Answers1

0

the problem is that you don't instantiate your SessionManagement object anywhere in your Activity. Implement this statement in your initObjects method session = SessionManagement(this);