Updating Shared Preferences while updating user information - java

I am using a Shared preferences class to hold the information of the user after login, for later updating I am using the information I have kept in the Share preferences class but when I update user information I have to log out from the profile and then log in the see the changes. Can anyone help me to in how to change the information in the SharedPrefManager class while I update the user info? Bellow is the SharedPrefManager Class and user updating Class.
public class SharedPrefManager {
private static SharedPrefManager mInstance;
private static Context mCtx;
private static final String SHARED_PREF_NAME = "mysharedpref";
private static final String KEY_USERNAME = "name";
private static final String KEY_USER_EMAIL = "email";
private static final String KEY_USER_ID = "id";
private static final String KEY_USER_DESCRIPTION = "description";
private SharedPrefManager(Context context) {
mCtx = context;
}
public static synchronized SharedPrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
public boolean userLogin(int id, String name, String email , String description){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_USER_ID, id);
editor.putString(KEY_USERNAME, name);
editor.putString(KEY_USER_EMAIL, email);
editor.putString(KEY_USER_DESCRIPTION, description);
editor.apply();
return true;
}
public boolean isLoggedIn(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
if(sharedPreferences.getString(KEY_USERNAME, null) != null){
return true;
}
return false;
}
public boolean logout(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
return true;
}
public String getUsername(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_USERNAME, null);
}
public String getUserEmail(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_USER_EMAIL, null);
}
public String getUserDesc(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_USER_DESCRIPTION, null);
}
}
This the User Updating Class.
public class EditProfile extends AppCompatActivity implements View.OnClickListener {
EditText name, description;
String email;
private ProgressDialog progressDialog;
Button update, delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
name = (EditText) findViewById(R.id.editText);
description = (EditText) findViewById(R.id.editDes);
update = (Button) findViewById(R.id.editUpdate);
delete = (Button) findViewById(R.id.DeletePro);
name.setText(SharedPrefManager.getInstance(this).getUsername());
description.setText(SharedPrefManager.getInstance(this).getUserDesc());
email = SharedPrefManager.getInstance(this).getUserEmail();
progressDialog = new ProgressDialog(this);
update.setOnClickListener(this);
delete.setOnClickListener(this);
}
private void updateUser() {
final String username = name.getText().toString().trim();
final String desc = description.getText().toString().trim();
if (username == "" || desc.length()>100) {
Toast.makeText(getApplicationContext(),"Invalid User Name or Description is exceeding thr limit",Toast.LENGTH_SHORT).show();
} else {
progressDialog.setMessage("Updating Information ...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_updatePro,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("name", username);
params.put("email", email);
params.put("description", desc);
return params;
}
};
RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
finish();
}
}
#Override
public void onClick(View v) {
if (v == update) {
updateUser();
}
if (v == delete)
{
startActivity(new Intent(EditProfile.this, DeleteProfile.class));
finish();
}
}
}

Check this link: Answered here
I showed a guy how to implement sharedPrefs, It's fairly simple to update the preferences and every time you re-initialize an activity or fragment your code should automatically retrieve whatever is stored in the SharedPrefs. That means that if you update the user's name in Activity A, when you load Activity B, it will fetch the sharedPrefs and find this new name (Assuming your getSharedPrefs code is within the onCreate or onResume method for your fragments/activities).
If you're not seeing the sharedPrefs info update within your activity, it may be because the activity is not refreshing (either because you haven't told it to, or because something has broken). You could try adding a 'refresh' button to the activity to test this, which would restart the activity, rather than logging out/in - which does the same thing as refreshing.

I think here u getting the update profile info.
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("name", username);
params.put("email", email);
params.put("description", desc);
name.setText(username);
description.setText(desc);
return params;
}
Hope this will work

Related

Android Studio SharedPrerefernces is not working another activity

