尝试结束会话时应用崩溃。null对象引用

时间:2019-01-04 21:06:45

标签: java object session reference null

我正在尝试为我正在开发的应用程序实现注销按钮。当我从导航菜单中单击注销时session.logoutUser();被调用,并在我的IDE中导致以下错误;

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ravi.myapplication, PID: 32694
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.ravi.myapplication.SessionHandler.logoutUser()' on a null object reference
    at com.example.ravi.myapplication.BaseActivity$1.onNavigationItemSelected(BaseActivity.java:57)
    at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:154)
    at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
    at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
    at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
    at android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:342)
    at android.view.View.performClick(View.java:6597)
    at android.view.View.performClickInternal(View.java:6574)
    at android.view.View.access$3100(View.java:778)
    at android.view.View$PerformClick.run(View.java:25885)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

我在基本活动类的开头调用会话类时收到从未分配的私有字段的警告。如果有人能弄清楚为什么会发生这种情况,它将被彻底应用!这些类的代码如下:

BaseActivity.java

package com.example.ravi.myapplication;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Spinner;

public class BaseActivity extends AppCompatActivity {
private SessionHandler session;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
Toolbar toolbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_base);
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawerLayout.setDrawerListener(actionBarDrawerToggle);



    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {
            final String appPackageName = getPackageName();

            switch (item.getItemId()) {

                case R.id.nav_dashboard:
                    Intent dash = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(dash);
//                        finish();
                    drawerLayout.closeDrawers();
                    break;


                case R.id.nav_about_us:
                    Intent anIntent = new Intent(getApplicationContext(), AboutUS.class);
                    startActivity(anIntent);
//                        finish();
                    drawerLayout.closeDrawers();
                    break;

                case R.id.nav_logout:
                    session.logoutUser();
                    Intent i = new Intent(getApplicationContext(), LoginActivity.class);
                    startActivity(i);
                    break;


            }
            return false;
        }
    });

}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);

    actionBarDrawerToggle.syncState();
}

@Override
public void finish() {
    super.finish();
    overridePendingTransitionExit();
}

@Override
public void startActivity(Intent intent) {
    super.startActivity(intent);
    overridePendingTransitionEnter();
}

/**
 * Overrides the pending Activity transition by performing the "Enter" animation.
 */
protected void overridePendingTransitionEnter() {
    overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left);
}

/**
 * Overrides the pending Activity transition by performing the "Exit" animation.
 */
protected void overridePendingTransitionExit() {
    overridePendingTransition(R.anim.slide_from_left, R.anim.slide_to_right);
}
}

SessionHandler.java

package com.example.ravi.myapplication;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.Date;

public class SessionHandler {
private static final String PREF_NAME = "UserSession";
private static final String KEY_USERNAME = "username";
private static final String KEY_EXPIRES = "expires";
private static final String KEY_FULL_NAME = "full_name";
private static final String KEY_EMPTY = "";
private Context mContext;
private SharedPreferences.Editor mEditor;
private SharedPreferences mPreferences;

public SessionHandler(Context mContext) {
    this.mContext = mContext;
    mPreferences = mContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    this.mEditor = mPreferences.edit();
}

/**
 * Logs in the user by saving user details and setting session
 */
public void loginUser(String username, String fullName) {
    mEditor.putString(KEY_USERNAME, username);
    mEditor.putString(KEY_FULL_NAME, fullName);
    Date date = new Date();

    //Set user session for next 7 days
    long millis = date.getTime() + (7 * 24 * 60 * 60 * 1000);
    mEditor.putLong(KEY_EXPIRES, millis);
    mEditor.commit();
}

/**
 * Checks whether user is logged in
 */
public boolean isLoggedIn() {
    Date currentDate = new Date();

    long millis = mPreferences.getLong(KEY_EXPIRES, 0);

    /* If shared preferences does not have a value
     then user is not logged in
     */
    if (millis == 0) {
        return false;
    }
    Date expiryDate = new Date(millis);

    /* Check if session is expired by comparing
    current date and Session expiry date
    */
    return currentDate.before(expiryDate);
}

/**
 * Fetches and returns user details
 */
public User getUserDetails() {
    //Check if user is logged in first
    if (!isLoggedIn()) {
        return null;
    }
    User user = new User();
    user.setUsername(mPreferences.getString(KEY_USERNAME, KEY_EMPTY));
    user.setFullName(mPreferences.getString(KEY_FULL_NAME, KEY_EMPTY));
    user.setSessionExpiryDate(new Date(mPreferences.getLong(KEY_EXPIRES, 0)));

    return user;
}

/**
 * Logs out user by clearing the session
 */
public void logoutUser(){
    mEditor.clear();
    mEditor.commit();
}

}

1 个答案:

答案 0 :(得分:1)

向类session中的BaseActivity字段,未分配任何值,因此它为空