I have create an App where a User list for a group is already placed in a database on MySQL, the Usernames, passwords and variables assigned to them are already uploaded.
Below is the login activity that allows a user to log in and go to their own user area (There is a loginrequest class also that brings the params over).
What I need assistance with is making the application stay logged in until logout for that user even when they have closed the app.
Also will this if possible allow me to send user notifications when the app is closed to individual users?
thank you.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bLogin = (Button) findViewById(R.id.bLogin);
final TextView registerLink = (TextView) findViewById(R.id.tvRegisterHere);
//Register Here button
registerLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
//Login Button
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Taking the username and password and converting it to a string
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//Taking the JSONObject from the 000webhost database
JSONObject jsonResponse = new JSONObject(response);
//If the response is successful ie is there a username and password that match
boolean success = jsonResponse.getBoolean("success");
if (success){
//Gather the information below
String name = jsonResponse.getString("name");
int var1 = jsonResponse.getInt("var1");
int var2 = jsonResponse.getInt("var2");
int var3 = jsonResponse.getInt("var3");
int var4 = jsonResponse.getInt("var4");
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
intent.putExtra("name", name);
intent.putExtra("username", username);
intent.putExtra("var1", var1);
intent.putExtra("var2", var2);
intent.putExtra("var3", var3);
intent.putExtra("var4", var4);
intent.putExtra("password", password);
//Start the User Area Activity
LoginActivity.this.startActivity(intent);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
}
You can use SharedPreferences, to resolve your problem.
Use this to verify if the user has "session" started or not
private SharedPreferences sharedpreferences;
sharedpreferences=getApplicationContext().getSharedPreferences("Preferences", 0);
String login = sharedpreferences.getString("LOGIN", null);
if (login != null) {
//put your code if user is logged. For example, go to another activity
}else {
// to go login activity
}
Use this to set the "session" when click on login button
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("LOGIN", newUser.getEmail_user());
editor.commit
Use this on Logout Button
Editor editor = sharedpreferences.edit();
editor.remove("LOGIN");
editor.commit();
Related
Login using JSON with shared Preferences When user Enter their Phone Number then user got success from API and go to new activity and after resume app, users state will log in
When user Enter their Phone Number then user got success from API and go to new activity and after resume app, users state will log in
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView3);
usr_number = findViewById(R.id.usr_pass);
go = findViewById(R.id.button);
signup = findViewById(R.id.signup_signup);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getjsondata();
String hhh = usr_number.getText().toString();
url = "http://readnow.flatdeal4u.com/Api/Register.aspx?mobile=" + hhh + "&choice=2";
//Toast.makeText(MainActivity.this, ""+hhh, Toast.LENGTH_SHORT).show();
if (usr_number.getText().toString().isEmpty()) {
usr_number.setError("Enter Phone Number");
Toast.makeText(MainActivity.this, "Enter Details", Toast.LENGTH_SHORT).show();
} else {
if (usr_number.getText().toString().equals("" + hhh)) {
Intent intent = new Intent(MainActivity.this, select_your_exams.class);
startActivity(intent);
pref = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
pref.getString("mobilenumber", hhh);
pref.getString("nameofuser", "");
}
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Signup.class);
startActivity(intent);
}
});
}
Here are my JSON method codes:
public void get JSON data) {
final StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener < String > () {
#Override
public void onResponse(String response) {
try {
JSONObject jobj = new JSONObject(response);
JSONArray array = jobj.getJSONArray("userInfos");
//Toast.makeText(MainActivity.this, "data found"+array, Toast.LENGTH_LONG).show();
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
final Phn_modal mo = new Phn_modal();
final String mobile = obj.getString("mobileNumber");
final String name = obj.getString("fullName");
final String email = obj.getString("emailId");
Toast.makeText(MainActivity.this, "Welcome You-" + name, Toast.LENGTH_LONG).show();
mo.setMobile(mobile);
mo.setName(name);
mo.setEmailId(email);
mo.getMobile(mobile);
mo.getMobile(name);
editor.putString("mobilenumber", mobile);
editor.putString("nameofuser", name);
editor.apply();
editor.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
i think your question is , you login first time, and next time you again visit application that time directly go to the activity withouth asking login,
then you can try this.
public void storeString(SharedPreferences sharedPreferences, String key, String value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
above function is used to store the specific value in our shared prefrence, with given key.
Now when we hint the login button that time if login is success then store the login success value in our prefrence.
this one is usefull for again visit in your application
storeString(mPreferences, "Login_flag", "true");
-> Now, when we again visit application check the our prefrence is true or false.
if our prefrence is true then user already login, not required to login again
Check like this,
if(mPreferences.getString(PreferenceList.LOGIN_FLAG, "false").equals("true")){
//if alredy login then access this
}else{
//if not login then access this
}
if you want to create a login session in your app then you should create an preference class in your project and save data in that class and match the data where you want to use follow this answer to maintain the login session in your app:- Preventing users to login again after closing the app
I'm very new to programming and I'm writing to ask for help for my application. I'm using android studio 2.3.
I'm trying to create an app where there are two types of users which is high committee and non-high committee. The difference between both types of users is that the high committee has an additional activity which the non-high committee doesn't have.
High committee able to: Login, View calendar, Add/Update event
Non-high committee able to: Login, View calendar
However, I don't know how to create a login activity that allows these types of users to login in the same login screen using username and password and how to make these users to have a different Homepage.
I'd really appreciate any help with this, thanks in advance.
I have this code here below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bLogin = (Button) findViewById(R.id.bLogin);
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>(){
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(LoginActivity.this, HomeCalendar.class);
LoginActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
}
}
Send the usertype also, along with the server response and check the received usertype in your java code and then redirect to the corresponding home activity.
Below is a code sample. Please check it..
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
String user_type = jsonResponse.getString("user_type"); //get user_type from response
if (success) {
if(user_type.equals("high_committee")){ //check the type of user
Intent intent = new Intent(LoginActivity.this, HomeCommittee.class); //if user_type = committee, then redirect to Committee home activity
LoginActivity.this.startActivity(intent);
}
else{
Intent intent = new Intent(LoginActivity.this, HomeNonCommittee.class); //if user_type != committee, then redirect to Committee home activity
LoginActivity.this.startActivity(intent);
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I got user-login template from github. I modified it a bit to suit my need but didn't altered any important code.
Problem 1: If I register and login, the page goes to activity_main class(landing page) and my login credentials(name & email) are shown. But if I log out and logging again the credentials are not shown on the landing page. First time it shows next time never.
Problem 2: If I register a new ID but login with any old already registered ID (immediately after registering new), landing page shows the credential of newly register ID. After that again it won't show up if I log in with any ID.
What I want to Happen: User credential to be shown on landing page whenever he logs in.Also prob 2nd to be fixed.
Any help would be appreciated guys.
login page code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(Activity_Login.this, Activity_Main.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
Activity_Register.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
Config_URL.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(Activity_Login.this,
Activity_Main.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Register page code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
inputFullName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
inputNumber = (EditText) findViewById(R.id.number);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(Activity_Register.this,
Activity_Main.class);
startActivity(intent);
finish();
}
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
String number = inputNumber.getText().toString();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty() && !number.isEmpty()) {
registerUser(name, email, password, number);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
Activity_Login.class);
startActivity(i);
finish();
}
});
}
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String name, final String email,
final String password, final String number) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
Config_URL.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch login activity
Intent intent = new Intent(
Activity_Register.this,
Activity_Login.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "register");
params.put("name", name);
params.put("email", email);
params.put("password", password);
params.put("number", number);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Main activity page code:
public class Activity_Main extends Activity {
private TextView txtName;
private TextView txtEmail;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
public Button booknow;
public void init(){
booknow= (Button) findViewById(R.id.booknow);
booknow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent toy = new Intent(Activity_Main.this,BikeEntryActivity.class);
startActivity(toy);
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
txtName = (TextView) findViewById(R.id.name);
txtEmail = (TextView) findViewById(R.id.email);
btnLogout = (Button) findViewById(R.id.btnLogout);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
String email = user.get("email");
// Displaying the user details on the screen
txtName.setText(name);
txtEmail.setText(email);
// Logout button click event
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logoutUser();
}
});
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(Activity_Main.this, Activity_Login.class);
startActivity(intent);
finish();
}
}
For problem 1, when you logout, you are deleting users by calling db.deleteUsers();
When you login again, you need to call db.addUser(name, email, uid, created_at); as you did for registration.
The same applies for problem 2.
UPDATE:
....
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
//You need to save the user here before launching main activity.
db.addUser(name,email);//or whatever method you use to save user.
// Launch main activity
Intent intent = new Intent(Activity_Login.this,
Activity_Main.class);
startActivity(intent);
finish();
}
when a user exit my android app without clicking log out button the user still appears logged in in my online database, when next he opens the app he will be directed to the log in page and he can't log in since he appears logged in in the database, please how do i solve this problem, am using the 1 and 0 form of log in. thanks
enter code here
public class MainActivity extends Activity {
private EditText username;
private EditText password;
private TextView reg;
//private TextToSpeech myTTS;
//status check code
//private int MY_DATA_CHECK_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reg = (TextView)findViewById(R.id.reger);
username = (EditText)findViewById(R.id.UserText1);
password = (EditText)findViewById(R.id.PassText2);
// String Userid;
//String Passid= password.toString();
Button login = (Button)findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final SharedPreferences userid = getSharedPreferences("prefs",0);
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username.getText().toString()));
postParameters.add(new BasicNameValuePair("password", password.getText().toString()));
postParameters.add(new BasicNameValuePair("login", "1"));
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://www.website.com/login4.php", postParameters);
String res=response.toString();
res = res.trim();
res= res.replaceAll("\\s+","");
//reg.setText(res);
//error.setText(res);
if(username.getText().toString().equals("") || password.getText().toString().equals("")){
reg.setText("Sorry!! Incorrect Username or Password");
}
else if(res.equals(username.getText().toString()+password.getText().toString())){
SharedPreferences.Editor editor = userid.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", password.getText().toString());
editor.commit();
//speakWords("You are logged in succesfully");
startActivity(new Intent(MainActivity.this, HomePage.class));
}
else {
reg.setText(res);
}
} catch (Exception e) {
reg.setText("You have a network failure");
}
}
});
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, Registration.class);
startActivity(intent);
}
});
TextView freeview =(TextView)findViewById(R.id.Samp);
freeview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, Sample_year.class);
startActivity(intent);
}
});
}
// Set up an instance of SystemUiHider to control the system UI for
}
?
change the value to 0 in the onStop() method of the activity class which is called when your user navigates away from the app!
For anyone else in the future I'm using firebase so this is what I did:
if (firebaseAuth.getCurrentUser()!= null)
{
startActivity(new Intent(getApplicationContext(),NavActivity.class));
}
I am using SharedPreferences for saving credentials which works fine but when the application is killed the user is asked to login again.
When the credentials are saved the user should not be asked to login if the application is killed. Any help would be appreciated.
public class MyActivity extends Activity {
public static final String PREFS_NAME = "myFile";
private String user;
private String userName;
#Override
public void onRestart(){
super.onRestart();
userName = null;
user=null;
//Retrieve the preferences.
SharedPreferences credentials = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
user = credentials.getString(userName, null);
//Check for stored preferences.
if (user!=null) {
Intent j = new Intent(getApplicationContext(), MainActivity.class);
startActivity(j);
finish();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting default screen to login.xml
setContentView(R.layout.layout_login_new);
//Initializing the fields from XML layout.
final Button login_btn = (Button) findViewById(R.id.btnLogin);
//Retrieve the preferences.
SharedPreferences credentials = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
final SharedPreferences.Editor editor = credentials.edit();
userName = null;
user=null;
//retrieve the stored values.
user = credentials.getString(userName, null);
//Check for stored preferences.
if (user!=null){
Intent j = new Intent(getApplicationContext(), MainActivity.class);
j.putExtra("user_name", user);
startActivity(j);
finish();
}
//Listener for the login button.
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent j = new Intent(getApplicationContext(), MainActivity.class);
// Verify the username and password.
if (
(username_login.getText().toString()).equals("test")&&(password_login.getText().toString()).equals("test")){
//Store the credentials in sharedPreferences.
user=username_login.getText().toString();
editor.putString(userName, username_login.getText().toString()).commit();
j.putExtra("user_name", user);
startActivity(j);
finish();
}
else{
Display_error_msg();
}
}
});
The way you are doing has some errors, you have not commited shared preferences values and there is no proper tags for store and retrive. just look at this code
if ((username_login.getText().toString()).equals("test")&&(password_login.getText().toString()).equals("test")){
//Store the credentials in sharedPreferences.
user=username_login.getText().toString();
editor.putString("UserName", username_login.getText().toString()).commit();
editor.commit(); //// changes will be effect after commit only
j.putExtra("user_name", user);
startActivity(j);
finish();
} else {
Display_error_msg();
}
and in another activity
public class MyActivity extends Activity {
public static final String PREFS_NAME = "myFile";
private String user;
private String userName;
#Override
public void onRestart(){
super.onRestart();
userName = "UserName";
user=null;
//Retrieve the preferences.
SharedPreferences credentials = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
user = credentials.getString(userName, null);
//Check for stored preferences.
if (user!=null){
Intent j = new Intent(getApplicationContext(), MainActivity.class);
startActivity(j);
finish();
}
}
Use onResume() instead of onRestart() to checking user login.
These are activity's life cycles, Not application's. ie, onRestart() doesn't mean app restart.