How to log out from google account in android ? - java

I am developing application that uses login using google Auth2.0 with android account manager. I am login successfully and fetching data from my google using different apis but I don't know about how to log out from my application and when logout want to shows login screen once again.

I don't think you can log-out, you will have to show the AccountChooser again
try
Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[] {"com.google"}, false, null, null, null, null);
startActivityForResult(intent, SOME_REQUEST_CODE);

Usually i saved the account name on SharedPreferences and on log-out just remove the account name from the SharedPreferences. Saving the account name from onActivityResult
if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.commit();
//do the rest after saving the account name on SharedPreferences
}
}
And log out(my log out occur on a different activity):
private void logOut(){
SharedPreferences sharedPreferences = getSharedPreferences("MainActivity",Context.MODE_PRIVATE);
if (sharedPreferences.getString(PREF_ACCOUNT_NAME,null)!=null){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(PREF_ACCOUNT_NAME);
editor.commit();
//here show the log-in screen again
}
}

While logging in you have saved data i.e. your access token in shared preferenes. So when you want to LogOut clear shared preferences. It is the only way to logout.

Related

How can you switch data from an activity that appears only once to another one that always appears, you register once and than you only need to login

HActivity.java
pass1 = (EditText) findViewById(R.id.edt1);
pass1c = (EditText) findViewById(R.id.edt2);
confirm = (TextView) findViewById(R.id.tv1);
SharedPreferences pref = getSharedPreferences("Apref", Context.MODE_PRIVATE);
if(pref.getBoolean("act_ex", false)){
String passs11 = pass1.getText().toString();
Intent intent = new Intent(this, LogInAct.class);
intent.putExtra("PASSWW", passs11);
startActivity(intent);
finish();
} else {
SharedPreferences.Editor ed = pref.edit();
ed.putBoolean("act_ex", true);
ed.commit();
}
// Its using java in Android Studio, it passes the password the first time you open the app but the second time you do that it will say wrong password (as I wanted) even if you type the right password (the one you registered with) how can I save it somewhere or do something with it?
LogInAct.java
tv2 = (TextView) findViewById(R.id.tv2);
edt3 = (EditText) findViewById(R.id.edt3);
Button loginbtn = (Button) findViewById(R.id.loginbtn);
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logpass = edt3.getText().toString();
passs1 = getIntent().getExtras().getString("PASSW");
passs11 = getIntent().getExtras().getString("PASSWW");
if (logpass.equals(passs1) && logpass.equals(passs11)) {
Intent intent = new Intent(getApplicationContext(), Photos.class);
startActivity(intent);
} else {
tv2.setText("wrong password");
}
}
});
So it looks to me like on your "registration" screen, you're capturing the username and password, and then passing them through the intent to the Login Screen? This works great in a single instance, but doesn't persist.
It's hard to tell just from the code, but how are you taking the user to the Login Screen on the next time they open the application? Is it just going to that screen as the launch?
Data passed over in intents is not persisted between sessions. It's most useful when passing data from one screen to another just for that session.
It can be used if you have a list screen and on the next screen is the detail screen. You want to pass the id of which item they clicked for example so you can load the data on that screen. But there is no reason to store it if they closed the app and opened it again.
To persist data between sessions, you want to store and extract from a more permanent storage. Ideally, you'll end up with a database system of some sort. But to answer what you're trying to do, use the shared preferences both for storing and extracting the password.
Registration:
SharedPreferences pref = getSharedPreferences("Apref", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("username", username);
editor.putString("password", password");
editor.apply();
Login:
SharedPreferences pref = getSharedPreferences("Apref", Context.MODE_PRIVATE);
passs1 = pref.getString("username");
Again, this is definitely not a good way to store user's credentials, but it answers your question of persistence.

sharedpreferences from LoginActivity to MainActivity

I want to save a value from my LoginActivity and Provide that to my MainActivity, but currently Log.d does not Show anything.
I tried using shared preferences.
My LoginActivity:
// I want to save email to mainactivity
SharedPreferences webrtcOptions = getSharedPreferences("webrtcOptions", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = webrtcOptions.edit();
editor.putString("email", email);
editor.commit();
And in my MainActivity I try to call it like this:
SharedPreferences webrtcOptions = getSharedPreferences("webrtcOptions", 0);
String currentUserMail = webrtcOptions.getString("email", "test");
Log.d("HERE", currentUserMail);
Try putExtra to send values to another Activities in your LoginActivity:
Intent i = new Intent(LoginActivity.this, MainActivity.class);
String strName = null;
i.putExtra("email", email);
In your MainActivity you get the value like this:
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("email");
}
} else {
newString= (String) savedInstanceState.getSerializable("email");
}
Log.d should at least show your string "HERE" if you can not see that it may have one of following reasons
Your Log.d code is not executed, make sure it is executed
Or your android studios log window has bad configuration then do the following:
If you do not see logs from your app check your Android studio's Log window then make sure you have selected
correct emulator or device
correct app
correct filter
make search field empty

Login Page shared preference not working as expected

I have an android app in which I am using shared preferences for login.Until now I have a flow like user logs in..when login is successful the credentials are stored.And when the user opens the app again the username password appears in the edit text.I have a login button and have setonclicklistner to login and jump to the inner activities.
I am trying a flow like when the user logs in successfully..and the app is restarted the credentials are stored..it should automatically go the next activity(inner activity).
What I have tried until now..
In oncreate the onclicklistner that opens next activity if credentials are good
buttonlogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(etemail.getText().toString().equals("") && etpass.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(),"Enter your username and Password",Toast.LENGTH_LONG).show();
}
else
{
load_data();
}
}
});
Code of shared pref
private void savePreferences() {
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
// Edit and commit
UnameValue = etemail.getText().toString();
PasswordValue = etpass.getText().toString();
editor.putString(PREF_UNAME, UnameValue);
editor.putString(PREF_PASSWORD, PasswordValue);
editor.commit();
}
private void loadPreferences()
{
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
// Get value
UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);
etemail.setText(UnameValue);
etpass.setText(PasswordValue);
}
What should I do in order to achieve this??if username password is stored automatically open next activity instead of clicking login button??
Thanks
you can use contains(String key) in SharedPreferences class
could be done in loadPreferences()
if login is only used to allow access to the next activity, then you don't need to simulate the button click, but if the click loads other data based on the provided username/password then you have to do it using performClick() in Button class.
so your code may look like this:
private void loadPreferences()
{
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if(settings.contains(PREF_UNAME) && settings.contains(PREF_PASSWORD)){
//you can start the 2nd activity directly here
//Intent intent = new Intent (...)
//startActivity(intent);
//finish();
//OR
//load data into edittexts and programatically click the login button
UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);
etemail.setText(UnameValue);
etpass.setText(PasswordValue);
//here it will click the button as if the user did it.
btnLogin.performClick();
}//contains
}
Side note: it's not good practice (not secure) to store passwords in SharedPreferences specially plain-text, not encrypted
Open the next activity first, and then in onCreate method check if the user is logged in. If not close the first, and open the loggin activity.
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new SessionManager(getApplicationContext());
CheckLogin();
...
}
private void CheckLogin(){
if(session.checkLogin()){finish();}
}
SessionManager.java
public boolean checkLogin(){
// Check login status
if(!this.isUserLoggedIn()){
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities from stack
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
return true;
}
return false;
}
After storing username and password in sharedpreference editor.putBoolean("hasLoggedin", true);
So it should be like
UnameValue = etemail.getText().toString();
PasswordValue = etpass.getText().toString();
editor.putString(PREF_UNAME, UnameValue);
editor.putString(PREF_PASSWORD, PasswordValue);
editor.putBoolean("hasLoggedin", true);
editor.commit();
then check in Oncreate method like
boolean hasLoggedin = sp.getBoolean("hasLoggedin", false);
if (hasLoggedin) {
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}

