2015-07-13 42 views
-1

當我跑我的應用程序,它顯示的logcat: -NullPointException虛方法

07-13 17:31:10.418: E/AndroidRuntime(20063): Process: com.quickblox.q_municate, PID: 20063 
07-13 17:31:10.418: E/AndroidRuntime(20063): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.quickblox.q_municate/ui.splash.SplashActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference 
07-13 17:31:10.418: E/AndroidRuntime(20063): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2240) 
07-13 17:31:10.418: E/AndroidRuntime(20063): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389) 
07-13 17:31:10.418: E/AndroidRuntime(20063): at android.app.ActivityThread.access$900(ActivityThread.java:147) 
07-13 17:31:10.418: E/AndroidRuntime(20063): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296) 
07-13 17:31:10.418: E/AndroidRuntime(20063): at android.os.Handler.dispatchMessage(Handler.java:102) 
07-13 17:31:10.418: E/AndroidRuntime(20063): at android.os.Looper.loop(Looper.java:135) 
07-13 17:31:10.418: E/AndroidRuntime(20063): at android.app.ActivityThread.main(ActivityThread.java:5254) 
07-13 17:31:10.418: E/AndroidRuntime(20063): at java.lang.reflect.Method.invoke(Native Method) 
07-13 17:31:10.418: E/AndroidRuntime(20063): at java.lang.reflect.Method.invoke(Method.java:372) 
07-13 17:31:10.418: E/AndroidRuntime(20063): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898) 
07-13 17:31:10.418: E/AndroidRuntime(20063): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693) 
07-13 17:31:10.418: E/AndroidRuntime(20063): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference 
07-13 17:31:10.418: E/AndroidRuntime(20063): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:137) 
07-13 17:31:10.418: E/AndroidRuntime(20063): at com.quickblox.q_municate_core.utils.PrefsHelper.<init>(PrefsHelper.java:48) 
07-13 17:31:10.418: E/AndroidRuntime(20063): at ui.splash.SplashActivity.<init>(SplashActivity.java:38) 
07-13 17:31:10.418: E/AndroidRuntime(20063): at java.lang.reflect.Constructor.newInstance(Native Method) 
07-13 17:31:10.418: E/AndroidRuntime(20063): at java.lang.Class.newInstance(Class.java:1572) 
07-13 17:31:10.418: E/AndroidRuntime(20063): at android.app.Instrumentation.newActivity(Instrumentation.java:1065) 
07-13 17:31:10.418: E/AndroidRuntime(20063): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2230) 

而且我的代碼: -

SplashActivity: -

public class SplashActivity extends BaseActivity { 

private static final String TAG = SplashActivity.class.getSimpleName(); 
private FacebookHelper facebookHelper; 
public String userEmail; 
public String userPassword; 
public PrefsHelper prefshelper= new PrefsHelper(this); 
public static void start(Context context) { 
    Intent intent = new Intent(context, SplashActivity.class); 
    context.startActivity(intent); 
} 

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

    addActions(); 

    facebookHelper = new FacebookHelper(this, savedInstanceState, new FacebookSessionStatusCallback()); 

    userEmail = prefshelper.getPref(PrefsHelper.PREF_USER_EMAIL); 
    userPassword = prefshelper.getPref(PrefsHelper.PREF_USER_PASSWORD); 

    boolean isRememberMe = prefshelper.getPref(PrefsHelper.PREF_REMEMBER_ME, false); 

    if (isRememberMe) { 
     checkStartExistSession(userEmail, userPassword); 
    } else { 
     startLanding(); 
    } 

    setContentView(R.layout.activity_splash); 
} 

@Override 
public void onStart() { 
    super.onStart(); 
    facebookHelper.onActivityStart(); 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
    if (isLoggedInToChat()) { 
     startMainActivity(); 
     finish(); 
    } 
} 

@Override 
public void onStop() { 
    super.onStop(); 
    facebookHelper.onActivityStop(); 
} 

@Override 
protected void onFailAction(String action) { 
    super.onFailAction(action); 
    startLanding(); 
} 

private boolean isLoggedInToChat() { 
    return QBChatService.isInitialized() && QBChatService.getInstance().isLoggedIn(); 
} 

