I want to implement a password change activity in my application, and here is the code which I've written for my activity, but I think that I should declare the String Password variable to somewhere else, because my new password changes successfully and works until I close the application,and when I run it again the old password is the right one.I'm really new to Android development, any answers/suggestions will be appreciated.
Change_Password code:
public class Change_Password extends Activity {
//----
public SharedPreferences prefs;
private String prefName = "MyPref";
private static final String TEXT_VALUE_KEY = "nothing";
//-----
public static String Password="soha";
public static String getPassword()
{
return Password;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.change_password);
Button btnCancel=(Button)findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
finish();
}
});
final EditText txtNewPassword=(EditText)findViewById(R.id.txtNewPassword);
final EditText txtCurrentPassword=(EditText)findViewById(R.id.txtCurrentPassword);
final EditText txtConfirmPassword=(EditText)findViewById(R.id.txtConfirmNewPassword);
Button btnSave=(Button)findViewById(R.id.btnSave);
btnSave.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(txtConfirmPassword.getText().toString().equalsIgnoreCase("") |
txtCurrentPassword.getText().toString().equalsIgnoreCase("") |
txtCurrentPassword.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getBaseContext(),"Please Complete the Information", Toast.LENGTH_SHORT).show();
}
else
if(!txtNewPassword.getText().toString().equalsIgnoreCase(txtConfirmPassword.getText().toString()))
{
Toast.makeText(getBaseContext(),
"These Passwords Don't Match !", Toast.LENGTH_SHORT).show();
}
else
if(!getPassword().equalsIgnoreCase(txtCurrentPassword.getText().toString()))
{
Toast.makeText(getBaseContext(),
"Current Password is Incorrect!", Toast.LENGTH_SHORT).show();
}
else
{
///------- //---save the values in the EditText view to preferences---
prefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(TEXT_VALUE_KEY, txtNewPassword.getText().toString());
//---saves the values---
editor.commit();
///--------
//Password=txtNewPassword.getText().toString();
Toast.makeText(getBaseContext(),
Password, Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_HOME)
BackToMainIntent();
else if(keyCode==KeyEvent.KEYCODE_BACK)
{
BackToMainIntent();
}
return false;
}
public void BackToMainIntent()
{
Intent intent = new Intent(this, Main.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
And Here my main activity:
public class mainC extends Activity {
private EditText uPass;
private Button loginBtn;
private Button Btn_Exit;
private ImageView Image;
///------
public SharedPreferences prefs;
private String prefName = "MyPref";
private static final String TEXT_VALUE_KEY = "1234";
////----------
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginpage);
Image=(ImageView)findViewById(R.id.NFCImage);
Image.setAlpha(100);
Btn_Exit=(Button)this.findViewById(R.id.Btn_exit_app);
Btn_Exit.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent _Intent =new Intent(Intent.ACTION_MAIN);
_Intent.addCategory(Intent.CATEGORY_HOME);
_Intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(_Intent);
}
});
setUpViews();
}
#Override
protected void onResume() {
super.onResume();
uPass.setText("");
uPass.setInputType(InputType.TYPE_CLASS_TEXT| InputType.TYPE_TEXT_VARIATION_PASSWORD);
uPass.setTextColor(Color.parseColor("#888888"));
}
private void setUpViews() {
uPass=(EditText)findViewById(R.id.usrPassTxt);
uPass.setOnFocusChangeListener(new View.OnFocusChangeListener(){
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
uPass.setInputType(InputType.TYPE_CLASS_TEXT| InputType.TYPE_TEXT_VARIATION_PASSWORD);
uPass.setText("");
}
}
});
loginBtn=(Button)findViewById(R.id.Btn_Login);
loginBtn.setOnClickListener(new OnClickListener() {
private String pass;
Intent myIntent;
public void onClick(View v) {
pass=uPass.getText().toString();
///-----
SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
String passtemp = prefs.getString(TEXT_VALUE_KEY, "nothing");
if( pass.equalsIgnoreCase(passtemp))
///-----
//if( pass.equalsIgnoreCase(Change_Password.getPassword()))
{
myIntent=new Intent(mainC.this,Main.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
System.out.println("---IF---");
}
else{
myIntent=new Intent(mainC.this,ErrorPage.class);
System.out.println("---ELSE---");
}
startActivity(myIntent);
}
});
}
#Override
public void onBackPressed() {
finish();
}
}
The problem here is that your are running all in memory, I mean, you have your Password variable (static) in memory, you assigned it when the password is changed and its ok.
But when you start the appliccation again, the value of password is 1234 because you have code it! xD, you have to store de password somewhere else, for example using SharedPreferences.
Here
if( pass.equalsIgnoreCase(Change_Password.getPassword()))
you are trying to call a method from previous Activity which is not valid way fro sharing data between Activities or Other Components of Application .
In your case, you can use SharedPreferences for Storing password instead of using static fields or methods
see these tutorials of we use SharedPreferences in our application :
http://developer.android.com/guide/topics/data/data-storage.html
http://saigeethamn.blogspot.in/2009/10/shared-preferences-android-developer.html
http://android-er.blogspot.in/2011/01/example-of-using-sharedpreferencesedito.html
Related
I have an app that has 3 activities:
MessagesActivity
LoginActivity
RegisterActivity
The LoginActivity contains 2 EditTexts and a CheckBox that keeps the user signed in. And of course 2 Buttons: one for signing in and the other for registering an account.
I have added an intent in the LoginActivity so when logged in, the MessagesActivity is shown. And another intent in the MessagesActivity for when reading from SharedPreferences if the CheckBox is not checked, switching to LoginActivity.
The problem is that I don't know how to do that. I'm still new to SharedPreferences. And even when logging in and the inputs are true, the app doesn't switch to MessagesActivity. It shows the LoginActivity again.
I want help in that please if anyone know how to do it.
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
private EditText registerUsername;
private EditText registerEmail;
private EditText registerPassword;
private EditText registerConfirmPassword;
private Button registerRegisterButton;
private Button registerLoginButton;
private ProgressBar registerProgressBar;
private FirebaseFirestore firebaseFirestore;
private String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
registerUsername = findViewById(R.id.register_username);
registerEmail = findViewById(R.id.register_email);
registerPassword = findViewById(R.id.register_password);
registerConfirmPassword = findViewById(R.id.register_confirm_password);
registerRegisterButton = findViewById(R.id.register_register_button);
registerLoginButton = findViewById(R.id.register_login_button);
registerProgressBar = findViewById(R.id.register_progressBar);
firebaseFirestore = FirebaseFirestore.getInstance();
registerLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent loginIntent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
}
});
registerRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = registerUsername.getText().toString();
String email = registerEmail.getText().toString();
String password = registerPassword.getText().toString();
String confirmPassword = registerConfirmPassword.getText().toString();
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(email) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(confirmPassword)) {
if (password.equals(confirmPassword)) {
registerProgressBar.setVisibility(View.VISIBLE);
Map<String, String> usersMap = new HashMap<>();
usersMap.put("username", username);
usersMap.put("email", email);
usersMap.put("password", password);
userID = registerUsername.getText().toString();
firebaseFirestore.collection("Users").document(userID).set(usersMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toasty.success(RegisterActivity.this, "Successfully Registered", Toast.LENGTH_SHORT).show();
Intent messagesIntent = new Intent(RegisterActivity.this, MessagesActivity.class);
startActivity(messagesIntent);
finish();
registerProgressBar.setVisibility(View.INVISIBLE);
}
});
} else {
Toasty.error(RegisterActivity.this, "Passwords Don't Match", Toast.LENGTH_SHORT).show();
}
}
}
});
}}
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
private EditText loginUsername;
private EditText loginPassword;
private CheckBox loginKeepSignedIn;
private Button loginLoginButton;
private Button loginRegisterButton;
private ProgressBar loginProgressBar;
private FirebaseFirestore firebaseFirestore;
private String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginUsername = findViewById(R.id.login_username);
loginPassword = findViewById(R.id.login_password);
loginKeepSignedIn = findViewById(R.id.login_keep_signed_in);
loginLoginButton = findViewById(R.id.login_login_button);
loginRegisterButton = findViewById(R.id.login_register_button);
loginProgressBar = findViewById(R.id.login_progressBar);
firebaseFirestore = FirebaseFirestore.getInstance();
if (loginKeepSignedIn.isChecked()) {
SharedPreferences preferences = getSharedPreferences("Preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("keepSignedIn", true);
editor.apply();
}
loginRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(registerIntent);
finish();
}
});
loginLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String username = loginUsername.getText().toString();
final String password = loginPassword.getText().toString();
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
loginProgressBar.setVisibility(View.VISIBLE);
userID = loginUsername.getText().toString();
firebaseFirestore.collection("Users").document(userID).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
String userUsername = task.getResult().getString("username");
String userPassword = task.getResult().getString("password");
if (userUsername.equals(username) && userPassword.equals(password)) {
Toast.makeText(LoginActivity.this, "Everything is equal", Toast.LENGTH_SHORT).show();
Toasty.info(LoginActivity.this, "Switching to Messages Activity", Toast.LENGTH_SHORT).show();
Intent messagesIntent = new Intent(LoginActivity.this, MessagesActivity.class);
startActivity(messagesIntent);
LoginActivity.this.finish();
} else {
Toast.makeText(LoginActivity.this, "There is something not equal", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Task is not successful",Toast.LENGTH_SHORT).show();
}
loginProgressBar.setVisibility(View.INVISIBLE);
}
});
}
}
});
}}
MessagesActivity.java
public class MessagesActivity extends AppCompatActivity {
private Toolbar messagesToolbar;
private Button logoutBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
messagesToolbar = findViewById(R.id.messages_toolbar);
setSupportActionBar(messagesToolbar);
getSupportActionBar().setTitle("Messages");
logoutBtn = findViewById(R.id.logout);
SharedPreferences preferences = getSharedPreferences("Preferences", MODE_PRIVATE);
boolean keepSignedIn = preferences.getBoolean("keepSignedIn", false);
if (!keepSignedIn) {
Intent loginIntent = new Intent(MessagesActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
}
logoutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent loginIntent = new Intent(MessagesActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
}
});
}
}
Well you just need to create an instance of SharedPreferences and store the value you need. It can either be a boolean , String e.t.c. Also you can store the preferences in a .xml file with a name you choose or let the system choose a name for you.
Use this piece of code to learn.
public class PrefsExample extends AppCompatActivity {
final String sharedPreferencesName = "chosenName";
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
//this allows the system to create a system wide sharedprefs file
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//this uses the name provided as the string above
//sharedPreferences = this.getSharedPreferences(sharedPreferencesName, MODE_PRIVATE);
//save the value(s) using
editor = sharedPreferences.edit();
editor.putBoolean("Logged", true);
editor.putString("Log In", "True");
editor.putInt("LoggedIn", 1);
//try out more options of the editor
//after editing,always apply to save
editor.apply();
//for read operations
readPrefs();
super.onCreate(savedInstanceState);
}
public void readPrefs() {
//again use this if only your prefs are system wide
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//and this if using a specified name
//sharedPreferences = this.getSharedPreferences(sharedPreferencesName, MODE_PRIVATE);
//retrieve your value using
String pref = sharedPreferences.getString("Log In","");
//use the get method of SharedPreferences to get but supply a default value eg for string "",for int 0,for boolean false e.t.c
//from here use a loop to check if values retrieved and values stored match and decide on which activity to proceed to from there
}}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm using Model View Presenter in my application, and i try to save a value token in SharedPreferences. But, I got the SharedPreferences null, the error is SharedPreferences.edit() is a null object references. Please, help me to solve this. Thank you
This is my Fragment
public class SignUpFragment extends BaseFragment {
#NotEmpty(messageResId = R.string.rules_no_empty)
#Bind(R.id.Name)
EditText etName;
#NotEmpty(messageResId = R.string.rules_no_empty)
#Bind(R.id.email)
EditText etEmail;
#NotEmpty(messageResId = R.string.rules_no_empty)
#Bind(R.id.phone)
EditText etPhone;
#Bind(R.id.btnSignUp)
Button btnSignUp;
public static final String TAG = SignUpFragment.class.getSimpleName();
private SignUpPresenter presenter;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
public static void showFragment(BaseActivity sourceActivity) {
if (!sourceActivity.isFragmentNotNull(TAG)) {
FragmentTransaction fragmentTransaction = sourceActivity.getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_question, new SignUpFragment(), TAG);
fragmentTransaction.commit();
}
}
#Override
protected int getLayout() {
return R.layout.activity_sign_up;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
presenter = new SignUpPresenter(this);
sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initview();
}
#Override
public void onResume() {
super.onResume();
}
private void initview (){
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!validate()) {
onSignupFailed();
return;
} else {
presenter.signup();
}
}
});
}
#Override
public void onValidationSucceeded() {
super.onValidationSucceeded();
presenter.signup();
}
public void onSignupFailed() {
Toast.makeText(getContext(), "Login failed", Toast.LENGTH_LONG).show();
btnSignUp.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String name = etName.getText().toString();
String email = etEmail.getText().toString();
String password = etPhone.getText().toString();
if (name.isEmpty() || name.length() < 3) {
etName.setError("at least 3 characters");
valid = false;
} else {
etName.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
etEmail.setError("enter a valid email address");
valid = false;
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
etPhone.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
etPhone.setError(null);
}
return valid;
}
public void gotoQuestionActivity(String email, String name, String phone) {
QuestionActivity.startActivity((BaseActivity) getActivity(), email, name, phone);
getActivity().finish();
}
}
and this my Presenter
public class SignUpPresenter {
private SignUpFragment fragment;
public String token = "token";
SharedPreferences sharedpreferences;
private Context mContext;
public static final String MyPREFERENCES = "MyPrefs" ;
public SignUpPresenter(SignUpFragment fragment) {
this.fragment = fragment;
}
public SignUpRequest constructSignUpRequest() {
SignUpRequest request = new SignUpRequest();
request.setName(getAndTrimValueFromEditText(fragment.etName));
request.setEmail(getAndTrimValueFromEditText(fragment.etEmail));
request.setMobile(getAndTrimValueFromEditText(fragment.etPhone));
return request;
}
private String getAndTrimValueFromEditText(EditText e) {
return e.getText().toString().trim();
}
public SharedPreferences getSharedPreferences() {
return sharedpreferences;
}
void signup (){
this.register(constructSignUpRequest());
}
void register(final SignUpRequest signUpRequest) {
fragment.showProgressDialog(fragment.loading);
fragment.getApi().regsiterCustomer(constructSignUpRequest())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<GenericResponse>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
fragment.dismissProgressDialog();
Timber.e(e.getLocalizedMessage());
Toast.makeText(fragment.getContext(), fragment.connectionError, Toast.LENGTH_SHORT).show();
}
#Override
public void onNext(GenericResponse signUpResponse) {
fragment.dismissProgressDialog();
Toast.makeText(fragment.getContext(), signUpResponse.getInfo(), Toast.LENGTH_SHORT).show();
if (signUpResponse.getCode() == fragment.successCode) {
/*fragment.gotoActivationCodeActivity(SignUpRequest.getEmail(), SignUpRequest.get());*/
fragment.gotoQuestionActivity(signUpRequest.getEmail(), signUpRequest.getName(), signUpRequest.getMobile());
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(token, signUpResponse.getData().getToken());
editor.commit();
}
}
});
}
}
You missed to define the sharedpreferences in the second class like this, the way you did in the first class.
sharedpreferences = fragment.getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Place this line, just above the code,
SharedPreferences.Editor editor = sharedpreferences.edit();
inside onNext()
I am using backendless.com as my backend for my application. I need to log my user in within a fragment. I keep getting a syntax error stating that the Asynchronous login method provided by backendless.com is not recognized. It works perfectly fine within an Activity. Does anyone know how to get it to work within a Fragment? Here is a screenshot of the error:
Here is the code for my Fragment:
public class LoginFragment extends Fragment implements View.OnClickListener {
private FragmentTransaction ft;
private Button registerButton, resetButton, loginButton;
EditText userName, password;
private boolean isPopUpOpen;
BackendlessUser userOne = new BackendlessUser();
private static final String PREFS_LOGGED_IN = "AreYouLoggedInFile";
public OnClickedListener listener;
public LogInInterface loggedInListener;
static interface OnClickedListener{
public void buttonClicked(View v);
}
static interface LogInInterface{
public void userLoggedIn(boolean loggedIn);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.listener = (OnClickedListener)activity;
this.loggedInListener = (LogInInterface)activity;
}
public LoginFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
isPopUpOpen = false;
if (savedInstanceState!=null){
if (savedInstanceState.getBoolean("isDialogOpen")){
resetPopUpWindow();
}
}
View view = inflater.inflate(R.layout.fragment_login, container, false);
registerButton = (Button)view.findViewById(R.id.register_button);
resetButton = (Button) view.findViewById(R.id.reset_button);
password = (EditText)view.findViewById(R.id.fragment_login_password);
userName = (EditText)view.findViewById(R.id.fragment_login_username);
loginButton = (Button)view.findViewById(R.id.fragment_login_loginButton);
registerButton.setOnClickListener(this);
resetButton.setOnClickListener(this);
loginButton.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.register_button:{
listener.buttonClicked(v);
break;
}
case R.id.reset_button:{
isPopUpOpen = true;
resetPopUpWindow();
break;
}
case R.id.fragment_login_loginButton:{
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Logging In...");
progressDialog.show();//FOLLOWING METHOD NOT WORKING...
Backendless.UserService.login("email", password, new AsyncCallback<BackendlessUser>() {
public void handleResponse(BackendlessUser user) {
Toast.makeText(getActivity(), "Logged In!", Toast.LENGTH_LONG).show();
SharedPreferences myPrefs = getActivity().getSharedPreferences(PREFS_LOGGED_IN, 0);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putBoolean("isLoggedIn", true);
editor.commit();
}
public void handleFault(BackendlessFault fault) {
Toast.makeText(getActivity(), "No Name", Toast.LENGTH_LONG).show();
}
});
}
break;
}
The login() method for Backendless expects a String as the second parameter. You're passing it an EditText. You have to extract the value out of the EditText. Do password.getText().toString() as your second parameter to the login() method.
And, its a good practice to check for empty value in the EditText before you actually send the value. So make sure to do those checks.
As this website mentions the login method syntax is like this:
public void Backendless.UserService.login( String login,
String password,
AsyncCallback<BackendlessUser> callback );
public void Backendless.UserService.login( String login,
String password,
boolean stayLoggedIn,
AsyncCallback<BackendlessUser> callback );
and you are passing an EditText instead of a String. So replace this:
Backendless.UserService.login("email", password, new AsyncCallback<BackendlessUser>() {
public void handleResponse(BackendlessUser user) {
Toast.makeText(getActivity(), "Logged In!", Toast.LENGTH_LONG).show();
SharedPreferences myPrefs = getActivity().getSharedPreferences(PREFS_LOGGED_IN, 0);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putBoolean("isLoggedIn", true);
editor.commit();
}
public void handleFault(BackendlessFault fault) {
Toast.makeText(getActivity(), "No Name", Toast.LENGTH_LONG).show();
}
});
with this:
Backendless.UserService.login("email", password.getText().toString(), new AsyncCallback<BackendlessUser>() {
public void handleResponse(BackendlessUser user) {
Toast.makeText(getActivity(), "Logged In!", Toast.LENGTH_LONG).show();
SharedPreferences myPrefs = getActivity().getSharedPreferences(PREFS_LOGGED_IN, 0);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putBoolean("isLoggedIn", true);
editor.commit();
}
public void handleFault(BackendlessFault fault) {
Toast.makeText(getActivity(), "No Name", Toast.LENGTH_LONG).show();
}
});
Hope it helps!!!
I want to add a checkbox in login-phase that, when it is clicked the app remember the user also when he exits without logout,
but when this checkbox isn't clicked the user access to several activities but when he exits without logout there is still the logout.
This is my code:
public class MainActivity extends Activity implements OnClickListener{
private EditText username=null;
private EditText password=null;
private Button login, registration;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String user = "nameKey";
public static final String pass = "passwordKey";
SharedPreferences sharedpreferences;
public boolean isChecked = false;
public boolean isunChecked = true;
private CheckBox check;
String a,b, result,z, clic;
Class<?> activityClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
username = (EditText)findViewById(R.id.editText1);
password = (EditText)findViewById(R.id.editText2);
registration = (Button)findViewById(R.id.button2);
login = (Button)findViewById(R.id.button1);
TextView text2 = (TextView) findViewById(R.id.tv);
login.setOnClickListener(this);
registration.setOnClickListener(this);
check = (CheckBox) findViewById(R.id.checkBox);
check.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1 : {
login.setEnabled(false);
registra.setEnabled(true);
registra.setClickable(false);
username.setFocusable(false);
password.setFocusable(false);
if (check.isChecked()) {
clic = "Checked";
System.out.println("CheckBox is checked");
}
else{
clic = "no_Checked";
System.out.println("CheckBox is unchecked");
}
LoginTask task = new LoginTask(username,password);
task.execute(null,null,null);
break;
}
case R.id.button2: {
registration.setEnabled(false);
login.setEnabled(true);
login.setClickable(false);
registration(v);
break;
}
}
}
public class LoginTask extends AsyncTask<Void, Void, String> {
public LoginTask(EditText username2, EditText password2) {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result.equals("ok")){
Toast.makeText(MainActivity.this, "ok", Toast.LENGTH_SHORT).show();
}
else {
login.setEnabled(true);
login.setClickable(true);
registration.setEnabled(true);
registration.setClickable(true);
username.setFocusableInTouchMode(true);
password.setFocusableInTouchMode(true);
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(Void... params) {
String result = null;
Editor editor = sharedpreferences.edit();
try {
[....]
String u = username.getText().toString();
String p = password.getText().toString();
editor.putString(user, u);
editor.putString(pass, p);
if(clic.equals("checked
editor.putBoolean("isChecked", isChecked);
System.out.println("clic");
}else{
editor.putBoolean("isChecked", isunChecked);
System.out.println("no_clic");
}
editor.commit();
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(intent);
}
catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
return result=e.getMessage();
}
return result="ok";
}
}
#Override
protected void onResume() {
sharedpreferences=getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
if(isChecked = sharedpreferences.getBoolean("isChecked", true)){
Toast.makeText(MainActivity.this, "login", Toast.LENGTH_SHORT).show();
if (sharedpreferences.contains(user))
{
if(sharedpreferences.contains(pass)){
Toast.makeText(MainActivity.this, "login", Toast.LENGTH_SHORT).show();
System.out.println(" CheckBox is checked");
try {
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
activityClass = Class.forName(prefs.getString("activity1", FirstActivity.class.getName()));
prefs.getString("activity2", SecondActivity.class.getName());
} catch(ClassNotFoundException ex) {
}
Intent i = new Intent(this, activityClass);
startActivity(i);
}
}
}else{
Toast.makeText(MainActivity.this, "logout", Toast.LENGTH_SHORT).show();
System.out.println("logout");
//logout();
}
super.onResume();
}
public void registration (View view){
Intent intent1;
intent1 = new Intent (this, Registration.class);
startActivity(intent1);
}
public void onPause() {
super.onPause();
this.finish();
}
public void closing() {
finish();
}
this code doesn't work, because when the checkbox isn't checked the user is logged yet. maybe I'm wrong to place the control on the checkbox? How can I solve this problem?
your user is remebered because when you pause the app, all attributes hold active. you have to destroy the main activity launcher to delete these values To hold the session if you click checkbox I recommend you to use a data base where you remember the user, password and active.
I'm attempting to evaluate my preferences in my java code in order to enable/disable other options it they chose not to do other options... So far i'm trying to only implement the OnPreferenceClickListener however i never see the toast from the changes. What am i doing wrong? There seem to be alot of other questions like this but i cannot see my error in reference to them.
public class UserSettingActivity extends PreferenceActivity implements OnPreferenceClickListener{
SharedPreferences mPreferences;
Boolean frequency;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
#Override
public boolean onPreferenceClick(Preference preference) {
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
frequency = mPreferences.getBoolean("frequency", true);
Context context = getApplicationContext();
Toast.makeText(context, "Hello toast 0!", Toast.LENGTH_LONG).show();
if (!frequency) {
Context context2 = getApplicationContext();
Toast.makeText(context2, "Hello toast 1!", Toast.LENGTH_LONG).show();
} else if (preference.getKey().equals("schedulestop")) {
} else if (preference.getKey().equals("priority")) {
} else {
Context context3 = getApplicationContext();
Toast.makeText(context3, "Hello toast 0!", Toast.LENGTH_LONG).show();
}
return false;
}
}
You have to register for PreferenceClickListener each individual preference
somePreference.setOnPreferenceClickListener(this);
or you can use getSharedPreferences().registerOnSharedPreferenceChangeListener for all preferences.
public class UserSettingActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener{
SharedPreferences mPreferences;
Boolean frequency;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
#SuppressWarnings("deprecation")
#Override
protected void onPause()
{
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
protected void onResume()
{
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("schedulestop")) {
// do something
}
else if (key.equals(......
}
}
first implement "OnSharedPreferenceChangeListener"
PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener
Then
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
settings.registerOnSharedPreferenceChangeListener(this);
}
THEN
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
switch (key) {
case "pref_key_auto_delete":
boolean notificationStatus = SP.getBoolean(key, false);
Log.d("stat", String.valueOf(notificationStatus));
break;
case "pref_key_notification_list":
String downloadType = SP.getString(key, "n/a");
Log.d("stat", String.valueOf(downloadType));
break;
}