I have created two activities SignUp and Login.
Also, I have SharedPreferences which get edittext value. When I call SharedPreferences(getNomre) inside onCreate It works but doesn't work as global variable. I want to declare a variable named mobileNomre for using put to Constant.mobile. How can I send Shared Preference value to Constant.mobile?
p.s: Acitivity code is too large. I noted some parts of them.
Thanks
SignUpActivity:
public void SignUpWithEmail(View view) {
if (!validateForm()) {
return;
}
showProgressDialog();
final String email = edtEmail.getText().toString();
final String password = edtPassword.getText().toString();
final String name = edtName.getText().toString();
final String mobile = edtMobile.getText().toString();
Session.setNomre(getApplicationContext(),"nomreler",mobile);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(name).build();
assert user != null;
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
}
}
});
sendEmailVerification();
} else {
hideProgressDialog();
try {
throw Objects.requireNonNull(task.getException());
} catch (FirebaseAuthInvalidCredentialsException | FirebaseAuthInvalidUserException | FirebaseAuthUserCollisionException invalidEmail) {
inputEmail.setError(invalidEmail.getMessage());
} catch (Exception e) {
e.printStackTrace();
inputEmail.setError(e.getMessage());
}
}
}
});
}
LoginActivity:
public class LoginActivity extends AppCompatActivity {
String TAG = "LoginActivity";
int RC_SIGN_IN = 9001;
CallbackManager mCallbackManager;
String token;
String mobileNomre = Session.getNomre(getApplicationContext(),"nomreler","");
public static FirebaseAuth mAuth;
GoogleSignInClient mGoogleSignInClient;
TextView tvPrivacy, tvTest;
ProgressDialog mProgressDialog;
public TextInputEditText edtEmail, edtPassword;
public TextInputLayout inputEmail, inputPass;
public void UserSignUpWithSocialMedia( final String mobileNomre,
final String fCode,
final String referCode,
final String name,
final String email,
final String profile,
final String type) {
StringRequest strReq = new StringRequest(Request.Method.POST, Constant.QUIZ_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
if (obj.getString("error").equals("false")) {
JSONObject jsonobj = obj.getJSONObject("data");
if (!jsonobj.getString(Constant.status).equals(Constant.DE_ACTIVE)) {
Session.saveUserDetail(getApplicationContext(),
jsonobj.getString(Constant.userId),
jsonobj.getString(Constant.name),
jsonobj.getString(Constant.email),
jsonobj.getString(Constant.mobile),
jsonobj.getString(Constant.PROFILE), referCode);
User user = new User(
jsonobj.getString(Constant.mobile),
jsonobj.getString(Constant.name),
jsonobj.getString(Constant.email),
"0",
false,
jsonobj.getString(Constant.PROFILE),
"0",
token,
jsonobj.getString(Constant.userId));
FirebaseDatabase.getInstance().getReference("user").child(FirebaseAuth.getInstance().
getCurrentUser().getUid()).setValue(user).
addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task1) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("type", "default");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
hideProgressDialog();
} else
setSnackBarStatus();
} else {
LoginManager.getInstance().logOut();
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(Constant.accessKey, Constant.accessKeyValue);
params.put(Constant.userSignUp, "1");
params.put(Constant.email, email);
params.put(Constant.name, name);
params.put(Constant.PROFILE, profile);
params.put(Constant.fcmId, token);
params.put(Constant.type, type);
params.put(Constant.mobile, mobileNomre );
params.put(Constant.REFER_CODE, referCode);
params.put(Constant.FRIENDS_CODE, fCode);
WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
params.put(Constant.ipAddress, ip);
System.out.println("---params social " + params.toString());
return params;
}
};
// AppController.getInstance().getRequestQueue().getCache().clear();
AppController.getInstance().addToRequestQueue(strReq);
}
SharedPrereferences:
public class Session {
public static void setNomre(Context mContext, String key, String objString) {
SharedPreferences.Editor editor =
mContext.getSharedPreferences(mContext.getString(R.string.app_name),
Context.MODE_PRIVATE).edit();
editor.putString(key, objString);
editor.commit();
}
public static String getNomre(Context mContext, final String key, final String defaultStr) {
SharedPreferences pref = mContext.getSharedPreferences(mContext.getString(R.string.app_name),
Context.MODE_PRIVATE);
return pref.getString(key, defaultStr);
}}
Make your String public static to access it globally;
public static String mobileNomre = Session.getNomre(getApplicationContext(),"nomreler","");
Haven't tried but working around with below code can give you an idea,
We uses this method if we want to access any function of Activity1 in Activity2..
AnotherActivity anotheractivity = (AnotherActivity) this.getActivity();

