Logging user out Java - java

I am creating a social app with a login/Registration system and I am having trouble logging the user out.
When I click the logout button I want to unset the username and clear the entire session of the user so that they go back to the LoginActivity class. Right now when I go to the profile activity and click logout I go straight back to the Home Activity which is only suppose to be for user who are logged in. I've been trying since yesterday and still nothing. Can someone help me ?
Login activity:
//SharedPreferences preferences;
private ProgressDialog loadingBar;
private Button LoginButton;
private EditText LoginUsername, LoginPassword;
private TextView NeedNewAccountLink;
private static final String PREF_LOGIN = "LOGIN_PREF";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(PREF_LOGIN, MODE_PRIVATE);
SharedPreferences sharedPreferences = getSharedPreferences(PREF_LOGIN, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
}
LoginButton = (Button) findViewById(R.id.login_button);
LoginUsername = (EditText) findViewById(R.id.login_username);
LoginPassword = (EditText) findViewById(R.id.login_password);
NeedNewAccountLink = (TextView) findViewById(R.id.need_new_account_link);
loadingBar = new ProgressDialog(this);
editor.putString("username", String.valueOf(LoginUsername));
editor.putString("pw", String.valueOf(LoginPassword));
editor.apply();
if (LoginUsername != null) {
editor.remove("username");
editor.remove(String.valueOf(sharedPreferences));
editor.remove("pw");
editor.clear();
editor.apply();
SendUserToHomeActivity();
}
private void SendUserToHomeActivity() {
Intent mainIntent = new Intent(LoginActivity.this, HomeActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
public void OnLogin(View view) {
String username = LoginUsername.getText().toString();
String pw = LoginPassword.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, username, pw);
}
profile activity:
LogoutButton.setOnClickListener(view -> {
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().clear().apply();
sharedPreferences.edit().remove("username").apply();
sharedPreferences.edit().remove("pw").apply();
editor.remove("username");
editor.remove("pw");
editor.clear();
editor.apply();
finish();
Intent intent = new Intent(ProfileActivity.this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
});

LogoutButton.setOnClickListener(view -> {
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().clear().apply();
sharedPreferences.edit().remove("username").apply();
sharedPreferences.edit().remove("pw").apply();
editor.remove("username");
editor.remove("pw");
editor.clear();
editor.apply();
Intent intent = new Intent(ProfileActivity.this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
});
Remove the Intent.FLAG_ACTIVITY_CLEAR_TOP flag will solve your problem. Please refer to this link.

I believe to get text from edit text you need
LoginUsername.getText().toString()
and Checking EditText "LoginUsername" against If condition will never yield null unless
it points to wrong ID
Try proceeding with appropriate changes in below code block
LoginUsername = (EditText) findViewById(R.id.login_username);
LoginPassword = (EditText) findViewById(R.id.login_password);
NeedNewAccountLink = (TextView) findViewById(R.id.need_new_account_link);
loadingBar = new ProgressDialog(this);
editor.putString("username", String.valueOf(LoginUsername));
editor.putString("pw", String.valueOf(LoginPassword));
editor.apply();
if (LoginUsername != null) {
editor.remove("username");
editor.remove(String.valueOf(sharedPreferences));
editor.remove("pw");
editor.clear();
editor.apply();
SendUserToHomeActivity();
}

Related

How to stop signInWithEmailAndPassword when another activity is started?

I am working on a login app using FirebaseAuth, I am implementing two separate Activities, one to work online and other for offline. There is third starter activity that tries to automatically login a user if his data is present on the SharedPreferences. When finish() is called on an activity signInWithEmailAndPassword won't stop.
when internet is not working and "Work Offline" button is clicked , it will lead the user to ActivityOffline. But when internet is restored while the user is on ActivityOffline , out of nowhere ActivityOnline will pop up because of signInWithEmailAndPassword on the starter activity which is already finished.
How can i stop signInWithEmailAndPassword when my Work Offline button is clicked?
public class Starter extends AppCompatActivity {
Button useOffline;
String email;
String password;
FirebaseAuth mAuth = FirebaseAuth.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starter);
Prefs prefs = new Prefs(this);
email = prefs.getStringEntry("email");
password = prefs.getStringEntry("password");
useOffline = findViewById(R.id.use_offline);
useOffline.setOnClickListener(v -> {
Intent intent = new Intent(Starter.this, OfflineActivity.class);
startActivity(intent);
finish();
});
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(() -> useOffline.setVisibility(View.VISIBLE), 5000);
if (email.equals("") || password.equals("")) {
Intent intent = new Intent(Starter.this, LoginActivity.class);
startActivity(intent);
finish();
} else {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
prefs.setStringEntry("UID", Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid());
Intent intent = new Intent(Starter.this, OnlineActivity.class);
startActivity(intent);
} else {
prefs.removeEntry("email");
prefs.removeEntry("password");
Intent intent = new Intent(Starter.this, LoginActivity.class);
startActivity(intent);
}
finish();
});
}
}
}
You can set a boolean flag to true when offline button press and check this flag before start online activity.

