我正在用安卓开发应用程序。因为我使用 SharedPreferences 进行会话管理的登录和注销活动。我的应用程序注销,将数据存储在 sharedpreferences 以保持会话成功完成。当我从应用程序(第二个活动)注销并呈现到第一个活动(登录活动)但是当我在成功注销后单击模拟器上的后退按钮仍然再次呈现到第二个活动并且遇到某些版本(如 2.3.3 等)时会发生什么例外
java.lang.RuntimeException: Unable to destroy activity {com.oj.bs/com.oj.bs.LoginActivity}: java.lang.NullPointerException
任何人都可以解决这个问题。请参考以下代码
以下是登录活动代码
sessionmngr = new SessionManager(getApplicationContext());
JSONObject json_user = jsonObj.getJSONObject("user");
sessionmngr.createLoginSession(id,json_user.getString(KEY_UNAME),
json_user.getString(KEY_UEMAIL));
.
.
以下是会话管理
public class SessionManager {
SharedPreferences pref;
Editor editor;
Context contxt;
//shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "bookingScapePref";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
public static final String KEY_NAME = "name";
public static final String KEY_ID = "id";
public static final String KEY_EMAIL = "email";
public SessionManager(Context context) {
super();
this.contxt = context;
pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
editor.commit();
}
/**
* Create login session
* */
public void createLoginSession(int id,String name, String email) {
editor.putBoolean(IS_LOGIN,true);
editor.putString(KEY_NAME, name);
editor.putString(KEY_EMAIL, email);
editor.putInt(KEY_ID, id);
editor.commit();
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails() {
HashMap<String, String> userDetails = new HashMap<String, String>();
userDetails.put(KEY_NAME, pref.getString(KEY_NAME, null));
userDetails.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
return userDetails;
}
/**
* Check login method will check user login status
* */
public void checkLogin() {
if (!this.isLoggedIn()) {
Intent i = new Intent(contxt, LoginActivity.class);
//closing all the activity
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
contxt.startActivity(i);
}
}
public void logoutUser() {
//clearing all data from sharedPreferences
editor.clear();
editor.commit();
Intent intnt = new Intent(contxt, LoginActivity.class);
// Closing all the Activities
intnt.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
intnt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
contxt.startActivity(intnt);
}
/**
* Quick check for login
* **/
// Get Login State
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN, false);
}
}
这是我正在检查会话的第二个活动
public class ProjectFragActivity extends SherlockFragmentActivity {
SessionManager sessionMngr ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionMngr = new SessionManager(getApplicationContext());
Toast.makeText(getApplicationContext(), "User Login Status: " + sessionMngr .isLoggedIn(),
Toast.LENGTH_LONG).show();
sessionMngr.checkLogin();
.
.