Store JWT token in shared preference? And retrieve value in whole app?

So far I made an app for my customer and now I integrate laravel API I don't understand the way how JWT tokens store in session and retrieve into other activities. Basically, on successful login API create JWT token and response I want to save it in session. I am able to retrieve the token from the JSON object in the result variable and I display it into logs but I don't find the way how I can store the token into session and then retrieve into all my app.
Below my code :
public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
String result;
#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);
// 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(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
}
/**
* 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,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(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);
//This is status api returned e.g 200 etc
Integer status = jObj.getInt("status");
//this is my token variable in this variable jwt is stored but how to store this variable in shared preferances.
String result = jObj.getString("result");
Log.d(TAG, "Login Response: " + status.toString());
Log.e(TAG,"Token "+result.toString());
if(status == 200) {
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
//intent.putExtra("full_name", name);
intent.putExtra("result", result.toString());
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();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, 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("email", email);
params.put("password", password);
//params.put("result", result);
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();
}
}
This is my shared preferences class code :
public class SessionManager {
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
// Shared Preferences
SharedPreferences pref;
Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "AndroidHiveLogin";
private static final String KEY_IS_LOGGED_IN = "isLoggedIn";
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_LOGGED_IN, isLoggedIn);
// commit changes
editor.commit();
Log.d(TAG, "User login session modified!");
}
public boolean isLoggedIn(){
return pref.getBoolean(KEY_IS_LOGGED_IN, false);
}
}
Add below methods in SessionManager class
//Save String data to Shared Prefs
public boolean saveStringData(String key, String value) {
SharedPreferences.Editor editor=mSharedPref.edit ();
editor.putString (key, value);
return editor.commit ();
}
public String getStringData(String key) {
String value=mSharedPref.getString (key, "");
return value;
}
Now on saving token call saveStringData method and pass a unique key (Remember on getting token this key will be used) and in value parameter pass token.
For getting token call getStringData method and pass that key which you passed when you saved token.
According to your query after adding above methods just write
1- For saving token :
session.saveStringData ("jwtToken", jObj.getString("result"));
2- For getting token anywhere in your application first initialize Session manager object and than call getStringData method like below.
private SessionManager session;
session = new SessionManager(getApplicationContext());
String token = session.getStringData("jwtToken");

java.lang.ClassCastException: Activity cannot be cast to MainActivity

I am trying to do a login session using Volley, PHP, MySQL but my login layout won't load. I do not know what is happening and in my logcat it says " java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.merylle.themoneyger/com.example.merylle.themoneyger.activity.LoginActivity}: java.lang.ClassCastException: com.example.merylle.themoneyger.activity.LoginActivity cannot be cast to com.example.merylle.themoneyger.activity.MainActivity"
which is cause by "Caused by: java.lang.ClassCastException: com.example.merylle.themoneyger.activity.LoginActivity cannot be cast to com.example.merylle.themoneyger.activity.MainActivity"
Can someone help me identify my error? Here's my code
SessionManager.java
public class SessionManager {
SharedPreferences sharedPreferences;
public SharedPreferences.Editor editor;
public Context context;
int PRIVATE_MODE=0;
private static final String PREF_NAME = "MONEYGER";
private static final String LOGIN = "IS_LOGIN";
public static final String FIRSTNAME = "NAME";
public static final String EMAIL = "EMAIL";
public static final String USERID = "USERID";
public SessionManager(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = sharedPreferences.edit();
}
public void createSession(String firstname, String email) {
editor.putBoolean(LOGIN, true);
editor.putString(FIRSTNAME, firstname);
editor.putString(EMAIL, email);
/*editor.putString(USERID, userid);*/
editor.apply();
}
public boolean isLoggin(){
return sharedPreferences.getBoolean(LOGIN, false);
}
public void checkLogin() {
if (!this.isLoggin()) {
Intent i = new Intent(context, LoginActivity.class);
context.startActivity(i);
((MainActivity)context).finish();
}
}
public HashMap<String, String> getUserDetail() {
HashMap<String, String> user = new HashMap<>();
user.put(FIRSTNAME, sharedPreferences.getString(FIRSTNAME, null));
user.put(EMAIL, sharedPreferences.getString(EMAIL, null));
/*user.put(USERID, sharedPreferences.getString(USERID, null));*/
return user;
}
public void logout() {
editor.clear();
editor.commit();
Intent i = new Intent(context, LoginActivity.class);
context.startActivity(i);
((MainActivity)context).finish();
}
}
LoginActivity.java
public class LoginActivity extends Activity {
TextView title;
Typeface marcellus;
private EditText emailuser, passworduser;
TextView forgot;
private Button login, register;
private ProgressBar progressBar;
private static String HttpURL = "http://10.0.2.2:63343/TheMoneyger/api/user-login.php?";
SessionManager sessionManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sessionManager = new SessionManager(this);
sessionManager.checkLogin();
title = (TextView) findViewById(R.id.txtTitle);
marcellus = Typeface.createFromAsset(getAssets(), "marcellus.ttf");
title.setTypeface(marcellus);
emailuser = (EditText) findViewById(R.id.txtEmail);
passworduser = (EditText) findViewById(R.id.txtPassword);
login = (Button) findViewById(R.id.btnLogin);
forgot = (TextView) findViewById(R.id.txtForgotPW);
register = (Button) findViewById(R.id.btnRegister);
progressBar = (ProgressBar)findViewById(R.id.progressBar3);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String mEmail = emailuser.getText().toString().trim();
String mPass = passworduser.getText().toString().trim();
if(!mEmail.isEmpty() || !mPass.isEmpty()) {
Login(mEmail, mPass);
}
else {
emailuser.setError("Please insert email");
passworduser.setError("Please insert password");
}
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registration = new Intent(LoginActivity.this, RegistrationActivity.class);
startActivity(registration);
}
});
forgot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent forgot = new Intent(LoginActivity.this, ForgotPassword.class);
startActivity(forgot);
}
});
}
private void Login(final String emailuser, final String passworduser) {
progressBar.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("login");
if (success.equals("1")) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String firstname = object.getString("firstname").trim();
String email = object.getString("email").trim();
String id = object.getString("userid").trim();
sessionManager.createSession(firstname, email);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("firstname", firstname);
intent.putExtra("email", email);
startActivity(intent);
finish();
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(LoginActivity.this, "Something went wrong.. " + e.toString(), Toast.LENGTH_SHORT).show();
login.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Something went wrong.. " + error.toString(), Toast.LENGTH_SHORT).show();
login.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", emailuser);
params.put("password", passworduser);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Home2.java
public class Home2 extends Fragment {
private TextView profileName, profileEmail;
CardView cv1, cv2, cv3, cv4, cv5, cv6;
SessionManager sessionManager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
sessionManager = new SessionManager(getActivity().getApplicationContext());
sessionManager.checkLogin();
cv1 = (CardView)view.findViewById(R.id.cv1); //settings
cv2 = (CardView)view.findViewById(R.id.cv2); //profile
cv3 = (CardView)view.findViewById(R.id.cv3); //expenses summary
cv4 = (CardView)view.findViewById(R.id.cv4); //budget summary
cv5 = (CardView)view.findViewById(R.id.cv5); //report
cv6 = (CardView)view.findViewById(R.id.cv6); //logout
profileName = (TextView)view.findViewById(R.id.txtProfileName); //display profilename
profileEmail = (TextView)view.findViewById(R.id.txtProfileEmail); //display profileemail
HashMap<String, String> user = sessionManager.getUserDetail();
String mName = user.get(sessionManager.FIRSTNAME);
String mEmail = user.get(sessionManager.EMAIL);
profileName.setText(mName);
profileEmail.setText(mEmail);
return view;
}
}
user-login.php
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email = $_POST['email'];
$password = $_POST['password'];
require_once 'config.php';
$sql = "SELECT * FROM users WHERE email='$username'";
$response = mysqli_query($db, $sql);
$result = array();
$result['login'] = array();
if ( mysqli_num_rows($response) === 1 ) {
$row = mysqli_fetch_assoc($response);
if ( password_verify($password, $row['password']) ) {
$index['firstname'] = $row['firstname'];
$index['email'] = $row['email'];
array_push($result['login'], $index);
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
mysqli_close($db);
} else {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
mysqli_close($db);
}
}
}
?>
You have initialized sessionManager with LoginActivity's context:
sessionManager = new SessionManager(this);
and then inside SessionManager class you use this:
((MainActivity)context).finish();
which throws the error.
You can't cast LoginActivity's context to MainActivity.
Change to this:
((LoginActivity)context).finish();
After all it is LoginActivity you want to finish isn't it?

