Hello I have been working on an project of an android app so i used firebase android google authentication but when i launch app and login it works fine and after closing app and relaunching it app stucks on white screen please help im posting my file below
googleutil.java
public class GoogleUtil {
public static boolean getBooleanPreference(Context context, String key, boolean defaultValue) {
boolean value = defaultValue;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (preferences != null) {
value = preferences.getBoolean(key, defaultValue);
}
return value;
}
public static boolean setBooleanPreference(Context context, String key, boolean value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (preferences != null) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
return editor.commit();
}
return false;
}
}
google.java
public class Google {
private static final int RC_SIGN_IN = 10;
private GoogleApiClient mGoogleApiClient;
private FragmentActivity context;
private OnInfoLoginGoogleCallback mGoogleCallback;
public Google(FragmentActivity context, OnInfoLoginGoogleCallback mGoogleCallback) {
this.context = context;
this.mGoogleCallback = mGoogleCallback;
getConfigDefaultLogin();
}
private void getConfigDefaultLogin() {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(context.getString(R.string.default_web_client_id))
// TODO: 25-05-2017 Check With JSON default_web_client_id !!! Important
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(context)
.enableAutoManage(context /* FragmentActivity */, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
mGoogleCallback.connectionFailedApiClient(connectionResult);
}
}).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
mGoogleCallback.loginFailed();
}
}
}
public void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
context.startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void firebaseAuthWithGoogle(final GoogleSignInAccount acct) {
FirebaseAuth auth = FirebaseAuth.getInstance();
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
auth.signInWithCredential(credential).addOnCompleteListener(context, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
mGoogleCallback.loginFailed();
} else {
mGoogleCallback.getInfoLoginGoogle(acct);
}
}
});
}
public interface OnInfoLoginGoogleCallback {
void getInfoLoginGoogle(GoogleSignInAccount account);
void connectionFailedApiClient(ConnectionResult connectionResult);
void loginFailed();
}
}
and finally implement all these in main activiity
public class MainActivity extends AppCompatActivity implements View.OnClickListener, Google.OnInfoLoginGoogleCallback {
private static final String USER_ROOT = "User";
private static final String KEY_LOGIN = "Key_Login";
private Google mGoogleSign;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
setContentView(R.layout.activity_main);
TextView server_load = (TextView) findViewById(R.id.secure_key);
server_load.setText("Server Secure " + Math.random() + " Key");
firstShow();
if (GoogleUtil.getBooleanPreference(this, KEY_LOGIN, false)) {
startActivity(new Intent(this, MainActivity.class));
finish();
}
initViews();
}
private void firstShow() {
SharedPreferences sharedPreferences = getSharedPreferences("app", MODE_PRIVATE);
if (sharedPreferences.getBoolean("isFirst", true)) {
Intent intent = new Intent(MainActivity.this, OnboardingActivity.class);
startActivity(intent);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isFirst", false);
editor.apply();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mGoogleSign.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.sign_in_trigger:
signInGoogle();
break;
}
}
#Override
public void getInfoLoginGoogle(GoogleSignInAccount account) {
sendUserFirebase();
}
#Override
public void connectionFailedApiClient(ConnectionResult connectionResult) {
addProgressBar(false);
toast("Error Play Services COD" + connectionResult);
}
#Override
public void loginFailed() {
addProgressBar(false);
toast("Login Failed");
}
private void initViews() {
mGoogleSign = new Google(this, this);
Button mBtnGoogleplus = (Button) findViewById(R.id.sign_in_trigger);
mProgressBar = (ProgressBar) findViewById(R.id.sign_in_progress_bar);
mBtnGoogleplus.setOnClickListener(this);
}
private void signInGoogle() {
mGoogleSign.signIn();
addProgressBar(true);
}
private void toast(String mensage) {
Toast.makeText(this, mensage, Toast.LENGTH_LONG).show();
}
private void addProgressBar(boolean flag) {
mProgressBar.setVisibility(flag ? View.VISIBLE : View.GONE);
}
private void sendUserFirebase() {
DatabaseReference referenceUser = FirebaseDatabase.getInstance().getReference().child(USER_ROOT);
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
User user = new User();
user.setName(firebaseUser.getDisplayName());
user.setEmail(firebaseUser.getEmail());
user.setPhotoUrl(firebaseUser.getPhotoUrl() == null ? "default_uri" : firebaseUser.getPhotoUrl().toString());
user.setuId(firebaseUser.getUid());
referenceUser.child(firebaseUser.getUid()).setValue(user).addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
GoogleUtil.setBooleanPreference(MainActivity.this, KEY_LOGIN, true);
startActivity(new Intent(MainActivity.this, FeedActivity.class));
finish();
} else {
toast("Login Failed Send User, try again.");
}
addProgressBar(false);
}
});
}
}
}
and also i used User.java to send user email to database
User.java
public class User {
private String Name;
private String Email;
private String UID;
private String PhotoURL;
public User() {
}
public User(String name, String email, String uId, String photoUrl) {
this.Name = name;
this.Email = email;
this.UID = uId;
this.PhotoURL = photoUrl;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
this.Email = email;
}
public String getuId() {
return UID;
}
public void setuId(String uId) {
this.UID = uId;
}
public String getPhotoUrl() {
return PhotoURL;
}
public void setPhotoUrl(String photoUrl) {
this.PhotoURL = photoUrl;
}
}
So much code.
As I understood, you need some silent log in in background.
Here You go:
OptionalPendingResult example:
// LogIN pending result
mGoogleApiClientPendingResult = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (mGoogleApiClientPendingResult.isDone()) {
// There's immediate result available.
// Handle you result here
handleSignInResult(mGoogleApiClientPendingResult.get());
} else {
// There's no immediate result ready, displays some progress indicator and waits for the
// async callback.
mGoogleApiClientPendingResult.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(#NonNull GoogleSignInResult result) {
// Handle you result here
handleSignInResult(result);
}
});
}
Main Activity example:
private static final int RC_SIGN_IN = 28;
private static final String RC_SIGN_IN_TAG = "GoogleSignIn";
private GoogleApiClient mGoogleApiClient;
private OptionalPendingResult<GoogleSignInResult> mGoogleApiClientPendingResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Google Log In
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
// Change this for Your needs
.requestScopes(new Scope(Scopes.DRIVE_APPFOLDER), new Scope(Scopes.DRIVE_FILE), new Scope(Scopes.PROFILE))
.requestEmail()
.build();
// Build a GoogleApiClient with access to the Google Sign-In API and the
// options specified by gso.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
//
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
.addApi(Drive.API)
.addScope(Drive.SCOPE_APPFOLDER)
.addScope(Drive.SCOPE_FILE)
.build();
// LogIN pending result
mGoogleApiClientPendingResult = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (mGoogleApiClientPendingResult.isDone()) {
// There's immediate result available.
// Handle you result here
handleSignInResult(mGoogleApiClientPendingResult.get());
} else {
// There's no immediate result ready, displays some progress indicator and waits for the
// async callback.
mGoogleApiClientPendingResult.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(#NonNull GoogleSignInResult result) {
// Handle you result here
handleSignInResult(result);
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(RC_SIGN_IN_TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
if (acct != null) {
// Do your things here
nameTextView.setText(acct.getDisplayName());
emailTextView.setText(acct.getEmail());
// You can gat methods here - https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount
}
}
}
Related
After pressing verify button to send me the code the application opens browser and wait sometime. Nothing happens and no SMS sent to me and this toast appears to me. before you ask i made everything before, firebase and and SHA certificate fingerprints.
public class PhoneSingUp extends AppCompatActivity {
private FirebaseAuth auth;
TextView SignUpTXT , VerifyingTXT , ErrorTXT ;
GifImageView VerifySuccess ;
Button VerifyBTN , ContinueBTN ;
CountryCodePicker ccp;
EditText NumberEnt;
PinView VerifyPIN;
String VerifyCodeBySystem , Code , CountryCodeS ,UserEnteredNumber , PhoneNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_sing_up);
auth = FirebaseAuth.getInstance();
SignUpTXT = findViewById(R.id.SingUpTXT);
ccp = (CountryCodePicker) findViewById(R.id.ccp);
NumberEnt = (EditText) findViewById(R.id.editText_carrierNumber);
VerifyingTXT = findViewById(R.id.verifyingTXT);
ErrorTXT = findViewById(R.id.ErrorTXT);
VerifyPIN = findViewById(R.id.VerificationPIN);
VerifySuccess = findViewById(R.id.VerifySuccess);
VerifyBTN = findViewById(R.id.VerifyBTN);
VerifyBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CountryCodeS = ccp.getSelectedCountryCode();
UserEnteredNumber = NumberEnt.getText().toString();
PhoneNumber = "+" + CountryCodeS + UserEnteredNumber;
if (PhoneNumber.length() < 13){
ErrorTXT.setVisibility(View.VISIBLE);
VerifyingTXT.setVisibility(View.INVISIBLE);
}else {
if (PhoneNumber.length() == 13) {
ErrorTXT.setVisibility(View.GONE);
VerifyingTXT.setVisibility(View.VISIBLE);
sendVerificationCode(PhoneNumber);
}
}
}
});
ContinueBTN = findViewById(R.id.ContinueBTN);
ContinueBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(PhoneSingUp.this, MainActivity.class));
finish();
}
});
}
private void sendVerificationCode(String phoneNumber) {
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(phoneNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(PhoneSingUp.this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
VerifyCodeBySystem = s;
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
Code = phoneAuthCredential.getSmsCode();
if (Code != null){
VerifyPIN.setText(Code);
VerifyCode(Code);
VerifySuccess.setVisibility(View.VISIBLE);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(PhoneSingUp.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
};
private void VerifyCode(String code) {
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(VerifyCodeBySystem,code);
signInWithPhoneAuthCredential(phoneAuthCredential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
auth.signInWithCredential(phoneAuthCredential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
}
}
}
});
}
}
I want to create Phone Auth Credential like Uber, I mean when user use the app for the first time he has to complete his registration information after phone authentication then he will be able to move to DriverHome Activity, but next time he uses the authentication he will redirect to the DriverHome Activity automatically.
I've used Phone Auth Credential code and it works fine but I need to add the part is responsible for checking if the user registered before or not.
public class VerifyPhoneActivity extends AppCompatActivity {
private String verificationId;
private FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference users;
ProgressBar progressBar;
TextInputEditText editText;
AppCompatButton buttonSignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verification_code);
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressbar);
editText = findViewById(R.id.editTextCode);
buttonSignIn = findViewById(R.id.buttonSignIn);
String phoneNumber = getIntent().getStringExtra("phoneNumber");
sendVerificationCode(phoneNumber);
// save phone number
SharedPreferences prefs = getApplicationContext().getSharedPreferences("USER_PREF",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("phoneNumber", phoneNumber);
editor.apply();
buttonSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = editText.getText().toString().trim();
if (code.isEmpty() || code.length() < 6) {
editText.setError("Enter code...");
editText.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
}
private void signInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(VerifyPhoneActivity.this, DriverHomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else {
Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
private void sendVerificationCode(String number) {
progressBar.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
progressBar.setVisibility(View.GONE);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
editText.setText(code);
verifyCode(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
};
}
before onCreateView
check if sharepreference has phone number if it has then using startActivity(new Intent(this, DriverHomeActivity.class); to go directly to driverhome activity
if sharepreference has no phone number then
Save phone number in sharepreference if onComplete function of signInWithCredential return successful using isSucessful
public class VerifyPhoneActivity extends AppCompatActivity {
private String verificationId;
private FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference users;
ProgressBar progressBar;
TextInputEditText editText;
AppCompatButton buttonSignIn;
SharedPreferences prefs ;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = getApplicationContext().getSharedPreferences("USER_PREF",
Context.MODE_PRIVATE);
editor = prefs.edit();
//add this line
if(prefs.getString("phoneNumber", null) != null)
startActivity(new Intent(this, DriverHomeActivity.class));
setContentView(R.layout.activity_verification_code);
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressbar);
editText = findViewById(R.id.editTextCode);
buttonSignIn = findViewById(R.id.buttonSignIn);
String phoneNumber = getIntent().getStringExtra("phoneNumber");
sendVerificationCode(phoneNumber);
buttonSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = editText.getText().toString().trim();
if (code.isEmpty() || code.length() < 6) {
editText.setError("Enter code...");
editText.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
}
private void signInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
//insert data if task is successful
editor.putString("phoneNumber", phoneNumber);
editor.apply();
Intent intent = new Intent(VerifyPhoneActivity.this, DriverHomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else {
Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
private void sendVerificationCode(String number) {
progressBar.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
progressBar.setVisibility(View.GONE);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
editText.setText(code);
verifyCode(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
};
I am building an app where the user can store his/her usernames and passwords. The app has a simple UI. The Main thread has a list of entries, a FAB and a delete all icon on the action bar. My issue is that I am not able to edit and update existing entries.
I have the following code in the onCreate() of my MainActivity.java. When the user holds an entry, it launches the AddEditEntry.java activity. What happens here is that the launched activity does not have the existing entry data in its EditText fields:
adapter.setOnItemLongClickListener(new RecyclerViewAdapter.OnItemLongClickListener() {
#Override
public void onItemLongClick(Entries entries) {
Intent intent = new Intent(MainActivity.this, AddEditEntry.class);
intent.putExtra(AddEditEntry.EXTRA_USERNAME, entry.getUsername());
intent.putExtra(AddEditEntry.EXTRA_HINT, entry.getHint());
intent.putExtra(AddEditEntry.EXTRA_PASSWORD, entry.getPassword());
intent.putExtra(AddEditEntry.EXTRA_ID, entry.getId());
startActivityForResult(intent, EDIT_ENTRY_REQUEST);
}
});
In my AddEditEntry.java activity, I have the following code in the onClick of the save button. I am adding the new data as extras to the intent:
saveEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra(EXTRA_USERNAME, usernameEditText.getText().toString());
data.putExtra(EXTRA_HINT, hintEditText.getText().toString());
data.putExtra(EXTRA_PASSWORD, passwordEditText.getText().toString());
int id = getIntent().getIntExtra(EXTRA_ID, -1);
if(id != -1){data.putExtra(EXTRA_ID, id);}
setResult(RESULT_OK, data);
finish();
}
});
and back in my MainActivity.jav, this is my onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == ADD_ENTRY_REQUEST && resultCode == RESULT_OK){
String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);
Entries entry = new Entries(username, hint, password);
viewModel.insert(entry);
Toast.makeText(this, "Entry added!", Toast.LENGTH_SHORT).show();
}else if(requestCode == EDIT_ENTRY_REQUEST && resultCode == RESULT_OK){
int id = Objects.requireNonNull(data).getIntExtra(AddEditEntry.EXTRA_ID, -1);
String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);
if (id == -1){Toast.makeText(addEditEntry, "Something went wrong", Toast.LENGTH_SHORT).show();}
Entries entry = new Entries(username, hint, password);
entry.setId(id);
viewModel.update(entry);
Toast.makeText(this, "Entry updated", Toast.LENGTH_SHORT).show();
}
else{Toast.makeText(this, "Entry not added!", Toast.LENGTH_SHORT).show();}
}
When I run the app and try to edit an entry, the Toast message reads "Entry updated!" so it does run that code but the changes do not exist. I tried stopping the app and restarting it to refresh it but it still doesn't exist.
ViewModel.java:
public class EntryViewModel extends AndroidViewModel {
private EntryRepository repository;
private LiveData<List<Entries>> allEntries;
public EntryViewModel(#NonNull Application application) {
super(application);
repository = new EntryRepository(application);
allEntries = repository.getAllEntries();
}
public void insert(Entries entries){repository.insert(entries);}
public void update(Entries entries){repository.update(entries);}
public void delete(Entries entries){repository.delete(entries);}
public void deleteAll(){repository.deleteAllEntries();}
public LiveData<List<Entries>> getAllEntries() {return allEntries;}
}
EntryRepository.java:
public class EntryRepository {
private EntryDAO entryDAO;
private LiveData<List<Entries>> allEntries;
public EntryRepository(Application application){
EntryDatabase database = EntryDatabase.getInstance(application);
entryDAO = database.generateDao();
allEntries = entryDAO.getAllEntries();
}
public void insert(Entries entries){new InsertEntryAsyncTask(entryDAO).execute(entries);}
public void update(Entries entries){new UpdateEntryAsyncTask(entryDAO).execute(entries);}
public void delete(Entries entries){new DeleteEntryAsyncTask(entryDAO).execute(entries);}
public void deleteAllEntries(){new DeleteAllEntriesAsyncTask(entryDAO).execute();}
public LiveData<List<Entries>> getAllEntries(){return allEntries;}
public static class InsertEntryAsyncTask extends AsyncTask<Entries, Void, Void>{
private EntryDAO entryDAO;
private InsertEntryAsyncTask(EntryDAO entryDAO){this.entryDAO = entryDAO;}
#Override
protected Void doInBackground(Entries... entries) {
entryDAO.insert(entries[0]);
return null;
}
}
public static class UpdateEntryAsyncTask extends AsyncTask<Entries, Void, Void>{
private EntryDAO entryDAO;
private UpdateEntryAsyncTask(EntryDAO entryDAO){
this.entryDAO = entryDAO;
}
#Override
protected Void doInBackground(Entries... entries) {
entryDAO.update(entries[0]);
return null;
}
}
public static class DeleteEntryAsyncTask extends AsyncTask<Entries, Void, Void>{
private EntryDAO entryDAO;
private DeleteEntryAsyncTask(EntryDAO entryDAO){this.entryDAO = entryDAO;}
#Override
protected Void doInBackground(Entries... entries) {
entryDAO.delete(entries[0]);
return null;
}
}
public static class DeleteAllEntriesAsyncTask extends AsyncTask<Void, Void, Void>{
private EntryDAO entryDAO;
private DeleteAllEntriesAsyncTask(EntryDAO entryDAO){this.entryDAO = entryDAO;}
#Override
protected Void doInBackground(Void... voids) {
entryDAO.deleteAllEntries();
return null;
}
}
}
EntryDAO.java:
#Dao
public interface EntryDAO {
#Insert
void insert(Entries entries);
#Update
void update(Entries entries);
#Delete
void delete(Entries entries);
#Query("DELETE FROM entries_table")
void deleteAllEntries();
#Query("SELECT * FROM entries_table")
LiveData<List<Entries>> getAllEntries();
}
Entries.java:
#Entity(tableName = "entries_table")
public class Entries {
#PrimaryKey(autoGenerate = true)
private int id;
private String username, hint, password;
public Entries(String username, String hint, String password){
this.username = username;
this.hint = hint;
this.password = password;
}
public Entries(){}
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getUsername() {return username;}
public void setUsername(String username) {this.username = username;}
public String getHint() {return hint;}
public void setHint(String hint) {this.hint = hint;}
public String getPassword() {return password;}
public void setPassword(String password) {this.password = password;}
}
This is the onCreate() of my AddEditEntry.java class. I've added the following Toast messages to see if it was receiving the data at all and turns out it doesn't. The Toast messages were empty:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addedit_entry);
usernameEditText = findViewById(R.id.username_field);
passwordEditText = findViewById(R.id.password_field);
hintEditText = findViewById(R.id.hint_field);
passwordABCD = findViewById(R.id.upp_checkbox);
passwordabcd = findViewById(R.id.low_checkbox);
password0123 = findViewById(R.id.num_checkbox);
passwordSymbols = findViewById(R.id.sym_checkbox);
radio4 = findViewById(R.id.four);
radio8 = findViewById(R.id.eight);
radio12 = findViewById(R.id.twelve);
radio16 = findViewById(R.id.sixteen);
Button generatePassword = findViewById(R.id.btn_password_generate);
Button saveEntry = findViewById(R.id.btn_save);
Intent intent = getIntent();
if(intent.hasExtra(EXTRA_ID)){
setTitle("Edit Entry");
usernameEditText.setText(Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_USERNAME));
passwordEditText.setText(Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_PASSWORD));
hintEditText.setText(Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_HINT));
Toast.makeText(this, "Info Received!!!", Toast.LENGTH_SHORT).show();
Toast.makeText(this, Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_USERNAME), Toast.LENGTH_SHORT).show();
Toast.makeText(this, Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_PASSWORD), Toast.LENGTH_SHORT).show();
Toast.makeText(this, Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_HINT), Toast.LENGTH_SHORT).show();
}
else{setTitle("Add Entry");}
generatePassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {passwordEditText.setText(generatedPassword());}});
saveEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra(EXTRA_USERNAME, usernameEditText.getText().toString());
data.putExtra(EXTRA_HINT, hintEditText.getText().toString());
data.putExtra(EXTRA_PASSWORD, passwordEditText.getText().toString());
int id = getIntent().getIntExtra(EXTRA_ID, -1);
if(id != -1){data.putExtra(EXTRA_ID, id);}
setResult(RESULT_OK, data);
finish();
}
});
}
Do it like this
In your MainActivity.java
....
....
adapter.setOnItemLongClickListener(new RecyclerViewAdapter.OnItemLongClickListener() {
#Override
public void onItemLongClick(Entries entries) {
entry = entries; // this is very important, entry holds the current edited item
Intent intent = new Intent(MainActivity.this, AddEditEntry.class);
intent.putExtra(AddEditEntry.EXTRA_USERNAME, entry.getUsername());
intent.putExtra(AddEditEntry.EXTRA_HINT, entry.getHint());
intent.putExtra(AddEditEntry.EXTRA_PASSWORD, entry.getPassword());
// no need to pass the id, it's a autogenerated field
// intent.putExtra(AddEditEntry.EXTRA_ID, entry.getId());
startActivityForResult(intent, EDIT_ENTRY_REQUEST);
}
});
....
...
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == ADD_ENTRY_REQUEST && resultCode == RESULT_OK){
...
...
} else if(requestCode == EDIT_ENTRY_REQUEST && resultCode == RESULT_OK) {
// in an Edit operation, id should not be modified, so, no need to pass this parameter
// int id =
// Objects.requireNonNull(data).getIntExtra(AddEditEntry.EXTRA_ID, -1);
String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);
// entry already exists, so, no need to create a new one
//Entries entry = new Entries(username, hint, password);
//entry.setId(id);
entry.setUsername(username);
entry.setPassword(password);
entry.setHint(hint);
viewModel.update(entry);
Toast.makeText(this, "Entry updated", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Entry not added!", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
Other remarks...
In your RecyclerViewAdapter.java
// This is not needed. Your list is already created in your Room query
//private List<Entries> entries = new ArrayList<>();
private List<Entries> entries;
In your MainActivity.java
// This is not needed
// AddEditEntry addEditEntry;
....
....
// addEditEntry = new AddEditEntry();
I integrated Paypal in my android app in sandbox mode and everything worked perfectly fine. Now I switched to live mode and changed the client ID in my app as well.
Now this error is displayed when I tried to make a test purchase:
"Payment to this merchant is not allowed (invalid clientid)"
I don't know what to do. I changed the client id in every place from the sandbox id to the live id.
My class where Paypal is initialized when click on a button:
public class EssenActivity extends AppCompatActivity {
private static final String TAG = "Log Essen Activity";
private String kochuiD, preis, preis_ohne_euro, AnfragePortionenS, ungefahreAnkunftS, preisRe;
private EditText anzahlPortionen;
private TextView ungefähreAnkunft;
private Button essenBesätigenBtn;
private FirebaseFirestore firebaseFirestore;
private TextView preisRechner;
private FirebaseAuth mAuth;
public static final int PAYPAL_REQUEST_CODE = 7171;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(PayPalConfiguration.ENVIRONMENT_SANDBOX)
.clientId(Config.PAYPAL_CLIENT_ID);
private String amount, amountOhneEuro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_essen);
essenBesätigenBtn = findViewById(R.id.essenBestätigen);
essenBesätigenBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
processPayment();
}
}
}
private void processPayment() {
amount = preisRechner.getText().toString();
amountOhneEuro = amount.replace("€", "");
PayPalPayment payPalPayment = new PayPalPayment(new BigDecimal(String.valueOf(amountOhneEuro)), "EUR",
"Bezahle das Essen", PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(EssenActivity.this, PaymentActivity.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payPalPayment);
startActivityForResult(intent, PAYPAL_REQUEST_CODE);
}
#Override
//
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == PAYPAL_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
PaymentConfirmation confirmation = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirmation != null) {
try {
String paymentDetails = confirmation.toJSONObject().toString(4);
startActivity(new Intent(EssenActivity.this, PaymentDetails.class)
.putExtra("PaymentDetails", paymentDetails)
.putExtra("PaymentAmount", amountOhneEuro)
.putExtra("Koch Uid", kochuiD)
);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.d(TAG, "onActivityResult: wurde gecancelt");
}
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID)
Toast.makeText(EssenActivity.this, "Ungültig", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
EssenActivity.this.stopService(new Intent(EssenActivity.this, PayPalService.class));
super.onDestroy();
}
}
My Config class:
public class Config {
public static final String PAYPAL_CLIENT_ID ="MY CLIENT ID";
}
My Paymentdetails class:
public class PaymentDetails extends AppCompatActivity {
private static final String TAG = "PAYMENT";
private TextView txtid, txtAmount, txtStatus;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth mAuth;
private DocumentReference docIdRef;
private String kochUid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_details);
txtid = findViewById(R.id.txtId);
txtAmount = findViewById(R.id.txtAmount);
txtStatus = findViewById(R.id.txtStatus);
Intent intent = getIntent();
try {
JSONObject jsonObject = new JSONObject(intent.getStringExtra("PaymentDetails"));
showDetails(jsonObject.getJSONObject("response"), intent.getStringExtra("PaymentAmount"));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showDetails(JSONObject response, String paymentAmount) {
try {
firebaseFirestore = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
String uid = mAuth.getCurrentUser().getUid();
if (response.getString("state").equals("approved")) {
DocumentReference documentReference = firebaseFirestore.collection("essen_aktiv_anfrage").document(uid);
Map<String, String> anfrageMap = new HashMap<>();
anfrageMap.put("Id", response.getString("id"));
anfrageMap.put("Status", response.getString("state"));
anfrageMap.put("Betrag", paymentAmount + "€");
//NEU
anfrageMap.put("Anfrage User", uid);
anfrageMap.put("Koch Uid", kochUid);
documentReference.set(anfrageMap, SetOptions.merge())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Intent intent = new Intent(PaymentDetails.this, MainActivity.class);
intent.putExtra("Bezahlung war erfolgreich", "approved");
Toast.makeText(PaymentDetails.this, "Bezahlung war erfolgreich", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
} else{
Toast.makeText(PaymentDetails.this, "Bezahlung war nicht erfolgreich", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Any help is appreciated. Thank you very much.
Authorization defaults to sandbox unless explicitly set to "live". It needs to be set within the PayPalConfiguration which is used in creation of the oAuth token, and the creation of the APIContext which is used to call the PayPal service.
I had been getting the same error within a live environment, despite it working in sandbox. It is therefore likely that you have missed something.
Change ENVIRONMENT_SANDBOX to ENVIRONMENT_PRODUCTION
I am trying to handle Facebook and Google login into a single activity
The google login works but Facebook login is not showing the request permission dialog. When I click login with Facebook button I expect to see permissions dialog for public profile and email. Although the dialog does not appear it seems that I am signed in as Login with Facebook changes to Logout. Is there any better way of doing this?
public class LoginActivity extends AppCompatActivity {
private static final String TAG = LoginActivity.class.getSimpleName();
private static final int RC_SIGN_IN = 1;
private GoogleApiClient googleClient;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
SignInButton googleButton = (SignInButton)findViewById(R.id.google_button);
LoginButton facebookBtn = (LoginButton)findViewById(R.id.fb_login_button);
Button emailButton = (Button)findViewById(R.id.email_button);
googleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});
initGoogleSignIn();
initFacebookSignIn(facebookBtn);
}
private boolean isLoggedInByFacebook(){
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}
private void initGoogleSignIn(){
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
googleClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(googleClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done" and the GoogleSignInResult will be available instantly.
Log.d("TAG", "Got cached sign-in");
GoogleSignInResult result = opr.get();
finish();
}
}
private void initFacebookSignIn(LoginButton facebookBtn){
if(isLoggedInByFacebook()) {
finish();
}else{
callbackManager = CallbackManager.Factory.create();
facebookBtn.setReadPermissions(Arrays.asList(
"public_profile","email"));
// Callback registration
facebookBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
loginResult.getAccessToken().getUserId();
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
Log.i("Response",response.toString());
String email = response.getJSONObject().getString("email");
String name = response.getJSONObject().getString("name");
finish();
}catch (JSONException e){
Log.e(TAG,"Error getting facebook email", e);
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name,email");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
Log.e(TAG,"Error in facebook sign in", exception);
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
api.loginGoogle(acct.getIdToken()).subscribe(new Action1<User>() {
#Override
public void call(User user) {
api.getWeather(-31.0, 115.0).subscribe(new Action1<WeatherResponse>() {
#Override
public void call(WeatherResponse weatherResponse) {
}
});
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
System.out.println(throwable);
}
});
} else {
System.out.println(result.getStatus());
}
}else { //facebook
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
}
try this:
Declare the variables:
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
com.facebook.Profile profile;
private ProfileTracker mProfileTracker;
in your onCreate() method..
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
updateWithToken(AccessToken.getCurrentAccessToken());
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
updateWithToken(newToken);
}
};
accessTokenTracker.startTracking();
Now in updateWithToken() method
private void updateWithToken(AccessToken currentAccessToken) {
if (currentAccessToken != null) {
LoginManager.getInstance().logOut();
} else {
}
}
Now in the callback manager you have to track user's current profile
List<String> permissionNeeds = Arrays.asList(
"public_profile", "email", "user_birthday", "user_friends");
loginButton.setReadPermissions(permissionNeeds);
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("Success", "Login");
try {
if (Profile.getCurrentProfile() == null) {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile_old, Profile profile_new) {
// profile2 is the new profile
profile = profile_new;
if (profile_new != null)
Log.v("facebook - profile", profile_new.getFirstName());
mProfileTracker.stopTracking();
}
};
mProfileTracker.startTracking();
} else {
profile = Profile.getCurrentProfile();
if (profile != null)
Log.v("facebook - profile", profile.getFirstName());
}
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Application code
try {
Log.v("FACEBOOK LOGIN", response.toString());
fb_id = object.getString("id");
fb_name = object.getString("name");
fb_gender = object.getString("gender");
fb_email = object.getString("email");
fb_birthday = object.getString("birthday");
} catch (Exception e) {
e.printStackTrace();
Log.d("Error", e.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday,picture.type(small)");
request.setParameters(parameters);
request.executeAsync();
} catch (Exception e) {
Log.d("ERROR", e.toString());
}
}
#Override
public void onCancel() {
Log.d("FACEBOOK ERRROR", "cancelled");
}
#Override
public void onError(FacebookException exception) {
Log.d("FACEBOOK ERRROR", exception.toString());
});
If you don't mind using a WebView then try CloudRail for social login, it's very simple to use.
https://github.com/CloudRail/cloudrail-si-android-sdk