sharedPreferences.getString() return null

Im trying to display the user email in a textView using SharedPreferences.
Shared preferences is created in loginActivity.
I try to access it from mainActivity.
My session using sharedPreference work well (with a login boolean saved in sharedPreferences files).
So what's wrong?
- A context error?
- Because I try to access the data from an another activity?
Please help :) Thanks a lot!
Here is the code im using :
Login Activity :
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if(loggedIn){
//We will start the Profile Activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
}
...
//Creating a shared preference in a login()
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
//Adding values to editor
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true);
editor.putString(Config.EMAIL_SHARED_PREF, email);
//Saving values to editor
editor.commit();
...
Main Activity :
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
email_session = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Private");
usernameText.setText(email_session);
}
to read the stored preferences you need to do:
to save
SharedPreferences spref = getSharedPreferences("your_prefs_name", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("myTextViewValue", prefVal); //
editor.commit();
to read it
SharedPreferences preferences = getPreferences(Activity.MODE_PRIVATE);
String storedPreference = preferences.getStr("myTextViewValue", null);
This happens because your value is not stored in the shared preferences.
SharedPreferences pref = getSharedPreferences("your Pref Name", 0) // 0 for Private Mode
String name = pref.getString("your key store when login", null); // null is the default value you can put it here "No value". then you will not get null pointer.

Save intent in shared preference

I have an application from which i can launch other apps installed on my phone, with a long click i get the app picker, in result i receive an intent data, how can i save it so the user when closes an comes back to my app has the same shortcuts setup?
i save other things like this
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("Counter1", counter);
editor.putBoolean("FirstRun", firstRun);
editor.putString("Label2", label2S);
editor.commit();
But i can't do the same with the intent
Ok i found a way
I save the intent like this
SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);
SharedPreferences.Editor editor = settings.edit();
String uriString = data.toUri(requestCode);
editor.putString("Contacts_app", uriString);
editor.commit();
Then i retrieve it like this
SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);
String contactsApp = settings.getString("Contacts_app", null);
try {
telApp = Intent.parseUri(contactsApp, 0);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You could serialize the object to a string, and save the resulting string in the preferences. An easy way would be to serialize it in json format, using Google Gson for example.

Categories

Resources