Start splash screen after application termination

in my project I have static member as User.current.
If I run the app after it terminates in background, User.current will be null. I get user from server on splash screen.
I want to start splash screen when I run terminated application.
How I can solve this problem?
If you call a server, you probably use an Async task. In Async task
...
#Override
protected Boolean doInBackground(Void... params) {
...
value = jsonObj.getString("value");
return true;
}
protected void onPostExecute(Boolean iHaveValue) {
if(iHaveValue){
// use case 1 or 2
// 1
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("value", value);
startActivity(i);
// 2
SharedPreferences sharedpreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("value", value);
editor.commit();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
}
You get the user on the doInBackground(Void... params). And in the onPostExecute(Boolean iHaveValue) method you simply go to the MainActivity.
You can use the intent to put the value and receive on MainActivity (1) or use a shared preference (2)
(1)
in SplashScreen
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("value", value);
startActivity(i);
in MainActivity
Intent editIntent = new Intent(getApplicationContext(), Splashscreen.class);
(2)
in SplashScreen
SharedPreferences sharedpreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("value", value);
editor.commit();
in MainActivity
SharedPreferences prefs = getSharedPreferences("user", MODE_PRIVATE);
value = prefs.getString("value", "null");
If you need use this value for multiple locations, sharedPreferences helps a lot (case 2). If not, use putExtra to send info to MainActivity (case 1).

Shared Preferences not retrieving value

I have two activities namely Registration and Login where I defined a Shared Preferences in the Registration class. On the Registration page, if you click on the button that takes you to the Login Activity from the Registration Activity. I am storing a Shared Preferences value, so that on launching the app the second time, let the app immediately go to the LoginActivity instead of opening the first Activity which is Registration Activity. Here is my SharedPreferences class called Session.
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", usename).commit();
editor.commit();
public Boolean contKey(String key){
if (prefs.contains(key)){
return true;
}else{
return false;
}
}
Here is the button in the RegstrationActivity that stores the SharedPreferences value before going to the LoginActivity so that on launch the second time, it opens the LoginActivity class
loginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
session = new Session(getApplicationContext());
session.setusename("hello123");
Intent intent = new Intent(getApplication(),ActivityLogin.class);
startActivity(intent);
finish();
}
});
I have defined this in the onCreate method of RegistrationActivity class to switch to the ActivityLogin screen on next time the app is launched
System.out.println("it got here...2");
try {
if (session.contKey("username")) {
System.out.println("it got here...");
Intent intent = new Intent(getApplication(), ActivityLogin.class);
startActivity(intent);
overridePendingTransition(R.anim.enter, R.anim.exit);
finish();
} else {
System.out.println("it got here...3");
Intent intent = new Intent(getApplication(), ActivityRegistration.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.enter, R.anim.exit);
}
}catch(Exception ex){
}
Please why is my Shared Preferences not switching to the LoginActivity the second time the is launched. Kindly assist
TRy this
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", usename);
editor.commit();
}
}
public String getusename() {
return prefs.getString("username","");
}
}
than use this way to get value SharedPreferences
session = new Session(getApplicationContext());
session.setusename("hello123");
String username=session.getusename();
Sample code
try {
if (!session.getusename().equals("")) {
System.out.println("it got here...");
Intent intent = new Intent(getApplication(), ActivityLogin.class);
startActivity(intent);
overridePendingTransition(R.anim.enter, R.anim.exit);
finish();
} else {
System.out.println("it got here...3");
Intent intent = new Intent(getApplication(), ActivityRegistration.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.enter, R.anim.exit);
}
}catch(Exception ex){
}
Instead of default shared preference, you can define a private one with your desired name in the Activity A..like as follows..
SharedPreferences preferences = getSharedPreferences("myPreferences",0);
SharedPreferences.Editor editor= preferences.edit();
editor.putString("userName","raju");
editor.commit();
If you want to retrieve that value from shared preferences in Activty A(I mean in the same activity), you can use following code..
String user_name= preferences.getString("userName","N/A");
or else in Activity B(I mean in some other activty), this time you don't need editor(for retrieval)..the code will be as follows
SharedPreferences preferences = getSharedPreferences("myPreferences",0);
String user_name= preferences.getString("userName","N/A");

