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
Related
Hi in the below code I was implemented ontime login feature but it is not working with below code.If login is successful then it will redirecting to MainActivity.Next time want to skip login page directly it should show main activity.
SplashActivity.java:
final boolean needLogin = getIntent().getBooleanExtra("need login extra", true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
if(!needLogin) {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}else {
Intent i = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
}
},
Once the login is successfull it will redirect to MAninactivity.java.Entire app I am using session.
LoginActivity.java:
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
LoginAndFetchModules loginAndFetchModules = response.body();
String success = loginAndFetchModules.getSuccess();
if (success.equals("true")) {
Results results = loginAndFetchModules.getResult();
//parse login details
GetLoginListDetails loginDetails = results.getLogin();
String userId = loginDetails.getUserid();
String sessionId = loginDetails.getSession();
String firstname = loginDetails.getFirst_name();
String lastname = loginDetails.getLast_name();
String mobile = loginDetails.getMobile();
String role = loginDetails.getRole();
String reportto = loginDetails.getReportto();
//parse modules
ArrayList<LoginListForModules> modules = results.getModules();
//parse module information
for (LoginListForModules module : modules) {
module_id = module.getId();
String name = module.getName();
String isEntity = module.getIsEntity();
String label = module.getLabel();
String singular = module.getSingular();
}
if (username.equals(username1.getText().toString()) && password.equals(password1.getText().toString())) {
// fetchUserJSON(sessionId,username);
Toast.makeText(getApplicationContext(), "Login Successfully", Toast.LENGTH_LONG).show();
i = new Intent(LoginActivity.this, MainActivity.class);
// loader.setVisibility(View.GONE);
progressDialog.dismiss();
// llProgressBar.setVisibility(View.GONE);
i.putExtra("sessionId", sessionId);
i.putExtra("module_id", module_id);
i.putExtra("username", username);
i.putExtra("firstname", firstname);
i.putExtra("lastname", lastname);
i.putExtra("mobile", mobile);
i.putExtra("role", role);
i.putExtra("reportto", reportto);
startActivity(i);
finish();
} else {
Toast.makeText(getApplicationContext(), "Invalid Username and Password", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "Invalid Username and Password", Toast.LENGTH_LONG).show();
}
}
You can use SharedPreferences.
A SharedPreferences object points to a file containing key-value
pairs and provides simple methods to read and write them.
DEMO CODE
public class SharedPreferenceClass
{
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "Test";
public static final String KEY_SET_LOGIN_STATUS= "KEY_SET_LOGIN_STATUS";
public SharedPreferenceClass(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, 0);
editor = pref.edit();
}
public void setLoginStatus(String status)
{
editor.remove(KEY_SET_LOGIN_STATUS);
editor.putString(KEY_SET_LOGIN_STATUS, status);
editor.commit();
}
public String getLoginStatus()
{
String status= pref.getString(KEY_SET_LOGIN_STATUS, "");
return status;
}
}
Now you can store login status ( setLoginStatus("Login")) when ever login success And check your login status getLoginStatus(). If return "Login" then return to your desire activity.
I am very new in android.In my app I make a login page.I use Shared Preferences for session.it works fine but a problem when i close my app and again open then login page comes.I want when user press logout button only that time login page will come.
this is my SharedPreferences class
public class SharedPrefManager {
//the constants
private static final String SHARED_PREF_NAME = "dreamzsharedpref";
private static final String KEY_USERNAME = "keyusername";
private static final String KEY_PHONE = "keyphone";
private static final String KEY_ID = "keyid";
private static SharedPrefManager mInstance;
private static Context mCtx;
private SharedPrefManager(Context context) {
mCtx = context;
}
public static synchronized SharedPrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
//method to let the user login
//this method will store the user data in shared preferences
public void userLogin(User user) {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_ID, user.getUserid());
editor.putString(KEY_PHONE, user.getUserphno());
editor.putString(KEY_USERNAME, user.getUsername());
editor.apply();
}
//this method will checker whether user is already logged in or not
public boolean isLoggedIn() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_PHONE, null) != null;
}
//this method will give the logged in user
public User getUser() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return new User(
sharedPreferences.getString(KEY_USERNAME, null),
sharedPreferences.getString(KEY_PHONE, null),
sharedPreferences.getInt(KEY_ID, -1)
);
}
//this method will logout the user
public void logout() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
mCtx.startActivity(new Intent(mCtx, LoginActivity.class));
}
}
this is my login method in login class
private void userLogin() {
//first getting the values
final String username = UsernameEt.getText().toString();
final String password = PasswordEt.getText().toString();
//validating inputs
if (TextUtils.isEmpty(username)) {
UsernameEt.setError("Please enter your username");
UsernameEt.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
PasswordEt.setError("Please enter your password");
PasswordEt.requestFocus();
return;
}
//if everything is fine
class UserLogin extends AsyncTask<Void, Void, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("vuserphno", username);
params.put("votp", password);
//returing the response
return requestHandler.sendPostRequest(URLs.URL_LOGIN, params);//this URLs is a class where URL_LOGIN is login url
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressBar.setVisibility(View.GONE);
try {
JSONObject obj = new JSONObject(s);
JSONArray array = obj.getJSONArray("user");
for (int i = 0; i < array.length(); i++) {
//getting the user from the response
JSONObject userJson = array.getJSONObject(i);
//creating a new user object
User user = new User(
userJson.getString("username"),
userJson.getString("userphno"),
userJson.getInt("userid")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
}
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
UserLogin ul = new UserLogin();
ul.execute();
}
please tell me where is the problem and how I can solve this problem.
Thanks.
In your LoginActivity, check for login state and change activity, finish itself so it's clear from the back stack.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (SharedPrefManager.getInstance().isLoggedIn(this)) {
startActivity(this, MainActivity.class);
finish();
return;
}
// ...
}
JSON DATA
{
VerifiedMember: [{ user_id: "23", first_name: "karan", phone: "" }],
success: 1,
message: "success"
}
Login Activity Class
public class NewLogin extends AppCompatActivity {
private static final String PREFER_NAME = "Reg";
Button btnLogin;
private EditText editTextUserName;
private EditText editTextPassword;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
SharedPreferences sharedPreferences;
// User Session Manager Class
UserSessionManager session;
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login);
// User Session Manager
session = new UserSessionManager(getApplicationContext());
sharedPreferences = getApplication().getSharedPreferences("KEY", Context.MODE_PRIVATE);
sharedPreferences = getSharedPreferences(PREFER_NAME, Context.MODE_PRIVATE);
editTextUserName = (EditText) findViewById(R.id.et_email);
editTextPassword = (EditText) findViewById(R.id.et_password);
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
}
public void invokeLogin(View view) {
new loginAccess().execute();
}
private class loginAccess extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewLogin.this);
pDialog.setMessage("Login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
}
#Override
protected String doInBackground(String... arg0) {
List<NameValuePair> params = new ArrayList<>();
// Get username, password from EditText
String username = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
String url = "xxxx.xxx";
JSONObject json;
int successValue = 0;
try {
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
json = jsonParser.makeHttpRequest(url, "POST", params);
// Validate if username, password is filled
if(username.trim().length() > 0 && password.trim().length() > 0){
String uName = null;
String uPassword =null;
if (sharedPreferences.contains("username")) {
uName = sharedPreferences.getString("username", "");
}
if (sharedPreferences.contains("password")) {
uPassword = sharedPreferences.getString("password", "");
}
if (username.equals(uName) && password.equals(uPassword)) {
session.createUserLoginSession("username", "password");
} else {
}
}else{
}
Log.d("TESS :: ", json.toString());
successValue = json.getInt("success");
Log.d("Success Response :: ", String.valueOf(successValue));
} catch (Exception e1) {
// TODO Auto-generated catch block flag=1;
e1.printStackTrace();
}
return String.valueOf(successValue);
}
protected void onPostExecute(String jsonstring) {
pDialog.dismiss();
if (jsonstring.equals("1")) {
Intent i = new Intent(NewLogin.this, Sample.class);
startActivity(i);
finish();
} else {
Toast.makeText(NewLogin.this, "Please enter the correct details!!", Toast.LENGTH_LONG).show();
}
}
}
}
Sample activity:
public class Sample extends AppCompatActivity {
private static final String URL_DATA = "xxx.xxx";
// User Session Manager Class
UserSessionManager session;
LinearLayout linearLayout;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private SwipeRefreshLayout swipeRefreshLayout;
private List<Data_SAerver> data_sAervers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
// Session class instance
session = new UserSessionManager(getApplicationContext());
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
loadRecyclerViewData();
swipeRefreshLayout.setRefreshing(false);
}
});
swipeRefreshLayout.setColorScheme(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
linearLayout = (LinearLayout) findViewById(R.id.linaralayout1);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Sample.this, Post_data_Activity.class);
startActivity(i);
}
});
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
data_sAervers = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
String filename = "";
String filetype = "";
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray posts = jsonObject.getJSONArray("posts");
if (posts != null && posts.length() > 0) {
for (int i = 0; i < posts.length(); i++) {
JSONObject fileObj = posts.getJSONObject(i);
String fName = fileObj.getString("firstname");
String created_at = fileObj.getString("created_at");
String post_desc = fileObj.getString("post_desc");
Log.e("Details", fName + "" + created_at + "" + post_desc);
JSONArray files = fileObj.getJSONArray("files");
if (files != null && files.length() > 0) {
for (int j = 0; j < files.length(); j++) {
JSONObject Jsonfilename = files.getJSONObject(j);
filename = Jsonfilename.getString("file_name");
filetype = Jsonfilename.getString("file_type");
if (filetype.equalsIgnoreCase("2")) {
filename = "xxx.xxx" + filename;
} else if(filetype.equalsIgnoreCase("1")) {
filename = "xxx.xxx" + filename;
}
Log.e("Files", "" + filename);
}
} else {
filename = "";
filetype = "";
}
Data_SAerver item = new Data_SAerver(fName, created_at, post_desc, filename, filetype);
data_sAervers.add(item);
}
}
adapter = new MyAdapter(data_sAervers, getApplicationContext());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menuLogout:
session.logoutUser();
/*startActivity(new Intent(this, NewLogin.class));
break;*/
}
return true;
}
}
MyAdapter class:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<Data_SAerver> data_sAervers;
private Context context;
public MyAdapter(List<Data_SAerver> data_sAervers, Context context) {
this.data_sAervers = data_sAervers;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.sample, parent, false);
return new ViewHolder(v, context);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Data_SAerver data_sAerver = data_sAervers.get(position);
holder.firstname.setText(data_sAerver.getFirstname());
holder.created_at.setText(data_sAerver.getCreated_at());
holder.post_desc.setText(data_sAerver.getPost_desc());
holder.filepathurl.setText(data_sAerver.getfilepath());
if (data_sAerver.getFiletype().equals("1")) {
holder.files.setVisibility(View.VISIBLE);
Picasso.with(context).load(data_sAerver.getfilepath()).resize(736, 1128).onlyScaleDown().into(holder.files);
holder.playvideo.setVisibility(View.GONE);
} else {
if (data_sAerver.getFiletype().equals("2")) {
holder.playvideo.setVisibility(View.VISIBLE);
holder.files.setVisibility(View.GONE);
holder.playvideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent play = new Intent(context, PlayVideo.class);
play.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
play.putExtra("url", data_sAerver.getfilepath());
context.startActivity(play);
}
});
}
}
}
#Override
public int getItemCount() {
return data_sAervers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// User Session Manager Class
UserSessionManager session;
public TextView firstname, commenttext;
public TextView created_at;
public TextView post_desc;
public ImageView files;
public LinearLayout comment_linear_layout;
public TextView comment_btn;
public TextView filepathurl;
public TextView playvideo;
// private TextView editTextUserName;
public TextView onlinefirstname;
Context con;
public ViewHolder(View itemView, Context context) {
super(itemView);
filepathurl = (TextView) itemView.findViewById(R.id.filepathurl);
filepathurl.setVisibility(View.GONE);
// editTextUserName = (TextView) itemView.findViewById(R.id.editTextUserrName);
playvideo = (TextView) itemView.findViewById(R.id.playvideo);
firstname = (TextView) itemView.findViewById(R.id.firstname);
created_at = (TextView) itemView.findViewById(R.id.created_at);
post_desc = (TextView) itemView.findViewById(R.id.post_desc);
files = (ImageView) itemView.findViewById(R.id.image_files);
con = context;
// onlinefirstname = (TextView)itemView.findViewById(R.id.online_user_firstname);
SparkButton sparkButton = (SparkButton) itemView.findViewById(R.id.star_button1);
sparkButton.setChecked(false);
comment_btn = (TextView) itemView.findViewById(R.id.comment_btn);
comment_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(con, Popup_layout.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
con.startActivity(i);
}
});
}
}
}
UserSessionManager:
public class UserSessionManager {
// Shared Preferences reference
SharedPreferences pref;
// Editor reference for Shared preferences
Editor editor;
// Context
Context _context;
// Shared preferences mode
int PRIVATE_MODE = 0;
// Shared preferences file name
public static final String PREFER_NAME = "Reg";
// All Shared Preferences Keys
public static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "username";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "firstname";
// password
public static final String KEY_PASSWORD = "password";
// Constructor
public UserSessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Create login session
public void createUserLoginSession(String uName, String uPassord){
// Storing login value as TRUE
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, uName);
// Storing email in pref
editor.putString(KEY_PASSWORD, uPassord);
// commit changes
editor.commit();
}
/**
* Check login method will check user login status
* If false it will redirect user to login page
* Else do anything
* */
public boolean checkLogin() {
// Check login status
if (!this.isUserLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Sample.class);
// Closing all the Activities from stack
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 true;
}
return false;
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails() {
//Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
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 user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Login Activity
Intent i = new Intent(_context, NewLogin.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);
}
// Check for login
public boolean isUserLoggedIn(){
return pref.getBoolean(IS_USER_LOGIN, false);
}
}
Here I am not able to get user_id using shared preference. Please help me how to get it.
In onPostExecute try this you will get User ID
try {
String userid;
JSONObject ob = new JSONObject(jsonstring);
JSONArray arr = ob.getJSONArray("VerifiedMember");
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
userid=obj.getString("user_id");
}
} catch (Exception e) {
}
You can use this pojo generator
http://www.jsonschema2pojo.org/
For parsing you can use google's gson library or jackson parser is also good.
http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html
I know there are n number of examples in android for shared preferences but I want to Register and store the info in shared preferences and in database using JSON. And then fetch data from JSON and Login with those credentials. If user is already logged in open Main Activity,else go to Splash screen and then open Login Activity. Please go through my detailed code :
RegisterActivity :
public class RegisterActivity extends AppCompatActivity implements ServerRequests.Registereponse {
private EditText password, phone, email;
public static EditText name;
ServerRequests serverRequests;
JSONParser jsonParser;
private Button registerButton;
TextView alreadyMember;
Editor editor;
UserSession session;
SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs";
public static final String Name1 = "nameKey";
public static final String Phone1 = "phoneKey";
public static final String Email1 = "emailKey";
public static final String Password1 = "passwordKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setRegistereponse(this);
alreadyMember = (TextView) findViewById(R.id.alreadyMember);
name = (EditText) findViewById(R.id.FName);
phone = (EditText) findViewById(R.id.PhoneNum);
email = (EditText) findViewById(R.id.mail);
password = (EditText) findViewById(R.id.password);
registerButton = (Button) findViewById(R.id.email_sign_in_button);
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence temp_emailID = email.getText().toString();
if (name.getText().toString().length() == 0) {
name.setError("Please enter your name");
name.requestFocus();
} else if (phone.getText().toString().length() == 0) {
phone.setError("Please enter your phone number");
phone.requestFocus();
} else if (!isValidEmail(temp_emailID)) {
email.setError("Please enter valid email");
email.requestFocus();
} else if (password.getText().toString().length() == 0) {
password.setError("Please enter password");
password.requestFocus();
} else {
try {
String Name = name.getText().toString();
String Email = email.getText().toString();
String Password = password.getText().toString();
String Phone = phone.getText().toString();
JSONObject obj = jsonParser.makeRegisterJson(Name, Email, Password, Long.parseLong(Phone));
Log.e("final Json", obj.toString());
serverRequests.register(obj);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Name1, Name);
editor.putString(Email1, Email);
editor.putString(Password1, Password);
editor.putString(Phone1, Phone);
editor.commit();
// Toast.makeText(RegisterActivity.this, "Registered Successfully!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
}
}
// startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}
});
alreadyMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
finish();
}
});
}
#Override
public void onRegsiterReposne(JSONObject object) {
Toast.makeText(RegisterActivity.this, "hiii" + object.toString(), Toast.LENGTH_SHORT).show();
}
public final static boolean isValidEmail(CharSequence target) {
if (TextUtils.isEmpty(target)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
}
LoginActivity :
public class LoginActivity extends AppCompatActivity implements ServerRequests.Loginreponse {
private static final String PREFER_NAME = "Reg";
private Button email_sign_in_button;
private EditText email, password;
private TextView notMember, forgotPass;
UserSession session;
private SharedPreferences sharedPreferences;
ServerRequests serverRequests;
JSONParser jsonParser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setLoginreponse(this);
notMember = (TextView) findViewById(R.id.notMember);
forgotPass = (TextView) findViewById(R.id.forgotPass);
notMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
finish();
}
});
forgotPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ForgotPassword.class));
}
});
// get Email, Password input text
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.pass);
// User Login button
email_sign_in_button = (Button) findViewById(R.id.login);
sharedPreferences = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
// Login button click event
email_sign_in_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
String Email = email.getText().toString();
String Password = password.getText().toString();
JSONObject obj = jsonParser.makeLoginJson(Email, Password);
Log.e("final Json", obj.toString());
serverRequests.login(obj);
} catch (Exception e) {
}
// startActivity(new Intent(LoginActivity.this, MainActivity.class));
// finish();
}
});
}
#Override
public void onLoginReposne(JSONObject object) {
Toast.makeText(LoginActivity.this, "helloo" + object.toString(), Toast.LENGTH_SHORT).show();
if (object.toString().contains("true")) {
Toast.makeText(LoginActivity.this, "Logged in..", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}
}
SplashScreen :
public class SplashScreen extends Activity {
Thread splashTread;
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
StartAnimations();
}
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
private void StartAnimations() {
Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
anim.reset();
LinearLayout l = (LinearLayout) findViewById(R.id.lin_lay);
l.clearAnimation();
l.startAnimation(anim);
anim = AnimationUtils.loadAnimation(this, R.anim.translate);
anim.reset();
ImageView iv = (ImageView) findViewById(R.id.splashImage);
iv.clearAnimation();
iv.startAnimation(anim);
/* TextView tv = (TextView) findViewById(R.id.splashText);
tv.clearAnimation();
tv.startAnimation(anim);*/
splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// Splash screen pause time
while (waited < 3500) {
sleep(100);
waited += 100;
}
startNextScreen();
} catch (InterruptedException e) {
// do nothing
} finally {
SplashScreen.this.finish();
}
}
};
splashTread.start();
}
private void startNextScreen() {
preferences = getSharedPreferences("TrainingApp", MODE_PRIVATE);
String userLoginStatus = preferences.getString("userLoginStatus", "no");
if (userLoginStatus.equals("no")) {
Intent intent = new Intent(SplashScreen.this,
LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
SplashScreen.this.finish();
} else {
Intent intent = new Intent(SplashScreen.this,
MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
SplashScreen.this.finish();
}
}
}
JSONParser class :
public class JSONParser {
//----------For Register
public JSONObject makeRegisterJson(String name, String email, String password, long phone) throws JSONException {
JSONObject object = new JSONObject();
object.put("name", name);
object.put("email", email);
object.put("password", password);
object.put("phone", phone);
// if its in array------
/*JSONObject finalObject=new JSONObject();
finalObject.put("request",object);
return finalObject;*/
return object;
}
//--------For Login--------------------------------------------------------
public JSONObject makeLoginJson(String Name, String password) throws JSONException {
JSONObject object = new JSONObject();
object.put("userName", Name);
object.put("password", password);
/*JSONObject finalObject=new JSONObject();
finalObject.put("request",object);
return finalObject;*/
return object;
}
}
ServerRequests class :
// ---------------- for register------------------------------------------------------------------------------
public void setRegistereponse(Registereponse registereponse) {
this.registereponse = registereponse;
}
private Registereponse registereponse;
public interface Registereponse {
void onRegsiterReposne(JSONObject object);
}
public void register(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (registereponse != null) {
registereponse.onRegsiterReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
// --------------For Login ---------------------------------------------------------------------------
public void setLoginreponse(Loginreponse loginreponse) {
this.loginreponse = loginreponse;
}
private Loginreponse loginreponse;
public interface Loginreponse {
void onLoginReposne(JSONObject object);
}
public void login(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.LOGIN_URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (loginreponse != null) {
loginreponse.onLoginReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
UserSession class :
public class UserSession {
// Shared Preferences reference
SharedPreferences pref;
// Editor reference for Shared preferences
Editor editor;
// Context
Context _context;
// Shared preferences mode
int PRIVATE_MODE = 0;
// Shared preferences file name
public static final String PREFER_NAME = "Reg";
// All Shared Preferences Keys
public static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "Name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "Email";
// password
public static final String KEY_PASSWORD = "Password";
public static final String KEY_PHONE = "PhoneNumber";
public static final String KEY_QUALIFICATION = "Qualification";
// Constructor
public UserSession(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Create login session
public void createUserLoginSession(String uEmail, String uPassword) {
// Storing login value as TRUE
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in preferences
editor.putString(KEY_EMAIL, uEmail);
// Storing email in preferences
editor.putString(KEY_PASSWORD, uPassword);
// commit changes
editor.commit();
}
/**
* Check login method will check user login status
* If false it will redirect user to login page
* Else do anything
*/
public boolean checkLogin() {
// Check login status
if (!this.isUserLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities from stack
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 true;
}
return false;
}
/**
* Get stored session data
*/
public HashMap<String, String> getUserDetails() {
//Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));
user.put(KEY_PHONE, pref.getString(KEY_PHONE, null));
user.put(KEY_QUALIFICATION, pref.getString(KEY_QUALIFICATION, null));
// return user
return user;
}
/**
* Clear session details
*/
public void logoutUser() {
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to MainActivity
Intent i = new Intent(_context, LoginActivity.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);
}
// Check for login
public boolean isUserLoggedIn() {
return pref.getBoolean(IS_USER_LOGIN, false);
}
}
At the time of login successfull put this code:
prefs = getSharedPreferences("logindetail", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("userLoginStatus", "yes");
edit.commit();
At the time of logout use this:
prefs = getSharedPreferences("logindetail", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.clear();
edit.commit();
And at the time of checking if user is login or not use below code:
Loginprefs = getApplicationContext().getSharedPreferences("logindetail", 0);
userLoginStatus = Loginprefs.getString("userLoginStatus", null);
if(userLoginStatus.tostring().equals("yes")){
//the user is login
}else{
//user is logout
}
Hope this helps you
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);
}
}