This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Help me on android SharedPreferences, I have login activity when after login will set the SharedPreferences, but when set SharedPreferences always error null pointer. I try to show the value with toast and all variable have value. this my activity
public class LoginNewActivity extends Activity {
public SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView toRegister = (TextView) findViewById(R.id.link_to_register);
toRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(i);
}
});
final EditText etUsnm = (EditText) findViewById(R.id.tuserid);
final EditText etPswd = (EditText) findViewById(R.id.tpasswd);
Button bLogin = (Button) findViewById(R.id.btnLogin);
bLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = etUsnm.getText().toString();
String password = etPswd.getText().toString();
new UserLoginTask().execute(username, password);
}
});
}
public class UserLoginTask extends AsyncTask<String, String, JSONObject> {
ProgressDialog pdLoading = new ProgressDialog(LoginNewActivity.this);
HttpURLConnection conn;
URL url = null;
JSONParser jsonParser = new JSONParser();
private static final String TAG_MESSAGE = "message";
private static final String TAG_NAMA = "nama_user";
private static final String TAG_USERNAME = "username";
private static final String TAG_HAKAKSES = "role";
private static final String TAG_ERROR = "error";
private static final String LOGIN_URL = "http://192.168.1.101/mlls/getLoginNew.php";
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> params = new HashMap<>();
params.put("username", args[0]);
params.put("password", args[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
String nama = "";
int iduser = 0;
String email = "";
String hakakses = "";
int error_message = 0;
if (json != null) {
//Toast.makeText(LoginActivity.this, json.toString(),
//Toast.LENGTH_LONG).show();
try {
nama = json.getString(TAG_NAMA);
email = json.getString(TAG_USERNAME);
hakakses = json.getString(TAG_HAKAKSES);
error_message = json.getInt(TAG_ERROR);
} catch (JSONException e) {
e.printStackTrace();
}
}
if(error_message == 1) {
pdLoading.dismiss();
session.setLogin(true);
session.setStatus(hakakses);
session.setNama(nama);
session.setUsername(email);
session.setId(iduser);
Toast.makeText(LoginNewActivity.this, hakakses,
Toast.LENGTH_LONG).show();
//Intent intent = new Intent(LoginNewActivity.this, LessonListActivity.class);
//intent.putExtra("nama", nama);
//intent.putExtra("email", email);
//intent.putExtra("hakakses", hakakses);
//startActivity(intent);
//LoginNewActivity.this.finish();
}else{
Toast.makeText(getApplicationContext(), "User ID atau Password anda salah.", Toast.LENGTH_LONG).show();
}
}
}}
and this is my sharedPreferences
public class SessionManager {
private static String TAG = SessionManager.class.getSimpleName();
SharedPreferences pref;
Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "Hlls";
private static final String KEY_IS_LOGGEDIN = "isLoggenIn";
private static final String KEY_IS_USER = "isStatus";
private static final String KEY_IS_NAMA = "isNama";
private static final String KEY_IS_USERNAME = "isUsername";
private static final String KEY_IS_IDUSER = "isIdUser";
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setLogin(boolean isLoggedIn){
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
editor.commit();
Log.d(TAG, "User login session modified");
}
public void setId(int isIdUser){
editor.putInt(KEY_IS_IDUSER, isIdUser);
editor.commit();
Log.d(TAG, "ID User akses session modified");
}
public void setStatus(String isStatus){
editor.putString(KEY_IS_USER, isStatus);
editor.commit();
Log.d(TAG, "User akses session modified");
}
public void setNama(String isNama){
editor.putString(KEY_IS_NAMA, isNama);
editor.commit();
Log.d(TAG, "Username session modified");
}
public void setUsername(String isUsername){
editor.putString(KEY_IS_USERNAME, isUsername);
editor.commit();
Log.d(TAG, "Username session modified");
}
public String isNama(){
return pref.getString(KEY_IS_NAMA, "");
}
public int isId(){
return pref.getInt(KEY_IS_IDUSER, 0);
}
public String isUsername(){
return pref.getString(KEY_IS_USERNAME, "");
}
public boolean isLoggedIn(){
return pref.getBoolean(KEY_IS_LOGGEDIN, false);
}
public String isStatus(){
return pref.getString(KEY_IS_USER, "");
}
}
help me for this error, sorry for bad english
NullPointerException is thrown when an application attempts to use an
object reference that has the null value .
You should call this in your ONCREATE section .
session=new SessionManager(LoginNewActivity.this);
Finally
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
session=new SessionManager(LoginNewActivity.this);
Use mode private instead of private mode
pref = _context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
It is flag provided by android itself you need not assign any other flag to it.
and you have not initialized session manager context is null.
I guess you are not initializing your Shared Preference class.
SessionManager session = new SessionManager(this);
In case its true
Please try and make it a singleton class as a general practise
Something like this
public final class PreferenceManager {
private static SharedPreferences preferences;
/**
* Private constructor to restrict the instantiation of class.
*/
private PreferenceManager() {
throw new AssertionError();
}
public static SharedPreferences getInstance(Context context) {
if (preferences == null && context != null) {
preferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
}
return preferences;
}
}
You need to do the following in your Activity:
session = new SessionManager(LoginNewActivity.this);
You have not created the object of your SessionManager class, so its constructor never gets called and you get NPE.
Related
I am trying to create app that can connect to a MS SQL database when the user enters his username and password, I have tried multiple times and just cannot succeed. What would be the best way to connect my app?
This is the code that I have tried below.
public class LoginActivity extends AppCompatActivity {
private static String ip = "myip";
private static String port = "myportnum";
private static String Class = "net.sourceforge.jtds.jtbc.Driver";
private static String database = "name";
private static String username = "name";
private static String password = "password";
private static String url = "jdbc:jtds:sqlserver://"+ip+":"+port+"/"+database;
private Connection connection = null;
private EditText userNameET, passwordEt;
private Button loginBTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userNameET = findViewById(R.id.userNameEditText);
passwordEt = findViewById(R.id.passEditText);
loginBTN = findViewById(R.id.loginBtn);
StrictMode.ThreadPolicy policy = null;
policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// #android.support.annotation.RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
private class DoLoginForUser extends AsyncTask<String, Void, String> {
String emailId, password;
#Override
protected void onPreExecute() {
super.onPreExecute();
emailId = userNameET.getText().toString();
password = passwordEt.getText().toString();
// progressBar.setVisibility(View.VISIBLE);
loginBTN.setVisibility(View.GONE);
}
#Override
protected String doInBackground(String... params) {
try {
ConnectionHelper con = new ConnectionHelper();
Connection connect = ConnectionHelper.CONN();
String query = "Select * from testDatabase where UserId='" + emailId + "'";
PreparedStatement ps = connect.prepareStatement(query);
Log.e("query",query);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
String passcode = rs.getString("password");
connect.close();
rs.close();
ps.close();
if (passcode != null && !passcode.trim().equals("") && passcode.equals(password))
return "success";
else
return "Invalid Credentials";
} else
return "User does not exists.";
} catch (Exception e) {
return "Error:" + e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
//Toast.makeText(signup.this, result, Toast.LENGTH_SHORT).show();
// ShowSnackBar(result);
// progressBar.setVisibility(View.GONE);
loginBTN.setVisibility(View.VISIBLE);
if (result.equals("success")) {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("userdetails",0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("email",userNameET.getText().toString());
editor.commit();
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
} else {
//ShowSnackBar(result);
}
}
}
//public void ShowSnackBar(String message) {
// Snackbar.make(lvparent, message, Snackbar.LENGTH_LONG)
// .setAction("CLOSE", new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//// }
// })
// .setActionTextColor(getResources().getColor(android.R.color.holo_red_light))
// .show();
// }
public void DoLogin(View v)
{
DoLoginForUser login = null;
login = new DoLoginForUser();
login.execute("");
}
I am expecting it to connect and then take me to the next screen.
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 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”
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