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();
}
Related
I'm developing a basic android application with just a login page and a home page, where on the home page consists of the WebView in it.
What I'm doing here is I'm trying to save the login details(username and password) with the help of shared preferences in the login page and retrieve those on the home page through the localStorage of the WebView.
This is how I'm saving my login credentials in the login page through shared preferences
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
usernameEdit = findViewById(R.id.et_login_email);
passwordEdit = findViewById(R.id.et_login_pass);
private void loginActivity(){
String username = usernameEdit.getText().toString().trim();
String password = passwordEdit.getText().toString().trim();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(KEY_USERNAME, username);
editor.putString(KEY_PASSWORD, password);
editor.commit();
startActivity(new Intent(LoginActivity.this, HomePage.class));
}
ANd this is my homepage where I'm using the LocalStorage in the WebView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
Window window = HomePage.this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(ContextCompat.getColor(HomePage.this, R.color.colorPrimary));
}
swipeRefreshLayout = findViewById(R.id.swipelayout);
myWebView = findViewById(R.id.webview);
WebSettings settings = myWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDatabasePath("/data/data/" + this.getPackageName() + "/databases/");
settings.setDomStorageEnabled(true);
myWebView.setWebChromeClient(new WebChromeClient(){
#Override
public void onConsoleMessage(String message, int lineNumber, String sourceID) {
Log.d("WebView", "Line: " + lineNumber + "," + message);
}
#Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
return false;
}
});
myWebView.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
myWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(HomePage.this, "WebView Example", "Loading...");
myWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
if (url.equals("https://www.codecell.in/jkdapp") == true){
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String username = preferences.getString(KEY_USERNAME, "");
String password = preferences.getString(KEY_PASSWORD, "");
if (username == null || password == null) {
return;
}
view.loadUrl("javascript:fillvalues(" + username + "," + password + ");");
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(HomePage.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.show();
}
});
myWebView.addJavascriptInterface(new JavascriptInterface(), "Android");
myWebView.loadUrl("https://www.codecell.in/jkdapp");
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
myWebView.reload();
}
});
}
private class JavascriptInterface{
public void saveValues(String name, String pass){
if (name == null || pass == null){
return;
}
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString(KEY_USERNAME, name);
editor.putString(KEY_PASSWORD, pass);
editor.apply();
}
}
public class StoreManager {
private SharedPreferences.Editor editor;
private Context _context;
public SharedPreferences pref;
private int PRIVATE_MODE = 0;
private static final String PREF_NAME = "_store";
public StoreManager(Context _context) {
this._context = _context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setToken(String Token) {
editor.putString("Token", Token);
System.out.println("token saved" + " " + Token);
editor.commit();
}
public String getToken() {
return pref.getString("Token", "");
}
}
I saved my data as tring in shared pref like this and when you login get data from there and call setToken of shared pref
StoreManager storeManager = new StoreManager(getApplicationContext());
storeManager.setToken("Your Username here");
and you can get data in same way by simply calling
StoreManager storeManager = new StoreManager(getApplicationContext());
storeManager.getToken();
I want to create login activity with multiple types of user. This login is connected with MySQL. The multiple choice is "Reviewer" and "Non-Reviewer". Now I use Spinner and the values I call from string.xml. At the table 'user', there are some column such as 'username', 'password', and 'usertype'. Example, user 'peter' is a "Reviewer", he will able to login if user name, password and user type that he uses is correct. How can i solve this problem? Below is my code.
//login activity
public class MainActivity extends AppCompatActivity{
private static final String KEY_USERNAME = "username";
private static final String LOGIN_URL = "http://lienawan.xyz/login.php";
private SharedPreferences.Editor loginPrefsEditor;
private EditText etEmail;
private EditText etPassword;
private CheckBox chkMe;
ArrayAdapter<CharSequence> adapter;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
Objects.requireNonNull(getSupportActionBar()).hide(); // hide the title ba
setContentView(R.layout.activity_main);
etEmail = findViewById(R.id.etEmail);
etPassword = findViewById(R.id.etPassword);
chkMe = findViewById(R.id.chkMe);
SharedPreferences loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
boolean saveLogin = loginPreferences.getBoolean("saveLogin", false);
if (saveLogin) {
etEmail.setText(loginPreferences.getString("username", ""));
etPassword.setText(loginPreferences.getString("password", ""));
chkMe.setChecked(true);
}
Spinner spCategory = findViewById(R.id.spCategory);
adapter = ArrayAdapter.createFromResource(this,R.array.usertype,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCategory.setAdapter(adapter);
spCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Button btnLogin = findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(etEmail.getWindowToken(), 0);
String username = etEmail.getText().toString();
String password = etPassword.getText().toString();
if (chkMe.isChecked()) {
loginPrefsEditor.putBoolean("saveLogin", true);
loginPrefsEditor.putString("username", username);
loginPrefsEditor.putString("password", password);
loginPrefsEditor.apply();
} else {
loginPrefsEditor.clear();
loginPrefsEditor.commit();
}
}
});
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Exit");
builder.setMessage("Do you want to exit?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
}
private void login() {
String username = etEmail.getText().toString().trim();
String password = etPassword.getText().toString().trim();
userLogin(username, password);
}
private void userLogin(final String username, final String password){
class UserLoginClass extends AsyncTask<String,Void,String> {
private ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Login... Please Wait",null,true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(MainActivity.this,DashboardApp.class);
intent.putExtra(KEY_USERNAME,username);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this,s, Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
HashMap<String,String> data = new HashMap<>();
data.put("username",params[0]);
data.put("password",params[1]);
Connection ruc = new Connection();
String result = ruc.sendPostRequest(LOGIN_URL,data);
return result;
}
}
UserLoginClass ulc = new UserLoginClass();
ulc.execute(username, password);
}
}
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$username = $_POST['username'];
$password = $_POST['password'];
$approver = $_POST['approver'];
require_once('dbConnect.php');
$sql = "select * from user where username='$username' and password='$password'";
$check = mysqli_fetch_array(mysqli_query($con,$sql));
if(isset($check)){
echo "success";
}else{
echo "Invalid Username or Password";
}
}else{
echo "error try again";
To get selected value from spinner you write below code in onItemSelected :
String item;//declare globally out of your all method
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
Now,check if item and other value are not null , like below :
private void login() {
String username = etEmail.getText().toString().trim();
String password = etPassword.getText().toString().trim();
//checking if fields are not null
if (username.isEmpty() || password.isEmpty() || item.isEmpty()) {
Toast.makeText(getActivity().getApplicationContext(), "Please enter name or pass or select one type!", Toast.LENGTH_SHORT).show();
return;
}else{
userLogin(username, password,item);//passing value to volley
}
}
And in your volley request change like below :
private void userLogin(final String username, final String password,final String item){
...
#Override
protected String doInBackground(String... params) {
HashMap<String,String> data = new HashMap<>();
data.put("username",params[0]);
data.put("password",params[1]);
data.put("approver",params[2]);//adding item value
..
}
}
}
At your php side just change your query to :
$sql = "select * from user where username='$username' and password='$password' and usertype='$approver'";
Hope this helps you !
Note : Also never used plain-text password and try using prepared statement it is safe an secure.
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 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
}
}