HashMap save and get shared preference - android

I have a project and i want to save every variables that are available to the user online to the shared preference. It is their string values user_id, Fname, Lname, and their int values "lexile", "user_id".I have been following a tutorial online so far so good but it only provides saving two variables so I improvise. I didnt get any error when running but when actually using the application I cant seem to login and open the second activity maybe because of my hashmaping.
Here is the code below
this is the part of the login that is related
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//SUBUKAN NA ISINGIT DINE ANG PAGCHECK SA INTERNET SERCVICE
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
//OPENS THE NEW ACTIVITY
if (success) {
String Fname = jsonResponse.getString("Fname");
String Lname = jsonResponse.getString("Lname");
int lexile = jsonResponse.getInt("lexile");
int user_id = jsonResponse.getInt("user_id");
// String username = jsonResponse.getString("username");
// int user_id = jsonResponse.getInt("user_id");
Intent intent = new Intent(Login.this, User_nav.class);
intent.putExtra("Lname", Lname);
intent.putExtra("Fname", Fname);
intent.putExtra("lexile", lexile);
intent.putExtra("user_id", user_id);
// intent.putExtra("username",username);
//intent.putExtra("user_id", user_id);
//THIS IS THE PART OF THE SESSION MANAGER
session.createLoginSession(Lname, Fname, lexile, user_id);
Login.this.startActivity(intent);
progress.dismiss();
}
This is the second activity, the codes that are related
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
session = new SessionManager(getApplicationContext());
Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(),Toast.LENGTH_LONG).show();
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
String Lname = user.get(SessionManager.KEY_FNAME);
String Fname = user.get(SessionManager.KEY_LNAME);
HashMap<String, Integer> user_int = session.getUserLexileNID();
Integer lexile = user_int.get(SessionManager.KEY_LEXILE);
Integer user_id = user_int.get(SessionManager.KEY_USER_ID);
TextView Name = (TextView) header.findViewById(R.id.Name);
TextView displayLexile = (TextView) header.findViewById(R.id.lexile);
Name.setText(Html.fromHtml(Lname+", " +Fname));
displayLexile.setText("Lexile Level: "+lexile + "" +user_id);
This is the SessionManager that holds all of those codes for session making.
package com.capstone.jmilibraryapp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.content.SharedPreferencesCompat;
import java.util.HashMap;
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "JMIPref";
private static final String IS_LOGIN = "IsLoggedIn";
public static final String KEY_FNAME = "Fname";
public static final String KEY_LNAME = "Lname";
public static final String KEY_USER_ID = "user_id";//PART OF THE PROBLEM
public static final String KEY_LEXILE = "lexile";///PART OF THE PROBLEM
//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 Fname, String Lname, Integer user_id, Integer lexile){
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_FNAME, Fname);
editor.putString(KEY_LNAME, Lname);
editor.putInt(KEY_USER_ID, user_id);
editor.putInt(KEY_LEXILE, lexile);
editor.commit();
}
//Part of the tutorial dont seem to have any problem
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_FNAME, pref.getString(KEY_FNAME, null));
user.put(KEY_LNAME, pref.getString(KEY_LNAME, null));
return user;
}
//THIS MAYBE THE SOURCE OF THE PROBLEM
public HashMap<String, Integer> getUserLexileNID(){
HashMap<String, Integer> user_int = new HashMap<>();
user_int.put(KEY_LEXILE, pref.getInt(KEY_LEXILE,-1 ));
user_int.put(KEY_USER_ID, pref.getInt(KEY_USER_ID,-1 ));
return user_int;
}
public void checkLogin(){
if (!this.isLoggedIn()) {
Intent i = new Intent(_context, Login.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}}
public void logoutUser(){
editor.clear();
editor.commit();
Intent i = new Intent(_context, Login.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN, false);
}
}

Related

Error on SharedPreferences