Pass multiple Intents to multiple activities

I want to pass info as shown in this picture screen description
I know that my code is working, becuase with one Intent it works perfectley. However, when I try to put two or more Intents it seems to get messed up. I also checked here to find a sutibale solution, but I don't think I can use it the same way. Thanks in advance
--update--
still dosen't work
i did this on my saving side
Intent saveIntent = new Intent(this, MainActivity.class);
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("time", displayTime.getText().toString());
editor.commit();
startActivity(saveIntent);
and this on my reciving side
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String time = preferences.getString("time",null);
if (time != null)
getTime.setText(time);
Main Activity:
private Button createNewEvent;
private Button showMyEvents;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNewEvent = (Button) findViewById(R.id.bCreateNewEvent);
showMyEvents = (Button) findViewById(R.id.bShowMyEvents);
}
public void buttonOnClick(View v) {
switch (v.getId()) {
case R.id.bCreateNewEvent:
Intent createNewEventIntent = new Intent(this, CreateNewEventActivity.class);
startActivity(createNewEventIntent);
break;
case R.id.bShowMyEvents:
Intent myEventsIntent = new Intent(this,MyEventsActivity.class);
startActivity(myEventsIntent);
break;
}
}
}
screen 1 save button:
case R.id.bSaveNewEvent:
Intent putIntent = new Intent(getApplicationContext(),MyEventsActivity.class);
// String text = displayTime.getText().toString();
putIntent.putExtra("time",displayTime.getText().toString());
Intent saveIntent = new Intent(this, MainActivity.class);
startActivity(saveIntent);
startActivity(putIntent);
screen 2 getExtras
public class MyEventsActivity extends AppCompatActivity {
TextView getTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_events);
getTime = (TextView) findViewById(R.id.tvGetTime);
Intent in = getIntent();
String name = in.getStringExtra("time");
getTime.setText(name);
/* Bundle extras = getIntent().getExtras();
if (extras != null){
getTime.setText(extras.getString("time"));
}*/
If you are trying to save data that will be need to be used in multiple other activities, SharedPreferences will be the easiest solution.
https://developer.android.com/training/basics/data-storage/shared-preferences.html
When you want to save a value, you would use:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("time", displayTime.getText().toString());
editor.commit();
Then when you want to get the preference later on you would use:
SharedPreferences preferences = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String time = preferences.getString("time", "");

Getting data from an Intent

I am doing a project (Android app) for uni and after a bit of help I have a login screen as per the code below:
//Do once the "Login" button is clicked
public void onClick(View view)
{
//get the users name and password
EditText editName = (EditText) findViewById(R.id.txtUserName);
String name = editName.getText().toString();
//EditText editPassword = (EditText) findViewById(R.id.txtUserPassword);
//String password = editPassword.getText().toString();
//create an Intent object and pass it the name and password
Intent intent = new Intent(this, UserLoggedInScreen.class);
intent.putExtra("userName", name);
//intent.putExtra("userPassword", password);
startActivity(intent);
}
I have commented out the the password bit for now just to get the username bit working. The aim is to click the button and put the text input into textUserName by the user into the String name. Then pass that through to activity UserLoggedInScreen.
Then in UserLoggedInScreen collect the data:
public class UserLoggedInScreen extends Activity
{
TextView welcomeUser;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.userloggedinscreen);
//get the Intent Object from LapMasterActivity
Intent intent = getIntent();
//get the data from the Intent Object
String userName = intent.getStringExtra("userName");
//String userPassword = intent.getStringExtra("userPassword");
welcomeUser = (TextView) findViewById(R.id.txtUserName);
welcomeUser.setText(userName);
}
When I try running it and clicking the button in the opening activity I get the usual "Unfortunately UserLoggedInScreen has stopped working".
I think this bit might be the error:
welcomeUser = (TextView) findViewById(R.id.txtUserName);
I tried changing txtUserName to userName but that didn't help either.
Thanks.
First Thing As Bappy said Register Your activity so that it can be detected at runtime.
<activity android:name="UserLoggedInScreen">
</activity>
Second thing
welcomeUser = (TextView) findViewById(R.id.txtUserName);
EditText editName = (EditText) findViewById(R.id.txtUserName);
You are using same id, are you doing it intentionally??
Pleas Check id of TextView of UserLoggedInScreen.
have you maked activity in AndroidManifast for Second Class........
<activity android:name="UserLoggedInScreen"></activity>

Categories

Resources