Android: stay connected with checkbox - android

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.

Related

android - Always switching to the same activity even if the intent has another activity in its code

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
}}

Using Shared Preferences with Log in with Facebook

I'm trying to save user details after logging in (with Facebook). I'm able to fetch data but can't save it. I'm using SharedPreferences but can't save it. Data is not lost when I go on some other activity, but when I click back button and re-open this activity, all data is lost. Here is my code:
Profilee.java
public class Profilee extends Fragment {
String email1, birthday1, gender1;
ImageView imageView;
static int itis = 1;
TextView texty;
LoginButton button;
LinearLayout userinput;
private CallbackManager callbackManager;
private TextView textView;
SharedPreferences pref;
private TextView email, birthday, gende;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
GraphRequest graphrequest = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
JSONObject jsonObject = response.getJSONObject();
if (jsonObject != null) {
try {
email1 = jsonObject.getString("email");
gender1 = jsonObject.getString("gender");
birthday1 = jsonObject.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email, gender, birthday");
graphrequest.setParameters(parameters);
graphrequest.executeAsync();
AppEventsLogger.activateApp(getContext());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public Profilee() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
Toast.makeText(getContext(), "Create", Toast.LENGTH_SHORT).show();
pref = getContext().getSharedPreferences("", getContext().MODE_PRIVATE);
pref.getString("name", "asdfgh");
pref.getString("email", "qwerty");
pref.getString("gender", "zxcvb");
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profilee, container, false);
button = (LoginButton) v.findViewById(R.id.login_button);
TextView button12 = (TextView) v.findViewById(R.id.edit);
button12.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getContext(), PrifileEdit.class);
i.putExtra("st", email1);
startActivity(i);
}
});
texty = (TextView) v.findViewById(R.id.emo);
imageView = (ImageView) v.findViewById(R.id.asd);
userinput = (LinearLayout) v.findViewById(R.id.userdetail);
int unicode = 0x1F60E;
String emoji = getEmijoByUnicode(unicode);
String text = "We will never post on your wall without permission ";
texty.setText(text + emoji);
Toast.makeText(getContext(), "CreateView", Toast.LENGTH_SHORT).show();
return v;
}
public String getEmijoByUnicode(int unicode) {
return new String(Character.toChars(unicode));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
textView = (TextView) view.findViewById(R.id.textView);
email = (TextView) view.findViewById(R.id.emailid);
gende = (TextView) view.findViewById(R.id.gender);
birthday = (TextView) view.findViewById(R.id.birth);
loginButton.setReadPermissions("email");
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
Toast.makeText(getContext(), "ViewCreate", Toast.LENGTH_SHORT).show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
onResume();
}
}, 2000);
}
public void displayMessage(final Profile profile) {
if (itis == 1) {
if (profile != null) {
textView.setText(profile.getName());
email.setText(email1);
gende.setText(gender1);
birthday.setText(birthday1);
button.setVisibility(View.GONE);
texty.setVisibility(View.GONE);
userinput.setVisibility(View.VISIBLE);
pref = getContext().getSharedPreferences("", getContext().MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("name", String.valueOf(textView));
editor.putString("email", String.valueOf(email));
editor.putString("gender", String.valueOf(gende));
editor.commit();
}
}
}
#Override
public void onStart() {
super.onStart();
Toast.makeText(getContext(), "Start", Toast.LENGTH_SHORT).show();
}
#Override
public void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
AppEventsLogger.activateApp(getContext());
}
}
I think this problem is because of displayMessage() method .
when you reopen this Activity , onResume(); method will call , and then displayMessage() .
in displayMessage() you are setting sharedprefrecens values again , and this work cause you lost previous data from this sharedprefrecens.
for solve this problem you must cut onResume codes inside onCreate method
You aren't persisting the data in SharedPreferences correctly. getText() will retrieve the text that is currently displayed in the TextView, allowing you to store it into SharedPreferences.
editor.putString("name", String.valueOf(textView)); // wrong
editor.putString("name", textView.getText().toString()); // right
You can then retrieve the value and display it on screen by calling setText().
String myEmail = pref.getString("email", "qwerty");
textView.setText(myEmail);

BackEndless.Com - Asynchronous Login in Fragment

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!!!

Passing data through Intent Android

I'm currently trying to program an app which requires the user to key in their name. This is the "Login" page.
public class Login extends Activity
{
EditText username;
#Override
public void onCreate(Bundle savedInstanceState)
{
username = (EditText)findViewById(R.id.username);
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button loginButton = (Button) findViewById(R.id.loginBtn);
loginButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent("com.example.MainActivity");
Bundle extras = new Bundle();
extras.putString("name", username.getText().toString());
intent.putExtras(extras);
startActivity(intent);
}
});
}
protected void onDestroy() {
super.onDestroy();
}
protected void onPause() {
super.onPause();
saveAsPreferences();
}
protected void onRestart() {
super.onRestart();
saveAsPreferences();
}
protected void onResume() {
super.onResume();
retrievePreferences();
}
protected void onStart() {
super.onStart();
retrievePreferences();
}
protected void onStop() {
super.onStop();
saveAsPreferences();
}
public void saveAsPreferences()
{
SharedPreferences prefs = getSharedPreferences("preferences", MODE_PRIVATE);
String Name = username.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("name", Name);
editor.commit();
}
public void retrievePreferences()
{
SharedPreferences prefs = getSharedPreferences("preferences",MODE_PRIVATE);
if(prefs.contains("name"))
{
String Name = prefs.getString("name", "");
username.setText(Name);
}
}
}
and this is my Result page
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = getIntent().getExtras();
String Name = bundle.getString("name");
TextView welcomeUser = (TextView) findViewById(R.id.welcomeUser);
welcomeUser.setText("Hello " + Name + "!");
}
why isn't my codes working? Thanks!
Note: I've linked the pages correctly before I start on passing data.
You should change the order like in your Login Activity
setContentView(R.layout.login);
username = (EditText)findViewById(R.id.username);
First you need to setContentView(..) then reference Views.
do in this way . in your login class don't use Bundle . use intent.putExtra("name",username); and then in your main activity class . getIntent().getStringExtra("name"); this will return the username and define your Edittext aftert setContentView

Android Password Change Activity

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

Categories

Resources