I implemented code for Session Management day before yesterday It's working properly but now It's giving an error on getString() please check this below code and tell me where I am wrong.
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "MaangalPref";
private static final String IS_LOGIN = "IsLoggedIn";
public static final String KEY_PASSWORD = "name";
public static final String KEY_EMAIL = "email";
public static final String KEY_GENDER = "gender";
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public SessionManager() {}
Create login session
public void createLoginSession(String name, String email, String gender){
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_PASSWORD, name);
editor.putString(KEY_EMAIL, email);
editor.putString(KEY_GENDER, gender);
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(){
if(!this.isLoggedIn()){
Intent i = new Intent(_context, AuthenticActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
}
Get stored session data
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
user.put(KEY_GENDER,pref.getString(KEY_GENDER, null));
return user;
}
public void logoutUser(){
editor.clear();
editor.commit();
Intent i = new Intent(_context, AuthenticActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN, false);
}
}
onCreate method of Fragment Class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Session class instance
session = new SessionManager();
// get user data from session
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
Log.e("email________NewMatches",email);
DATA_URL = "http://192.168.2.110/xp/new_matches.php?matri_id="+email;
Log.e("URL________NewMatches",DATA_URL);
}
I think your are calling empty constructor of SessionManager in tab fragment like
session = new SessionManager();
that you are declared in your SessionManager class
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public SessionManager() {}
so finally use in tab fragment
session = new SessionManager(getContext()); //give context of class
instead of session = new SessionManager();
use below code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Session class instance
session = new SessionManager(getContext()); //here you have to change
// get user data from session
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
Log.e("email________NewMatches",email);
DATA_URL = "http://192.168.2.110/xp/new_matches.php?matri_id="+email;
Log.e("URL________NewMatches",DATA_URL);
}
and also remove empty constructor from SessionManager for future purpose....

Open the Dashboard while remaining on the Same Session

