I am using Firebase UI, it is working fine.
When I open the app I give one phone number and I sign in, but when I close and again open the app again give me a code.
I want that when I close the app and again open it doesn't give me again the code.
I know then this make with one if but I don't know how to make the best.
I was using firebase UI, I did see something about smart lock password of google but I don't know if this is right because the storage should be local
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.auth.IdpResponse;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.FirebaseDatabase;
import com.xx.xx.R;
import java.util.Arrays;
import java.util.List;
public class Login extends AppCompatActivity {
EditText et_login, et_password;
Button bt_login, bt_register;
private static int RC_SIGN_IN = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
setContentView(R.layout.activity_login);
et_login = (EditText) findViewById(R.id.et_login);
et_password = (EditText) findViewById(R.id.et_password);
bt_login = (Button) findViewById(R.id.bt_login);
bt_register = (Button) findViewById(R.id.bt_register);
bt_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
finish();
}
});
bt_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Login.this, RegisterActivity.class);
startActivity(intent);
}
});
// Choose authentication providers
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.PhoneBuilder().build());
// Create and launch sign-in intent
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.build(),
RC_SIGN_IN);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
if (requestCode == RC_SIGN_IN) {
IdpResponse response = IdpResponse.fromResultIntent(data);
if (resultCode == RESULT_OK) {
// Successfully signed in
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
//Save user to local database
// ...
} else {
// Sign in failed. If response is null the user canceled the
// sign-in flow using the back button. Otherwise check
// response.getError().getErrorCode() and handle the error.
// ...
}
}
}
}
The app should give me one number and save it, then when I close the app and open again it will not give me access again if not log in with before credential stored in the app.
What you can do is that in onStart check if the user is signed in or not, if the user is signed in then navigate to your MainActivity or any other Activity -
#Override
public void onStart() {
super.onStart();
// Check if the user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
// do your stuff
if (currentUser != null) {
// go to MainActivity
} else {
// user doesn't exist
}
}
Related
I am new to coding, please I need help on this specific function I will be so grateful if anyone could help.
I am working on an android studio project, and on my activity (supposed Activity A) I want to place a button which when clicked it will open Supposed Activity B.
I have been able to setup onclick function and intent to open Activity B on button click.
But now what I want is if the user is not logged in then it should take the user to LoginActivity when that button is clicked, but when user is logged in it should take user direct to Activity B.
Please how can I achieve this on my Activity? Thanks in anticipation of a solution.
Below is my LoginActivity Code
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.sckoolboy.premiumapp.R;
public class Login extends AppCompatActivity {
EditText mEmail,mPassword;
Button mCreateBtn,mLoginBtn;
TextView forgotTextLink;
ProgressBar progressBar;
FirebaseAuth fAuth;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
startActivity(new Intent(Login.this, Main1.class));
finish();
}
setContentView(R.layout.activity_login);
mEmail = findViewById(R.id.Email);
mPassword = findViewById(R.id.password);
progressBar = findViewById(R.id.progressBar);
fAuth = FirebaseAuth.getInstance();
mLoginBtn = findViewById(R.id.loginBtn);
mCreateBtn = findViewById(R.id.createText);
forgotTextLink = findViewById(R.id.forgotPassword);
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
if(TextUtils.isEmpty(email)){
mEmail.setError("Email is Required.");
return;
}
if(TextUtils.isEmpty(password)){
mPassword.setError("PremiumKey is Required.");
return;
}
if(password.length() < 6){
mPassword.setError("PremiumKey not valid");
return;
}
progressBar.setVisibility(View.VISIBLE);
// authenticate the user
fAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(Login.this, "Premium Successfully Unlocked", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),Main1.class));
}else {
Toast.makeText(Login.this, "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
});
mCreateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),Register.class));
}
});
forgotTextLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText resetMail = new EditText(v.getContext());
final AlertDialog.Builder passwordResetDialog = new AlertDialog.Builder(v.getContext());
passwordResetDialog.setTitle("Reset Password ?");
passwordResetDialog.setMessage("Enter Your Email To Received Reset Link.");
passwordResetDialog.setView(resetMail);
passwordResetDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// extract the email and send reset link
String mail = resetMail.getText().toString();
fAuth.sendPasswordResetEmail(mail).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(Login.this, "Reset Link Sent To Your Email.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Login.this, "Error ! Reset Link is Not Sent" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
passwordResetDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// close the dialog
}
});
passwordResetDialog.create().show();
}
});
}
}
using firebase authentication, how can i go about it from here
You can use an if block to switch between starting different activities, depending on whether the user was logged in or not.
For example, assuming loggedIn is the boolean variable storing whether the user was logged in, and button is the button,
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(v -> {
if (loggedIn) {
// Start ActivityB, user has logged in
Intent intent = new Intent(/* context here */, Main1.class);
startActivity(intent);
} else {
// Redirect to LoginActivity, user hasn't logged in
Intent intent = new Intent(/* context here */, Login.class);
startActivity(intent);
}
});
and the XML design for the new activity:
<!-- Root layout above..... -->
<Button
android:text="Log in"
android:id="#+id/button"/>
<!--Other elements below -->
You can get the login condition from Firebase's API, (reference made to https://stackoverflow.com/a/44585789/12204281), the method call should be:
FirebaseAuth.getInstance().getCurrentUser(), and this method returns null when user is not logged in.
So you can check if that value is null using equals operator and store it in loggedIn:
boolean loggedIn = FirebaseAuth.getInstance().getCurrentUser() != null;
i am trying to create a future payment flow into my android app. I already send to my server the OaUTH2 authentication in my method sendAuthorizationToServer; My question is, what and how should i do next, i know that i have to implement a http request to set the future payment but the documetns in paypal are using curl. what should i do next?
here is my paypal activity:
package studio.brunocasamassa.ajudaaqui.payment;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import com.google.firebase.database.DatabaseReference;
import com.paypal.android.sdk.payments.PayPalAuthorization;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalFuturePaymentActivity;
import com.paypal.android.sdk.payments.PayPalService;
import studio.brunocasamassa.ajudaaqui.R;
import studio.brunocasamassa.ajudaaqui.helper.Base64Decoder;
import studio.brunocasamassa.ajudaaqui.helper.FirebaseConfig;
/**
* Created by bruno on 02/07/2017.
*/
public class PaymentActivity extends AppCompatActivity implements View.OnClickListener{
private static final int REQUEST_CODE_FUTURE_PAYMENT = 123;
private static PayPalConfiguration config = new PayPalConfiguration()
// Start with mock environment. When ready, switch to sandbox (ENVIRONMENT_SANDBOX)
// or live (ENVIRONMENT_PRODUCTION)
.environment(PayPalConfiguration.ENVIRONMENT_NO_NETWORK)
.clientId(PayPalConfig.PAYPAL_CLIENT_ID)
// Minimally, you will need to set three merchant information properties.
// These should be the same values that you provided to PayPal when you registered your app.
.merchantName("Hipster Store")
.merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));
private ImageButton buttonPay;
private TextView editTextAmount;
private String userKey = Base64Decoder.encoderBase64(FirebaseConfig.getFirebaseAuthentication().getCurrentUser().getEmail());
private DatabaseReference dbUser = FirebaseConfig.getFireBase().child("usuarios").child(userKey);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paypal);
buttonPay = (ImageButton) findViewById(R.id.buttonPay);
editTextAmount = (TextView) findViewById(R.id.editTextAmount);
buttonPay.setOnClickListener(this);
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth = data
.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
if (auth != null) {
String authorization_code = auth.getAuthorizationCode();
Log.i("FuturePaymentExample", authorization_code);
sendAuthorizationToServer(auth);
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("FuturePaymentExample", "The user canceled.");
} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i("FuturePaymentExample",
"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
}
}
private void sendAuthorizationToServer(PayPalAuthorization auth) {
dbUser.child("auth").setValue(auth);
}
public void onFuturePaymentPressed(View pressed) {
Intent intent = new Intent(PaymentActivity.this, PayPalFuturePaymentActivity.class);
// send the same configuration for restart resiliency
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
}
public void onFuturePaymentPurchasePressed(View pressed) {
// Get the Client Metadata ID from the SDK
String metadataId = PayPalConfiguration.getClientMetadataId(this);
// TODO: Send metadataId and transaction details to your server for processing with
// PayPal...
dbUser.child("metadata").setValue(metadataId);
}
#Override
public void onDestroy() {
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
#Override
public void onClick(View v) {
onFuturePaymentPressed(v);
//onFuturePaymentPurchasePressed(v);
}
}
if someone knows, please tell me, i will be very gratefull
tks,
i am new in android app and i am doing google+ integration with my android app but i am facing problem in logout from google account .i have seen many tutorials and also download many demo projects but all in vain. also the login flow is not up to the mark. below i am going to explain u the steps performed by the app after login button clicked. sorry i can't post snapshots of my app screens.
click on signin button
add a google account by selecting EXISTING
fill email and password
signing in ....
google services COMMUNICATION check box tick.
click next
then it automatically return to the login button screen i.e very first screen
and then after some milliseconds automatically display consent screen where i click on a SIGNIN option
then i return back to the login screen (very first screen) again
and then automatically after a few milli seconds go to the next activity which i performed on
onConnected()
there i write if(mGoogleApiClient.isConnected()) logout button display but it does not, but when i write the if condition for not connected then logout button display
and then if i click on logout button ,my app crashes(i know this is not right way to go)
but anyways on clicking logout button i am unable to logout even disconnect() is applied and also cookies are not deleted.
here below is my code:
MainActivity.java
package com.gem.google;
import java.util.Arrays;
import java.util.List;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import com.gem.google.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
public class MainActivity extends FragmentActivity implements
ConnectionCallbacks , OnConnectionFailedListener
{
/* Request code used to invoke sign in user interactions. */
private static final int RC_SIGN_IN = 0;
private boolean mSignInClicked;
/* Store the connection result from onConnectionFailed callbacks so that we can
* resolve them when the user clicks sign-in.
*/
private ConnectionResult mConnectionResult;
/* Client used to interact with Google APIs. */
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private SignInButton signinbt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = build_GoogleApiClient();
setContentView(R.layout.activity_main);
signinbt=(SignInButton) findViewById(R.id.sign_in_button);
signinbt.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (view.getId() == R.id.sign_in_button
&& !mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}});
}
private GoogleApiClient build_GoogleApiClient() {
// When we build the GoogleApiClient we specify where connected and
// connection failed callbacks should be returned, which Google APIs our
// app uses and which OAuth 2.0 scopes our app requests.
return new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_SIGN_IN) {
if (resultCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
startIntentSenderForResult(mConnectionResult.getResolution().getIntentSender(),
RC_SIGN_IN, null, 0, 0, 0);
} catch (SendIntentException e) {
// The intent was canceled before it was sent. Return to the default
// state and attempt to connect to get an updated ConnectionResult.
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
public void onConnectionFailed(ConnectionResult result) {
if (!mIntentInProgress) {
// Store the ConnectionResult so that we can use it later when the user clicks
// 'sign-in'.
mConnectionResult = result;
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
public void onConnected(Bundle connectionHint) {
mSignInClicked = false;
Intent i = new Intent(MainActivity.this,nextscreen.class);
startActivity(i);
}
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
}
public void onDisconnected() {
// TODO Auto-generated method stub
}
}
nextscren.java
import android.widget.Button;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
//import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
//import android.widget.Button;
public class nextscreen extends Activity implements
GoogleApiClient.ConnectionCallbacks {
private Button signoutbt;
private GoogleApiClient mGoogleApiClient;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
// .addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
setContentView(R.layout.screen_next);
signoutbt=(Button) findViewById(R.id.btn_sign_out);
signoutbt.setVisibility (View.GONE);
if(mGoogleApiClient.isConnected())
{
signoutbt.setVisibility (View.VISIBLE);
signoutbt.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (view.getId() == R.id.btn_sign_out) {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
// CookieSyncManager.createInstance(mGoogleApiClient);
// CookieManager cookieManager = CookieManager.getInstance();
// cookieManager.removeAllCookie();
//CookieSyncManager.getInstance().sync() ;
signoutbt.setVisibility (View.GONE);
Intent i = new Intent(nextscreen.this,MainActivity.class);
startActivity(i);
// Toast.makeText(this, "User is logout!", Toast.LENGTH_LONG).show();
}
}
}
});
}
}
public void onConnected(Bundle connectionHint) {
}
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
}
}
The nextscreen activity is a class where the the control goes on connected after login and where i write the code for logout button.
so what i want is :
proper logout i.e login session must clear after logout so that on login again it ask for user id and password.
after successful login it directly go to the nextscreen activitywithout coming back to the mainactivity and then enter loginscreen.
step 7 at above should not be there i.e before consent screen login screen does not appear.
so please guys help me and tell me where i am wrong. and sorry for this long question but i am helpless and have no choice. please understand and suggest something.
Am glad to have finally resolved this issue after a long time of researching.
Bellow is the method for SigningOut
private void signOutFromGplus() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
}
}
After which at onPause of the fragment or activity, call the signOutFromGplus since all the details i need are already on my SharedPreference which i use all through my app.
#Override
public void onPause() {
super.onPause();
signOutFromGplus();
}
So on coming back to the fragment, its already SignedOut. So it wont automatically Login anymore.
Hope this helps.``
Regards
I have downloaded the sample from Parse.com for its login using facebook and adding uers to its data browser.
Its code is as follows:
IntegratingFacebookTutorialApplication class
public class IntegratingFacebookTutorialApplication extends Application {
static final String TAG = "MyApp";
#Override
public void onCreate() {
super.onCreate();
Parse.initialize(this, "Parse Application ID",
"Parse Client Key");
ParseFacebookUtils.initialize(getString(R.string.facebook_app_id));
}
Login class
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseFacebookUtils;
import com.parse.ParseUser;
public class LoginActivity extends Activity {
private Button loginButton;
private Dialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loginButton = (Button) findViewById(R.id.loginButton);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onLoginButtonClicked();
}
});
// Check if there is a currently logged in user
// and they are linked to a Facebook account.
ParseUser currentUser = ParseUser.getCurrentUser();
if ((currentUser != null) && ParseFacebookUtils.isLinked(currentUser)) {
// Go to the user info activity
showUserDetailsActivity();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ParseFacebookUtils.finishAuthentication(requestCode, resultCode, data);
}
private void onLoginButtonClicked() {
LoginActivity.this.progressDialog = ProgressDialog.show(
LoginActivity.this, "", "Logging in...", true);
List<String> permissions = Arrays.asList("basic_info", "user_about_me",
"user_relationships", "user_birthday", "user_location");
ParseFacebookUtils.logIn(permissions, this, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
LoginActivity.this.progressDialog.dismiss();
if (user == null)
{
Toast.makeText(getApplicationContext(), "Uh oh. The user cancelled the Facebook login.",
Toast.LENGTH_SHORT).show();
} else if (user.isNew()) {
Toast.makeText(getApplicationContext(), "User signed up and logged in through Facebook.",
Toast.LENGTH_SHORT).show();
showUserDetailsActivity();
} else {
Toast.makeText(getApplicationContext(), "User logged in through Facebook!",
Toast.LENGTH_SHORT).show();
showUserDetailsActivity();
}
}
});
}
private void showUserDetailsActivity() {
Intent intent = new Intent(this, UserDetailsActivity.class);
startActivity(intent);
}
}
Question:
Starting up the app (this tutorial), login page (page A) is shown, with a login in facebook button in middle.
If a user does not have facebook app in his device, the above code can run smoothly and successfully, after pressing login button, it will pop a dialog box and after logged in, the user details can be fetched and user details added to the data browser inside Parse.
However, if the user has already installed facebook app in the device, the dialog box would not appear, instead, it will open the facebook app and ask for login. This is where the problem happen. It shows for the permission dialog, and then after pressing "ok", the dialog is gone and return to the original page (page A).
The toast remarks "Uh oh. The user cancelled the Facebook login".
What is wrong with the code?? or the ADT environment? Should I further add anything in manifest?
I have researched as follows:
some say 'After a lot of attempts, the trick was a support.jar, specifically android-support-v4.jar. This comes with the new latest Facebook SDK but is not standard on your project. Use the Facebook one that is in their SDK and copy it into your libs folder and link.' (https://parse.com/questions/urgent-parsefacebookutilslogin-issue-android)
I was using the android:noHistory="true" on the manifest file for that activity. So whenever the facebook login activity was being opened, my activity was automatically being destroyed. But i do not have such history = true statement in the manifest.
I would like to make sure that when user log in it will stay in session no matter what happens (crashed, shut down/power down/reboot, leaving the app) at same time the user info data will be sending with all the activities in the app to the webserver.
for example at the start up of the app, user login '9999' it goes to the main activity that have 5 diff. activities. user 9999 will send one activity (i.e. gps location) it will send that info to the webserver as user 9999 gps 123.234 123.123.
I want to ensure the users stays in session and also send its users data with the "activity" data sent.
I read this link
What is the most appropriate way to store user settings in Android application
I was still unable to put it together.
At the same time in the same main screen it has a logout. User needs manager approval to logout by inputting the code(i.e. 1234) to completely logout and for new user to input their id number. I want to know how to put the hardcode '1234' within the activity.
this code is my main screen after login to give you the idea
MainActivity.java
import android.app.ListActivity;
import android.content.Intent; import
android.os.Bundle; import
android.view.View; import
android.widget.ArrayAdapter; import
android.widget.ListView; import
android.widget.TextView;
public class Customer extends ListActivity {TextView selection;
CustomerListItem[] items ={
new CustomerListItem("Start Trip",StartTripActivity.class),
new CustomerListItem("Clock in",ClockinActivity.class),
new CustomerListItem("Customer Svc",CustomerSvcActivity.class),
new CustomerListItem("IndependentInspection",InspectionActivity.class),
new CustomerListItem("Pick Up", PickUpActivity.class),
new CustomerListItem("Log Out", LogoutActivity.class)};
private TextView resultsTxt;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<CustomerListItem>(
this, android.R.layout.simple_list_item_1,
items));
selection = (TextView) findViewById(R.id.selection);
}
#Override
protected void onListItemClick(ListView l, View v,
int position, long id)
{
super.onListItemClick(l, v, position, id);
final Intent intent = new Intent(this,
items[position].getActivity());
startActivityForResult(intent, position);
}
#Override
protected void onActivityResult(int requestCode, int
resultCode, Intent intent)
{
super.onActivityResult(requestCode,
resultCode, intent);
if (resultCode == RESULT_OK)
{
// Perform different actions based on from which activity is
// the application returning:
switch (requestCode)
{
case 0:
// TODO: handle the return of the StartTripActivity
break;
case 1:
// TODO: handle the return of the ClockinActivity
break;
case 2:
// TODO: handle the return of the CustomerSvcActivity
case 3:
// TODO: handle the return of the InspectionActivity
break;
case 4:
// TODO: handle the return of the PickUpActivity
break;
case 5:
// TODO: handle the return of the LogoutActivity
break;
default:
break;
}
}
else if (resultCode == RESULT_CANCELED)
{
resultsTxt.setText("Canceled");
}
} }
UPDATE:
Login.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Login extends Activity {
private EditText etUsername;
private Button btnLogin;
private Button btnCancel;
private TextView lblResult;
/** Called when the activity is first created. */
//#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
etUsername = (EditText)findViewById(R.id.username);
btnLogin = (Button)findViewById(R.id.login_button);
btnCancel = (Button)findViewById(R.id.cancel_button);
lblResult = (TextView)findViewById(R.id.result);
btnLogin.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View v) {
// Check Login
String username = etUsername.getText().toString();
if(username.equals("guest")){
lblResult.setText("Login successful.");
Intent i = new Intent(getApplicationContext(), Customer.class);
startActivity(i);
} else {
lblResult.setText("Login failed. Username doesn't match.");
}
}
});
btnCancel.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View v) {
// Close the application
finish();
}
});
}
}
The link you included shows the way to store the user's ID - you can use SharedPreferences or you can store it in the database.
You can store the "approval code" anywhere. If you want to hard-code it, you may want to put it in a "static" helper class in a public static final String variable.