尝试在空对象引用上调用虚方法'void com.example.app.createLoginSession(java.lang.String)'

时间:2017-04-07 16:41:48

标签: java android nullpointerexception sharedpreferences

我正在尝试将用户名(EMAIL)传递到SharedPreferencesManagement类中的createLoginSession。当我尝试在登录时执行此操作时,我收到一条错误,指出“null对象引用上的”createLoginSession(java.lang.String)“。

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

活动登录的代码如下:

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

}

错误在“session.createLoginSession(”EMAIL“);”因为这是作为空值传递的。

1 个答案:

答案 0 :(得分:0)

问题是您没有在Activity中的任何位置实例化SessionManagement对象。在initObjects方法session = SessionManagement(this);

中实现此语句