I am able to login to the System, and Logout from the System.When i presses back from the Dashboard without making Logout from the System.I have login to the System eachtime.How can i restrict to loginPage without making the Logout from the System.I need to open the Dashbord page,if the user havenot logout from the System and direct to the Login if the accesstoken time expires
Login
public class Login extends AppCompatActivity implements View.OnClickListener {
EditText userName, Password;
Button login;
public static final String LOGIN_URL = "http://192.168.100.5:84/Token";
public static final String KEY_USERNAME = "UserName";
public static final String KEY_PASSWORD = "Password";
String username, password;
String accesstoken, tokentype, expiresin, masterid, name, access, issue, expires, masterid1;
SessionManagement sessionManagement;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userName = (EditText) findViewById(R.id.login_name);
Password = (EditText) findViewById(R.id.login_password);
userName.setHint(Html.fromHtml("<font color='#008b8b' style='italic'>Username</font>"));
Password.setHint(Html.fromHtml("<font color='#008b8b'>Password</font>"));
login = (Button) findViewById(R.id.login);
login.setOnClickListener(this);
/* sessionManagement = (SessionManagement) getSharedPreferences("mySharedPref", 0);
if (sessionManagement.isLoggedIn()) {
startActivity(new Intent(getApplicationContext(), Home.class));
} */
}
private void UserLogin() {
username = userName.getText().toString().trim();
password = Password.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
accesstoken = jsonObject.getString("access_token");
tokentype = jsonObject.getString("token_type");
expiresin = jsonObject.getString("expires_in");
username = jsonObject.getString("userName");
masterid = jsonObject.getString("MasterID");
masterid = masterid.replaceAll("[^\\.0123456789]", "");
masterid1 = jsonObject.getString("MasterID");
name = jsonObject.getString("Name");
access = jsonObject.getString("Access");
issue = jsonObject.getString(".issued");
expires = jsonObject.getString(".expires");
SessionManagement session = new SessionManagement(Login.this);
session.createLoginSession(accesstoken, tokentype, expiresin, username, masterid, name, access, issue, expires);
// session.createLoginSession(masterid1);
openProfile();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(Login.this, "Please enter valid username and Password", Toast.LENGTH_SHORT).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//params.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
return params;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
map.put(KEY_USERNAME, username);
map.put(KEY_PASSWORD, password);
//map.put("access_token", accesstoken);
map.put("grant_type", "password");
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void openProfile() {
Intent intent = new Intent(this, Home.class);
intent.putExtra(KEY_USERNAME, username);
startActivity(intent);
startActivity(intent);
}
#Override
public void onClick(View v) {
UserLogin();
}
}
SessionManagementis used for storing access token and other required information
public class SessionManagement {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";
private static final String IS_LOGIN = "IsLoggedIn";
public static final String KEY_access_token = "access_token";
public static final String KEY_token_type = "token_type";
public static final String Key_EXPIRES_IN = "expires_in";
public static final String KEY_USERNAME = "userName";
public static final String KEY_MASTER_ID = "MasterID";
public static final String KEY_MASTER_ID1 = "MasterID";
public static final String KEY_Name = "Name";
public static final String KEY_Access = "Access";
public static final String KEY_Issued = ".issued";
public static final String KEY_expires = ".expires";
// Constructor
public SessionManagement(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
SettingFragment context;
public void createLoginSession(String accesstoken, String tokentype, String expiresin, String username, String masterId, String name, String access, String issued, String expires) {
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_access_token, accesstoken);
editor.putString(KEY_token_type, tokentype);
editor.putString(Key_EXPIRES_IN, expiresin);
editor.putString(KEY_USERNAME, username);
editor.putString(KEY_MASTER_ID, masterId);
editor.putString(KEY_MASTER_ID1, masterId);
editor.putString(KEY_Name, name);
editor.putString(KEY_Access, access);
editor.putString(KEY_Issued, issued);
editor.putString(KEY_expires, expires);
editor.apply();
String user_new_access_token = pref.getString(KEY_access_token, null);
String user_new_access_tokentype = pref.getString(KEY_token_type, null);
String user_name_expiresin = pref.getString(Key_EXPIRES_IN, null);
String user_name_Username = pref.getString(KEY_USERNAME, null);
String user_name_masterID = pref.getString(KEY_MASTER_ID, null);
String user_name_name = pref.getString(KEY_Name, null);
String user_name_access = pref.getString(KEY_Access, null);
String user_name_issued = pref.getString(KEY_Issued, null);
String user_name_expires = pref.getString(KEY_expires, null);
String user_name_masterID1 = pref.getString(KEY_MASTER_ID1, null);
Log.d("TAG", "Access Token :" + accesstoken + user_new_access_token);
Log.d("TAG", "TokenType:" + user_new_access_tokentype);
Log.d("TAG", "Expires in:" + user_name_expiresin);
Log.d("TAG", "UserName:" + user_name_Username);
Log.d("TAG", "MasterID:" + user_name_masterID);
Log.d("TAG", "Name:" + user_name_name);
Log.d("TAG", "Access:" + user_name_access);
Log.d("TAG", "Issued:" + user_name_issued);
Log.d("TAG", "Expires:" + user_name_expires);
Log.d("TAG", "user_name_masterID1:" + user_name_masterID1);
// String user_name_new = pref.getString(KEY_access_token, null);
// Log.d("TAG", " :" + accesstoken + " user_name_new:" + user_name_new);
// Log.d(tokentype, "admin");
//ad Log.d(expiresin, "expiresin");
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, 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_USERNAME, pref.getString(KEY_USERNAME, null));
user.put(KEY_access_token, pref.getString(KEY_access_token, null));
user.put(KEY_token_type, pref.getString(KEY_token_type, null));
// user.put(KEY_TOKEN_TYPE, pref.getString(KEY_TOKEN_TYPE, null));
// user.put(KEY_MASTER_ID, pref.getString(KEY_MASTER_ID, null));
// user.put(KEY_access_token, pref.getString(KEY_access_token, null));
// user.put(KEY_NAME, pref.getString(KEY_NAME, null));
//user.put(KEY_Access, pref.getString(KEY_Access, null));
// return user
return user;
}
/**
* Clear session details
*/
public void logoutUser() {
editor.clear();
editor.commit();
// 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);
}
public String getMasterId() {
String masterID = pref.getString(KEY_MASTER_ID, null);
return masterID;
}
public String getMasterId1() {
String masterID = pref.getString(KEY_MASTER_ID1, null);
return masterID;
}
public String getAccess() {
String accessID = pref.getString(KEY_Access, null);
return accessID;
}
public String getKeyName() {
String KeyName = pref.getString(KEY_Name, null);
return KeyName;
}
public String getAccesstToken() {
String user_new_access_token = pref.getString(KEY_access_token, null);
return user_new_access_token;
}
public void clear() {
Log.d("TAg", "Full Cleared");
editor.clear();
// editor.remove(KEY_MASTER_ID);
// editor.remove(KEY_USERNAME);
editor.commit();
}
/**
* Quick check for login
**/
// Get Login State
public boolean isLoggedIn() {
return pref.getBoolean(IS_LOGIN, false);
}
}
How can i direct to dashboard page if the user has not logout to the
system?
I have checked the session on the Login page .If isLoggedIn() == true then i have switched to the Dashboard page.
sessionmanagement
public boolean isLoggedIn() {
System.out.println("Pref" + pref.getBoolean(IS_LOGIN, false));
return pref.getBoolean(IS_LOGIN, false);
}
public boolean 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);
}
// return false;
return false;
}
Login
if (session.isLoggedIn() == true) {
Intent intent = new Intent(this, Home.class);
startActivity(intent);
}
one can do with checking the session expiry time also

