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();
Related
how can I get the result of a StringRequest or JsonObjectRequest back to the class where I called the method.
In my MainActivty I have a Login Button. When I press it, it Calls the function checkLogin with a StingRequest from my Backgroundworker.class. How can I get the response back to my MainActivity to process it or Display it?
I can’t use a return at the end of the method because its asynchrony. I tried calling a method in my MainActivity but I always get an error when reaching the Intent
2019-05-16 16:43:52.794 3158-3158/com.test.Test E/Error: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
What’s the proper way to do a login function like this?
-MainActivity
package com.test.Test;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.test.Test.tools.BackgroundWorker;
public class MainActivity extends AppCompatActivity {
private EditText txtEditUser;
private EditText txtEditPw;
private Button btnLogin;
private Button btnRegister;
private TextView txtViewLoginfailed;
private String user;
private String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtEditUser = findViewById(R.id.txtEditUser);
txtEditPw = findViewById(R.id.txtEditPw);
btnLogin = findViewById(R.id.btnLogin);
btnRegister = findViewById(R.id.btnRegister);
txtViewLoginfailed = findViewById(R.id.txtViewLoginfailed);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user = txtEditUser.getText().toString();
password = txtEditPw.getText().toString();
new BackgroundWorker().checkLogin(user, password, getApplicationContext());
}
});
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent register = new Intent(getApplicationContext(), Register.class);
startActivity(register);
}
});
}
public void Login(Boolean LoginOK,Context context) {
if (LoginOK) {
Intent menu = new Intent(context, Menu.class);
startActivity(menu);
} else {
txtViewLoginfailed.setText("Login failed");
}
}
}
-Backgroundworker
public class BackgroundWorker {
private Boolean LoginOK;
public void checkLogin(final String user, final String password, final Context context) {
String url = "http://192.168.0.2:80/webapp/login.php";
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.d("testLogin", "3");
if (response.equals("login success")) {
LoginOK = true;
new MainActivity().Login(LoginOK, context);
} else {
Log.d("testLogin", "5");
}
} catch (Exception exc) {
exc.printStackTrace();
Log.e("Error", exc.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", error.getMessage());
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_name", user);
params.put("password", password);
return params;
}
};
queue.add(sr);
}
}
What you need is Callback interface.
Create new interface e.g. LoginRequestCallback:
public interface LoginRequestCallback {
void onLoginRequestSuccess();
void onLoginRequestError(String errorMessage);
}
In your checkLogin method add new parameter LoginRequestCallback callback:
public void checkLogin(final String user, final String password, final Context context, LoginRequestCallback callback) { ... }
And then call method corresponding to either success of login or to the error:
public void checkLogin(final String user, final String password, final Context context) {
String url = "http://192.168.0.2:80/webapp/login.php";
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.d("testLogin", "3");
if (response.equals("login success")) {
callback.onLoginRequestSuccess();
} else {
callback.onLoginRequestError("Invalid credentials");
}
} catch (Exception exc) {
exc.printStackTrace();
Log.e("Error", exc.getMessage());
callback.onLoginRequestError(exc.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", error.getMessage());
callback.onLoginRequestError(exc.getMessage());
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_name", user);
params.put("password", password);
return params;
}
};
queue.add(sr);
}
When calling from MainActivity, make MainActivity class implement this interface:
public class MainActivity extends Activity implements LoginRequestCallback {
//...
#Override
public void onLoginRequestSuccess() {
}
#Override
public void onLoginRequestError(String errorMessage) {
}
}
And when you call this method, pass this as callback:
void onLoginButtonClicked(View v) {
String user = "Asd";
String password = "asdasd";
this.backgroundWorker.checkLogin(user, password, this, this);
}
#Override
public void onLoginRequestSuccess() {
this.Login(true, this);
}
#Override
public void onLoginRequestError(String errorMessage) {
Toast.makeText(this, errorMessage, Toast.SHORT).show();
}
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?
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";
}
});
}
}
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
I am getting error in
final EditText etregpassword = (EditText)findViewById(R.id.etregpassword);
I would like help with the comparison of password and confirm password and to display the error in password mismatch.
public class RegisterActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etregname = (EditText)findViewById(R.id.etregname);
final EditText etregemailid = (EditText)findViewById(R.id.etregemailid);
final EditText etregpassword = (EditText)findViewById(R.id.etregpassword);
final EditText etconfirmregpassword = (EditText)findViewById(R.id.etconfirmregpassword);
final Button regbutton = (Button) findViewById(R.id.regbutton);
regbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String User_name = etregname.getText().toString();
final String Email_id = etregemailid.getText().toString();
final String Password = etregpassword.getText().toString();
final String Confirm_password = etconfirmregpassword.getText().toString();
Response.Listener<String> responseListner = new Response.Listener<String>(){
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean SUCCESS = jsonObject.getBoolean("success");
if(SUCCESS){
Intent intent = new Intent(RegisterActivity.this,LoginActivity.class);
RegisterActivity.this.startActivity(intent);
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(User_name,Email_id,Password,Confirm_password,responseListner);
RequestQueue queue= Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
Just compare those values:
final String password = etregpassword.getText().toString();
final String confirmPassword = etconfirmregpassword.getText().toString();
if (!TextUtils.isEmpty(password) && !TextUtils.isEmpty(confirmPassword))
{
if(password.equals(confirmPassword))
{
//are equal
}
else {
//are different
}
}