private void checkStartExistSession(String userEmail, String userPassword) { 
    boolean isEmailEntered = !TextUtils.isEmpty(userEmail); 
    boolean isPasswordEntered = !TextUtils.isEmpty(userPassword); 
    if ((isEmailEntered && isPasswordEntered) || (isLoggedViaFB(isPasswordEntered))) { 
     runExistSession(userEmail, userPassword); 
    } else { 
     startLanding(); 
    } 
} 

private boolean isLoggedViaFB(boolean isPasswordEntered) { 
    return isPasswordEntered && LoginType.FACEBOOK.equals(getCurrentLoginType()); 
} 

private void addActions() { 
    addAction(QBServiceConsts.LOGIN_SUCCESS_ACTION, new LoginSuccessAction()); 
    addAction(QBServiceConsts.LOGIN_AND_JOIN_CHATS_FAIL_ACTION, failAction); 
    addAction(QBServiceConsts.LOGIN_FAIL_ACTION, failAction); 
} 

public boolean isLoggedViaFB() { 
    return facebookHelper.isSessionOpened() && LoginType.FACEBOOK.equals(getCurrentLoginType()); 
} 

@Override 
protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    facebookHelper.onSaveInstanceState(outState); 
} 

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    facebookHelper.onActivityResult(requestCode, resultCode, data); 
} 

private void startLanding() { 
    LandingActivity.start(SplashActivity.this); 
    finish(); 
} 

private void runExistSession(String userEmail, String userPassword) { 
    //check is token valid for about 1 minute 
    if (AppSession.isSessionExistOrNotExpired(TimeUnit.MINUTES.toMillis(
      ConstsCore.TOKEN_VALID_TIME_IN_MINUTES))) { 
     startMainActivity(); 
     finish(); 
    } else { 
     doAutoLogin(userEmail, userPassword); 
    } 
} 

private void doAutoLogin(String userEmail, String userPassword) { 
    if (LoginType.EMAIL.equals(getCurrentLoginType())) { 
     login(userEmail, userPassword); 
    } else { 
     FacebookHelper.logout(); 
     facebookHelper.loginWithFacebook(); 
    } 
} 

private void login(String userEmail, String userPassword) { 
    QBUser user = new QBUser(null, userPassword, userEmail); 
    QBLoginCommand.start(this, user); 
} 

private LoginType getCurrentLoginType() { 
    return AppSession.getSession().getLoginType(); 
} 

private void startMainActivity() { 
    prefshelper.savePref(PrefsHelper.PREF_IMPORT_INITIALIZED, true); 
    MainActivity.start(SplashActivity.this); 
} 

private class FacebookSessionStatusCallback implements Session.StatusCallback { 

    @Override 
    public void call(Session session, SessionState state, Exception exception) { 
     if (session.isOpened() && LoginType.FACEBOOK.equals(getCurrentLoginType())) { 
      QBLoginRestWithSocialCommand.start(SplashActivity.this, QBProvider.FACEBOOK, 
        session.getAccessToken(), null); 
     } 
    } 
} 

private class LoginSuccessAction implements Command { 

    @Override 
    public void execute(Bundle bundle) { 
     QBUser user = (QBUser) bundle.getSerializable(QBServiceConsts.EXTRA_USER); 

     startMainActivity(); 

     AnalyticsUtils.pushAnalyticsData(SplashActivity.this, user, "User Sign In"); 

     finish(); 
    } 
} 

PrefsHelper: -

public class PrefsHelper { 

    public static final String PREF_REMEMBER_ME = "remember_me"; 
    public static final String PREF_LOGIN_TYPE = "login_type"; 
    public static final String PREF_DIALOG_ID = "dialog_id"; 
    public static final String PREF_USER_EMAIL = "email"; 
    public static final String PREF_USER_ID = "user_id"; 
    public static final String PREF_IS_LOGINED = "is_logined"; 
    public static final String PREF_USER_PASSWORD = "password"; 
    public static final String PREF_PUSH_NOTIFICATIONS = "push_notifications"; 
    public static final String PREF_IMPORT_INITIALIZED = "import_initialized"; 
    public static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"; 
    public static final String PREF_SIGN_UP_INITIALIZED = "sign_up_initialized"; 
    public static final String PREF_MISSED_MESSAGE = "missed_message"; 
    public static final String PREF_STATUS = "status"; 
    public static final String PREF_PUSH_MESSAGE = "message"; 
    public static final String PREF_REG_USER_ID = "registered_push_user"; 
    public static final String PREF_USER_AGREEMENT = "user_agreement"; 
    public static final String PREF_JOINED_TO_ALL_DIALOGS = "joined_to_all_dialogs"; 