Shared preferences Context error

I been trying to create a small login app that stores the logged in information to shared preferences.
i created a class called Mysession to store,get and clear shared preferences data,
the class takes a context and when i pass the context from my login activity to login class and then store the data to shared preferences i get an error.
the error indicates that i passed an empty context.
these are my classes and activities.
Login Activity
public class LoginActivity extends AppCompatActivity {
EditText lemailtxt,lpasstxt;
Button loginbttn;
String lurl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
lurl = "http://192.168.1.6/test/test.php";
lemailtxt = (EditText) findViewById(R.id.emailtxt);
lpasstxt = (EditText) findViewById(R.id.passtxt);
loginbttn = (Button) findViewById(R.id.loginbttn);
loginbttn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MLoginOnline login = new MLoginOnline(getApplicationContext()
,lurl,lemailtxt.getText().toString(),lpasstxt.getText().toString());
login.execute();
}
});
}
Login Class
public class MLoginOnline extends AsyncTask<Void,Void,String>{
Context mContext;
String Purl;
String Pemail,Ppass;
ProgressDialog progressDialog;
public MLoginOnline(Context mContext, String purl, String pemail, String ppass) {
this.mContext = mContext;
Purl = purl;
Pemail = pemail;
Ppass = ppass;
}
MySession session = new MySession(mContext);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(mContext);
progressDialog.setTitle("Login");
progressDialog.setMessage("Loging in please wait......");
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
String data = Loginto();
return data;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String id,name,sem;
if (s ==null){
Toast.makeText(mContext,"Error Login in",Toast.LENGTH_SHORT).show();
progressDialog.hide();
}else {
progressDialog.hide();
try {
JSONObject object = new JSONObject(s);
id = object.getString("id");
name = object.getString("name");
sem = object.getString("sem");
session.InPutUser(id,name,Pemail,sem);
Intent intent = new Intent(mContext, HomeActivity.class);
mContext.startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private String Loginto(){
InputStream inputStream=null;
String line = null;
try {
URL url = new URL(Purl+"?Email="+Pemail+"&Password="+Ppass);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
inputStream = new BufferedInputStream(con.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
if(bufferedReader != null){
while ((line=bufferedReader.readLine()) != null){
stringBuffer.append(line+"\n");
}
}else {
return null;
}
return stringBuffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
**Shared preferences class **
public class MySession {
Context mcontext;
SharedPreferences preferences;
SharedPreferences.Editor editor;
int PRIVATE_MODE = 0;
private static final String PREFER_NAME = "session";
private final String IS_USER_LOGED_IN = "IsUserLogedIn";
public final String KEY_ID = "id";
public final String KEY_EMAIL = "email";
public static final String KEY_NAME = "name";
public static final String KEY_SEM = "sem";
public MySession(Context mcontext) {
this.mcontext = mcontext;
this.preferences = mcontext.getSharedPreferences(PREFER_NAME,PRIVATE_MODE);
editor = preferences.edit();
}
public void InPutUser(String id,String name,String email,String sem){
editor.putBoolean(IS_USER_LOGED_IN,true);
editor.putString(KEY_ID,id);
editor.putString(KEY_NAME,name);
editor.putString(KEY_SEM,sem);
editor.putString(KEY_EMAIL,email);
editor.commit();
}
public void logoutUser(Context context,Class intent){
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Login Activity
Intent i = new Intent(context, intent);
// 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);
}
public HashMap<String, String> getNameAndSem(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, preferences.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, preferences.getString(KEY_SEM, null));
// return user
return user;
}
public HashMap<String, String> getIDandEMail() {
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, preferences.getString(KEY_ID, null));
// user email id
user.put(KEY_EMAIL, preferences.getString(KEY_EMAIL, null));
// return user
return user;
}
public boolean IsUserLoggedIn(){
return preferences.getBoolean(IS_USER_LOGED_IN, false);
}
}
Cat log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.zer0ll.demo.studentapp, PID: 20793
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
at com.zer0ll.demo.studentapp.MySession.<init>(MySession.java:36)
at com.zer0ll.demo.studentapp.MLoginOnline.<init>(MLoginOnline.java:43)
at com.zer0ll.demo.studentapp.MainView.LoginActivity$1.onClick(LoginActivity.java:32)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Application terminated.
In your MLoginOnline class
Here MySession session = new MySession(mContext); needs to be defined under a method cause mContext is not initialized yet.
MySession session; //declare globally
public MLoginOnline(Context mContext, String purl, String pemail, String ppass) {
this.mContext = mContext;
Purl = purl;
Pemail = pemail;
Ppass = ppass;
session = new MySession(mContext); //initialize here
}
Your session field is being initialized with null Context.
Instead of:
MySession session = new MySession(mContext);
Do:
MySession session;
public MLoginOnline(Context mContext, String purl, String pemail, String ppass) {
this.mContext = mContext;
Purl = purl;
Pemail = pemail;
Ppass = ppass;
session = new MySession(mContext);
}
public MLoginOnline(Context mContext, String purl, String pemail, String ppass) {
this.mContext = mContext;
Purl = purl;
Pemail = pemail;
Ppass = ppass;
}
MySession session = new MySession(mContext);
put MySession session = new MySession(mContext); into MLoginOnline
final code will be like this
MySession session;
public MLoginOnline(Context mContext, String purl, String pemail, String ppass) {
this.mContext = mContext;
Purl = purl;
Pemail = pemail;
Ppass = ppass;
session = new MySession(mContext);
}
You are using getApplicationContext() while creating MLoginOnline object.
I would say better use 'this' here.
here you could see the differences between context type
Difference between getContext() , getApplicationContext() , getBaseContext() and “this”

How to get values from shared preference and check it using if

Hi I'm using user login screen. In that I'm using shared preferences to store the user details and store whether the user is logged in or not. I'm using splash screen and in that splash activity I checked a value from sharedpreference to know whether the user is already logged in or not.If the user logged in,then after splash it will go to dashboard otherwise it goes to login screen.But i am getting null pointer error.please help me.
My shared prefrence class is:
public class Userloginsession {
public static final String IS_User_login = "isuserloggedin";
// {"did":"1","drivername":"arul ji","dusername":"PIKDRIVER01","logid":"79"}
//Driver Login details
//From DRIVER
public static final String IS_SNO = "sno";
public static final String IS_USERNAME = "userloginname";
public static final String IS_USERPASSWORD = "userloginpassword";
//
public static final String IS_EMP_ID = "emp_id";
//
//From Json Driver
public static final String IS_FIRST_NAME = "first_name";
public static final String IS_LAST_NAME = "last_name";
public static final String IS_IMAGE = "image";
static SharedPreferences user_details;
// Editor Reference for sharedpref
SharedPreferences.Editor user_details_editor;
public Userloginsession(final Context applicationContext) {
// create sharedpreff file "driverSession" for DRIVERLOGINACTIVITY
user_details = applicationContext.getSharedPreferences("usersession",0);
//Edit pfeff file
user_details_editor = user_details.edit();
user_details_editor.apply();
}
public static boolean isuserLoggedIn() {
return user_details.getBoolean(IS_User_login, false);
}
public void createuserLogin(String passwordp, String username, String SNO, final String EMP_ID, final String FIRST_NAME, final String LAST_NAME, final String Image) {
user_details_editor.putBoolean(IS_User_login, true);
user_details_editor.putString(IS_USERNAME, username);
user_details_editor.putString(IS_USERPASSWORD, passwordp);
user_details_editor.putString(IS_SNO, SNO);
user_details_editor.putString(IS_EMP_ID, EMP_ID);
user_details_editor.putString(IS_FIRST_NAME, FIRST_NAME);
user_details_editor.putString(IS_LAST_NAME, LAST_NAME);
user_details_editor.putString(IS_IMAGE, Image);
user_details_editor.commit();
}
public HashMap<String, String> isGetuserDetails() {
// Use hashmap to store user credentials
final HashMap<String, String> userdetailsmap = new HashMap<>();
// Driv pass
userdetailsmap.put(IS_USERNAME, user_details.getString(IS_USERNAME, null)); // Driv Pass
// Driver user name
userdetailsmap.put(IS_USERPASSWORD, user_details.getString(IS_USERPASSWORD, null));
// Driver ID
userdetailsmap.put(IS_SNO, user_details.getString(IS_SNO, null));
//Driver Name
userdetailsmap.put(IS_EMP_ID, user_details.getString(IS_EMP_ID, null));
userdetailsmap.put(IS_FIRST_NAME, user_details.getString(IS_FIRST_NAME, null));
userdetailsmap.put(IS_LAST_NAME, user_details.getString(IS_LAST_NAME, null));
userdetailsmap.put(IS_IMAGE, user_details.getString(IS_IMAGE, null));
return userdetailsmap;
}
public void clearAllvalues() {
user_details_editor = user_details.edit();
user_details_editor.clear();
user_details_editor.apply();
}
}
My splashscreen acticty is :
public class Splashscreen extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen2);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
if (Userloginsession.isuserLoggedIn()) {
// startActivity(new Intent(MainActivity.this, RideHistry.class));
startActivity(new Intent(Splashscreen.this, Dashboard.class));
/*overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);*/
finish();
} else {
// if driver not login go to DriverLogin Activity
startActivity(new Intent(Splashscreen.this, MainActivity.class));
finish();
}
/*} else {
startActivity(new Intent(Splashscreen.this, MainActivity.class));
finish();
}*/
}
}, SPLASH_TIME_OUT);
}
}
My error is:
Process: com.example.notebook.dptextiles, PID: 214 java.lang.NullPointerException:
Attempt to invoke interface method 'boolean android.content.SharedPreferences.getBoolean(java.lang.String, boolean)' on a null object reference
at com.example.notebook.dptextiles.fragments.Userloginsession.isuserLoggedIn(Userloginsession.java:45
at com.example.notebook.dptextiles.Splashscreen$1.run(Splashscreen at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
You are using Userloginsession.isuserLoggedIn() directly
use it like this
Userloginsession login=new Userloginsession(getApplicationContext());
if (login.isuserLoggedIn())
The problem is your are not initializing the sharedpreference. Ie. Userloginsession not get initialized. For that you need to give activity context.
the overall class should be
public class Splashscreen extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen2);
Userloginsession login=new Userloginsession(getApplicationContext());
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
if (login.isuserLoggedIn()) {
// startActivity(new Intent(MainActivity.this, RideHistry.class));
startActivity(new Intent(Splashscreen.this, Dashboard.class));
/*overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);*/
finish();
} else {
// if driver not login go to DriverLogin Activity
startActivity(new Intent(Splashscreen.this, MainActivity.class));
finish();
}
/*} else {
startActivity(new Intent(Splashscreen.this, MainActivity.class));
finish();
}*/
}
}, SPLASH_TIME_OUT);
}
}
Make sure your shared preferences is initialised before query. Put a breakpoint and debug.
you user_details shared preference is null..
in your Splash Activity:
initialize it like:
Userloginsession session = new Userloginsession(Splashscreen.this);
if (session.isuserLoggedIn()) {
First create a seperate Preference class
PrefManager.java
package name;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import java.util.HashMap;
/**
* Created by Ravi on 08/07/15.
*/
public class PrefManager {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "MegaInfomatix";
// All Shared Preferences Keys
private static final String KEY_IS_WAITING_FOR_SMS = "IsWaitingForSms";
private static final String KEY_MOBILE_NUMBER = "mobile_number";
private static final String KEY_IS_LOGGED_IN = "isLoggedIn";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_MOBILE = "mobile";
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setIsWaitingForSms(boolean isWaiting) {
editor.putBoolean(KEY_IS_WAITING_FOR_SMS, isWaiting);
editor.commit();
}
public boolean isWaitingForSms() {
return pref.getBoolean(KEY_IS_WAITING_FOR_SMS, false);
}
public void setMobileNumber(String mobileNumber) {
editor.putString(KEY_MOBILE_NUMBER, mobileNumber);
editor.commit();
}
public String getMobileNumber() {
return pref.getString(KEY_MOBILE_NUMBER, null);
}
public void createLogin(String name, String email, String mobile) {
editor.putString(KEY_NAME, name);
editor.putString(KEY_EMAIL, email);
editor.putString(KEY_MOBILE, mobile);
editor.putBoolean(KEY_IS_LOGGED_IN, true);
editor.commit();
}
public boolean isLoggedIn() {
return pref.getBoolean(KEY_IS_LOGGED_IN, false);
}
public void clearSession() {
editor.clear();
editor.commit();
}
public HashMap<String, String> getUserDetails() {
HashMap<String, String> profile = new HashMap<>();
profile.put("name", pref.getString(KEY_NAME, null));
profile.put("email", pref.getString(KEY_EMAIL, null));
profile.put("mobile", pref.getString(KEY_MOBILE, null));
return profile;
}
}
do this in LoginActivity class and in onCreate method
before onCreate method create preference class object
Preference pref;
pref = new PrefManager(this);
if (pref.isLoggedIn()) {
Intent intent = new Intent(SmsActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}

Saving user_id responce from JSON to sharepreferance

can any one help me out I really need a solution, I have already search on SO, could not success !
I want to store auto generated user_id which I am receiving from server as a JSON response in my share preference and then again get from share preference to other activity and send as a parameter to server
Here is my login Activity where I am receiving unique user id in JSON response when sending username and pass to server
public void connect(String useremail, String userpassword) throws JSONException, IOException
{
RestClient1 client = new RestClient1(Constants.serverPath + Constants.loginMethod);
client.addParam("email", useremail);
client.addParam("password", userpassword);
client.addHeader("content-type", "application/json");
try
{
String response = client.executePost();
JSONObject jsonResponse = new JSONObject(response);
String jsonData = jsonResponse.getString("code");
String jData = jsonResponse.getString("ResponseStatus");
jsData = jData;
if (jsonData.equals("200"))
{
System.out.println("responseStatus =" + jData);
startActivity(new Intent(LoginMainActivity.this, DashBoardActivity.class));
finish();
}
In the "ResponseStatus" I am geting "Login Succsesfull , user_id=1" from server <**<< want to store this response on Share Preference**
My Basic Session Manager class which is not fully construct for storing response in JSON
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 = "Apppersonal";
// All Shared Preferences Keys
private static final String KEY_USERID = "user_id";
// public static final String KEY_FULLNAME = "fullName";
// public static final String KEY_EMAIL = "email";
// public static final String KEY_DOB = "dateofbirth";
// public static final String KEY_ADDRESS = "address";
// Constructor
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void createloginSession(int user_id)
{
// Storing id in pref
editor.putInt(KEY_USERID, user_id);
editor.commit();
}
public HashMap<String, String> getPersonalDetails() {
HashMap<String, String> userPersonal = new HashMap<String, String>();
userPersonal.put(KEY_FULLNAME, pref.getString(KEY_FULLNAME, null));
userPersonal.put(KEY_DOB, pref.getString(KEY_DOB, null));
userPersonal.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
userPersonal.put(KEY_ADDRESS, pref.getString(KEY_ADDRESS, null));
// return user
return userPersonal;
// TODO Auto-generated method stub
// return null;
}
// 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, LoginMainActivity.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);
}
}
After getting the user_id just do the following:
SessionManager mSessionManager = new SessionManager(context);
mSessionManager.createloginSession(user_id);
Put it after extending activity
SessionManager session;
And in your method put this
session.createLoginSession(json.getString(user_id));

Categories

Resources