Button works on Second Click in android

I am using cloud Firestore as database, when I am clicking on login button, it is not updating the value at first but on second click it updates.
When I click on Login, at first it takes empty values, but on second click it takes the value entered. Same happens when I change text and press login again, it takes previous values and on second click it takes updated values.
public class LoginActivity extends AppCompatActivity {
private TextView appName;
private TextInputEditText registrationNumber;
private TextInputEditText password;
private User userSent;
private FirebaseFirestore db;
private CollectionReference collectionReference;
String result="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
db = FirebaseFirestore.getInstance();
db.enableNetwork();
collectionReference = db.collection("/user");
registrationNumber = findViewById(R.id.regno);
password = findViewById(R.id.password);
userSent = new User();
appName = findViewById(R.id.appname);
AssetManager assetManager = getApplicationContext().getAssets();
Typeface typeface = Typeface.createFromAsset(assetManager,"fonts/Ubuntu-Regular.ttf");
appName.setTypeface(typeface);
}
public void onLogin(View view){
userSent.setRegistrationNumber(registrationNumber.getText().toString());
userSent.setPassword(password.getText().toString());
if(!userSent.getRegistrationNumber().isEmpty() && !userSent.getPassword().isEmpty()) {
authenticateUser(userSent);
}
else{
Toast.makeText(this, "Registration Number or Password cannot be empty", Toast.LENGTH_LONG).show();
}
//Login Result
Log.d("Login Result: " , result);
if(result.contains("success")) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
else if(result.length()>0){
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
}
}
public void authenticateUser(final User sUser){
final String registration_number = sUser.getRegistrationNumber();
final String password = sUser.getPassword();
collectionReference.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for(QueryDocumentSnapshot queryDocumentSnapshot: queryDocumentSnapshots){
Map<String, Object> map;
map = queryDocumentSnapshot.getData();
String reg_no = (String) map.get("registration_number");
String pass = (String)map.get("password");
if(registration_number.equals(reg_no) && password.equals(pass)){
result = "success";
return;
}
else if(registration_number.equals(reg_no)){
result = "Incorrect Password";
return;
}
else{
result = "User does not exist";
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
result = "Error Connecting to Server";
}
});
}
}