    public static final String PREF_PUSH_MESSAGE_NEED_TO_OPEN_DIALOG = "push_need_to_open_dialog"; 
    public static final String PREF_PUSH_MESSAGE_DIALOG_ID = "push_dialog_id"; 
    public static final String PREF_PUSH_MESSAGE_USER_ID = "push_user_id"; 

    public static final String PREF_REG_ID = "registration_id"; 
    public static final String PREF_APP_VERSION = "appVersion"; 
    public static final String PREF_RECEIVE_PUSH = "receive_push"; 
    public static final String PREF_IS_SUBSCRIBED_ON_SERVER = "subscribed_on_server"; 
    public static final String PREF_USER_FULL_NAME = "full_name"; 
    public static final String PREF_SESSION_TOKEN = "session_token"; 

    private final SharedPreferences sharedPreferences; 
    private final SharedPreferences.Editor editor; 

    private static PrefsHelper instance; 

    public static PrefsHelper getPrefsHelper() { 
     return instance; 
    } 

    public PrefsHelper(Context context) { 
     instance = this; 
     String prefsFile = context.getPackageName(); 
     sharedPreferences = context.getSharedPreferences(prefsFile, Context.MODE_PRIVATE); 
     editor = sharedPreferences.edit(); 
    } 

    public void delete(String key) { 
     if (sharedPreferences.contains(key)) { 
      editor.remove(key).commit(); 
     } 
    } 

    public void savePref(String key, Object value) { 
     delete(key); 

     if (value instanceof Boolean) { 
      editor.putBoolean(key, (Boolean) value); 
     } else if (value instanceof Integer) { 
      editor.putInt(key, (Integer) value); 
     } else if (value instanceof Float) { 
      editor.putFloat(key, (Float) value); 
     } else if (value instanceof Long) { 
      editor.putLong(key, (Long) value); 
     } else if (value instanceof String) { 
      editor.putString(key, (String) value); 
     } else if (value instanceof Enum) { 
      editor.putString(key, value.toString()); 
     } else if (value != null) { 
      throw new RuntimeException("Attempting to save non-primitive preference"); 
     } 

     editor.commit(); 
    } 

    @SuppressWarnings("unchecked") 
    public <T> T getPref(String key) { 
     return (T) sharedPreferences.getAll().get(key); 
    } 

    @SuppressWarnings("unchecked") 
    public <T> T getPref(String key, T defValue) { 
     T returnValue = (T) sharedPreferences.getAll().get(key); 
     return returnValue == null ? defValue : returnValue; 
    } 

    public boolean isPrefExists(String key) { 
     return sharedPreferences.contains(key); 
    } 
} 
+0

刪除您的空 – Gattsu

回答

1

你剛纔宣佈public PrefsHelper prefshelper;而你沒有實例prefshelper這就是爲什麼你得到NullPointerException當您訪問

 userEmail = prefshelper.getPref(PrefsHelper.PREF_USER_EMAIL); 

實例化prefshelper,應該解決您的問題。

 prefshelper = new Prefshelper(this.getApplicationContext()); 

UPDATE

我認爲這個問題是您onCreate()之前你實例化prefshelper。你可以有定義它,但不初始化它

PrefsHelper prefshelper; 

裏面你onCreate(),後

super.onCreate(savedInstanceState); 

做到這一點

prefshelper = new PrefsHelper(this.getApplicationContext()); 
+0

仍然有錯誤..嘗試調用虛方法'java.lang,String.android.content.Context.getPackageName()'On Null Object Refrence –

+0

@MayankKhursija你改變了什麼,錯誤是什麼?你能用這些細節更新問題嗎? – Karthik

+0

正如你所說我實例化 –

1

你沒有實例化PrefsHelper任何地方。你簡單地調用:

userEmail = prefshelper.getPref(PrefsHelper.PREF_USER_EMAIL); 
userPassword = prefshelper.getPref(PrefsHelper.PREF_USER_PASSWORD); 

onCreate,但你從來沒有在任何地方prefshelper = new PrefsHelper(this),所以你得到一個NullPointerException

(我假設,因爲PrefHelper的構造得到上下文作爲參數,你應該通過它this,但我不能肯定不會對你的意圖有了更深的瞭解。)