mejkan mejkan - 5 months ago 48
Java Question

How To Store userid in session and retrieve it another class in android?

i want to save userid in session in login.java class and retrieve in another welcome.java class and toast it, while it gives error when i am trying to retrieve userid in welcome.java class and application get crashed, and if i remov retrieving code of userid from welcome.java class then working fine without retrievng userid. so please anyone help me what i am missing here?

here is sessionmanager.java code

public class SessionManager{

// 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";

// User name (make variable public to access from outside)
public static final String KEY_userid = "userid";
//public static final String KEY_NAME = "name";

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

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

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

// Storing name in pref
editor.putString(KEY_userid, userid);
//editor.putString(KEY_NAME, name);

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

// commit changes
editor.commit();
}

/**
* Check login method will 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, Login.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 name
user.put(KEY_userid, pref.getString(KEY_userid, null));

//user.put(KEY_NAME, pref.getString(KEY_NAME, null));

// 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();

//Toast.makeText(SessionManager.this, "function call...: " , Toast.LENGTH_LONG).show();

// After logout redirect user to Loing Activity
Intent i = new Intent(_context, Login.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);

//Intent intent = new Intent(getApplicationContext(), Second_activity.class);
//startActivity(intent);

}

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



}


and here is login.java code

In this class i removed extra code just write relevant code where userid save in session after login success,
public class Login extends Activity {

private EditText editTextUserName;
private EditText editTextPassword;
SessionManager session;
String userid,;

String username;
String password,regid;


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


session = new SessionManager(getApplicationContext());

editTextUserName = (EditText) findViewById(R.id.nameID);
editTextPassword = (EditText) findViewById(R.id.et_pass_ID);


}

respObject.getJSONObject("response");
userid = responses.getString("memberID");


String active = respObject.getString("status");
if(active.equalsIgnoreCase("200")){


session.createLoginSession(userid, "anroidhive@gmail.com");


Intent intent=new Intent(Login.this,Welcome.class);

startActivity(intent);
finish();

}

}


And here is Welcome.java code

Here i want to retrieve userid in this class that i saved before in login class, here i am writing only relevant code .
public class Welcome extends Activity {

SessionManager session;


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

HashMap<String, String> user = session.getUserDetails();
String userid = user.get(SessionManager.KEY_userid);


Toast.makeText(this, userid+"", Toast.LENGTH_LONG).show();
}
}


here it gives error while retrieving userid and application get crashed, if i removed retrieved code then application work fine. s i think error exist here when i try to receive, please any one help me, what i should do? what i am missing here?

Here is logcat error

06-25 21:28:27.050: W/IInputConnectionWrapper(20740): getSelectedText on inactive InputConnection
06-25 21:28:27.050: W/IInputConnectionWrapper(20740): setComposingText on inactive InputConnection
06-25 21:28:31.530: I/(20740): ION_IOC_IMPORT success d6de8cc0,phy addr = 8ee69000
06-25 21:29:01.800: W/IInputConnectionWrapper(20740): getSelectedText on inactive InputConnection
06-25 21:29:01.810: W/IInputConnectionWrapper(20740): setComposingText on inactive InputConnection
06-25 21:29:02.900: I/(20740): ION_IOC_IMPORT success c66fb140,phy addr = 8f157000


06-25 21:29:26.930: D/AbsListView(20740): Get MotionRecognitionManager
06-25 21:29:26.960: D/AndroidRuntime(20740): Shutting down VM
06-25 21:29:26.960: W/dalvikvm(20740): threadid=1: thread exiting with uncaught exception (group=0x416e82e8)
06-25 21:29:26.980: E/AndroidRuntime(20740): FATAL EXCEPTION: main
06-25 21:29:26.980: E/AndroidRuntime(20740): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.newapp/com.example.newapp.Welcome}: java.lang.NullPointerException
06-25 21:29:26.980: E/AndroidRuntime(20740): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2118)
06-25 21:29:26.980: E/AndroidRuntime(20740): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2143)
06-25 21:29:26.980: E/AndroidRuntime(20740): at android.app.ActivityThread.access$700(ActivityThread.java:140)
06-25 21:29:26.980: E/AndroidRuntime(20740): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
06-25 21:29:26.980: E/AndroidRuntime(20740): at android.os.Handler.dispatchMessage(Handler.java:99)
06-25 21:29:26.980: E/AndroidRuntime(20740): at android.os.Looper.loop(Looper.java:174)
06-25 21:29:26.980: E/AndroidRuntime(20740): at android.app.ActivityThread.main(ActivityThread.java:4952)
06-25 21:29:26.980: E/AndroidRuntime(20740): at java.lang.reflect.Method.invokeNative(Native Method)
06-25 21:29:26.980: E/AndroidRuntime(20740): at java.lang.reflect.Method.invoke(Method.java:511)
06-25 21:29:26.980: E/AndroidRuntime(20740): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
06-25 21:29:26.980: E/AndroidRuntime(20740): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
06-25 21:29:26.980: E/AndroidRuntime(20740): at dalvik.system.NativeStart.main(Native Method)
06-25 21:29:26.980: E/AndroidRuntime(20740): Caused by: java.lang.NullPointerException
06-25 21:29:26.980: E/AndroidRuntime(20740): at com.example.newapp.Welcome.onCreate(Welcome.java:72)
06-25 21:29:26.980: E/AndroidRuntime(20740): at android.app.Activity.performCreate(Activity.java:5188)
06-25 21:29:26.980: E/AndroidRuntime(20740): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
06-25 21:29:26.980: E/AndroidRuntime(20740): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2082)
06-25 21:29:26.980: E/AndroidRuntime(20740): ... 11 more

Answer

session is not initiated, please check following code,

public class Welcome extends Activity {

 SessionManager session;


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

    session = new SessionManager(getApplicationContext());//<-- this is what you missed
    HashMap<String, String> user = session.getUserDetails();
    String userid = user.get(SessionManager.KEY_userid);


    Toast.makeText(this, userid+"", Toast.LENGTH_LONG).show();
  }
}

Suggest using single instance for SessionManager.