SharedPreferences doesn't seem to save the variables

I have a class that implements the SharedPreferences but whenever I try to save the data or get the data it does not seem to do it.
public class SharedPreferenceManager {
public SharedPreferenceManager() {
super();
}
public static final String FILENAME = "PREFERENCES_FILE";
public static void saveData(Context context, String key, String data)
{
SharedPreferences sharedPreferences = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, data);
editor.apply();
}
public static String getData(Context context, String key){
SharedPreferences sharedPreferences = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
String data = sharedPreferences.getString(key, null);
return data;
}
public static void removeData(Context context, String key){
SharedPreferences sharedPreferences = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(key);
}
}
This is where I save the Data:
public class CreateUserActivity extends Activity {
EditText txtName, txtEmail, txtPassword;
AlertDialogManager alert = new AlertDialogManager();
private String token;
private SharedPreferenceManager sharedPreferenceManager;
public void setToken(String token) {
this.token = token;
}
public String getToken() {
return token;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_user_activity);
txtName = (EditText) findViewById(R.id.loginName);
txtEmail = (EditText) findViewById(R.id.loginEmail);
txtPassword = (EditText) findViewById(R.id.loginPassword);
sharedPreferenceManager = new SharedPreferenceManager();
}
public void checkCreateUser(View view) throws JSONException {
String name = txtName.getText().toString();
String email = txtEmail.getText().toString();
String password = txtPassword.getText().toString();
String token = getToken();
CheckBox checkBox = (CheckBox) findViewById(R.id.login_remember_checkbox);
if (name.trim().length() > 0 && password.trim().length() > 0 && email.trim().length() > 0) {
JSONObject userObj = new JSONObject();
userObj.put("name", name);
userObj.put("email", email);
userObj.put("password", password);
String jsonDocument = userObj.toString();
PostUserTask put = new PostUserTask();
put.execute("http://api.evang.dk/v2/users", jsonDocument);
if (checkBox.isChecked()) {
sharedPreferenceManager.saveData(CreateUserActivity.this, "USERNAME", name);
sharedPreferenceManager.saveData(CreateUserActivity.this, "EMAIL", email);
sharedPreferenceManager.saveData(CreateUserActivity.this, "PASSWORD", password);
sharedPreferenceManager.saveData(CreateUserActivity.this, "TOKEN", token);
} else {
sharedPreferenceManager.removeData(CreateUserActivity.this, "USERNAME");
sharedPreferenceManager.removeData(CreateUserActivity.this, "EMAIL");
sharedPreferenceManager.removeData(CreateUserActivity.this, "PASSWORD");
sharedPreferenceManager.removeData(CreateUserActivity.this, "TOKEN");
}
}
else
{
alert.showAlertDialog(CreateUserActivity.this, "Login failed!", "Please enter name, username and password", false);
}
Intent i = new Intent(getBaseContext(), UserActivity.class);
i.putExtra("SESSIONID", token);
i.putExtra("NAMEID", name);
startActivity(i);
}
And where I read the data of the SharedPreferences:
EditText userNameTxt, passwordTxt, emailTxt;
SharedPreferenceManager sharedPreferenceManager;
String token;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Intent intent = getIntent();
userNameTxt = (EditText) findViewById(R.id.userNameLogin);
passwordTxt = (EditText) findViewById(R.id.passwordLogin);
emailTxt = (EditText) findViewById(R.id.emailLogin);
sharedPreferenceManager = new SharedPreferenceManager();
String userName = sharedPreferenceManager.getData(getBaseContext(), "USERNAME");
String email = sharedPreferenceManager.getData(getBaseContext(), "EMAIL");
String password = sharedPreferenceManager.getData(getBaseContext(), "PASSWORD");
token = sharedPreferenceManager.getData(getBaseContext(), "TOKEN");
if(userName != null && email != null && password != null && token != null)
{
userNameTxt.setText(userName);
emailTxt.setText(email);
passwordTxt.setText(password);
}
}
since in saveData(...), you use editor.apply() and not editor.commit(), it's possible your data hasn't been written to file before you're reading it. (editor.apply() is asynchronous and doesn't write changes to disk immediately unlike editor.commit())
Try using editor.commit() instead, like this:
public static void saveData(Context context, String key, String data)
{
SharedPreferences sharedPreferences = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, data);
editor.commit();
}

Categories