My app goes straight into the MainActivity - java

I am creating an app just like WhatsApp but I have a problem. The app is suppose to go into the LoginActivity but instead it goes straight into the MainActivity without me logging in.
I tried changing the launcher scene in android manifest and the same thing is happening. I tried adding mAuth.signOut(); at the end of both of my loadingBar.dismiss();. I tried changing this
SendUserToMainActivity(); to this SendUserToRegisterActivity();. I deleted all of the accounts in the firebase database also.
LoginActivity:
private FirebaseUser currentUser;
private FirebaseAuth mAuth;
private ProgressDialog loadingBar;
private Button LoginButton, PhoneLoginButton;
private EditText UserEmail, UserPassword;
private TextView NeedNewAccountLink, ForgetPasswordLink;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
InitializeFields();
NeedNewAccountLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendUserToRegisterActivity();
}
});
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AllowUserToLogin();
}
});
}
private void AllowUserToLogin() {
String email = UserEmail.getText().toString();
String password = UserPassword.getText().toString();
if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter your email", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter your password", Toast.LENGTH_SHORT).show();
}
else{
loadingBar.setTitle("Logging In");
loadingBar.setMessage("Please wait...");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
SendUserToMainActivity();
Toast.makeText(LoginActivity.this, "Logged in successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else{
String message = task.getException().toString();
Toast.makeText(LoginActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
private void InitializeFields() {
LoginButton = (Button) findViewById(R.id.login_button);
PhoneLoginButton = (Button) findViewById(R.id.phone_login_button);
UserEmail = (EditText) findViewById(R.id.login_email);
UserPassword = (EditText) findViewById(R.id.login_password);
NeedNewAccountLink = (TextView) findViewById(R.id.need_new_account_link);
ForgetPasswordLink = (TextView) findViewById(R.id.forget_password_link);
loadingBar = new ProgressDialog(this);
}
#Override
protected void onStart() {
super.onStart();
if (currentUser != null){
SendUserToMainActivity();
}
}
private void SendUserToMainActivity() {
Intent loginIntent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(loginIntent);
}
private void SendUserToRegisterActivity() {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(registerIntent);
}
AndroidManifest:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name=".RegisterActivity" />
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity"/>
</application>

Clear the cache of your app once, change launcher from Main Activity to Login Activity Rebuild the app, and onStart of the LoginActivity you're getting the user logged in that's why he's always sending you to mainActivity,
It doesn't matter if you have removed all users in firebase you'll get auth until you'll clear the cache. Try this solution and let me know if it works for you.

In AllowUserToLogin() you must place a
return;
statement after you show the Toast with the error message.
Also remove the else after checking the password:
if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter your email", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter your password", Toast.LENGTH_SHORT).show();
return;
}
loadingBar.setTitle("Logging In");
..................................
Edit
After you posted the manifest, I see that your LAUNCHER activity is MainActivity although you mention in your question that:
I tried changing the launcher scene in android manifest and the same
thing is happening.
You must also change the LAUNCHER activity to LoginActivity

Change your manifest like this.
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name=".RegisterActivity" />
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity"/>
When opens login activity, check if user already logged send him into MainAcitivty.
Also that will be good if you will have a method, where you will check text fields verification.
Something like this:
public boolean verified() {
if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter your email", Toast.LENGTH_SHORT).show();
return false;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter your password",
Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
And do like this:
if(verified){
loadingBar.setTitle("Logging In");
loadingBar.setMessage("Please wait...");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
//And so on.
}

Related

When starting Android studio project, intent filter does not start from given page

I want the first LoginActivity.java page to open in my project, but AnasayfaActivity.java opens. I couldn't solve the problem. I use Android Studio. I am learning Android, and I would be glad if you help. I shared LoginActivity and AndroidManifest pages. When the application is opened for the first time, the Home Activity opens, when I go back, it goes to the LoginActivity.java page.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.geziproject">
>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Geziproject">
<activity android:name=".AnasayfaActivity"/>
<activity android:name=".MainActivity2" />
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:theme="#style/Theme.Geziproject.NoActionBar">
</activity>
<activity android:name=".bos" />
<activity android:name=".kayitol" />
<activity android:name=".kullanicigiris" />
</application>
</manifest>
LoginActivity.java:
public class LoginActivity extends AppCompatActivity {
private Button signInButton;
private GoogleSignInClient mGoogleSignInClient;
private FirebaseAuth mAuth;
private Button signout;
Button btngiris;
Button btnkayit;
private EditText txtad;
private EditText txtemail;
private EditText txtsifre;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button btngiris = findViewById(R.id.btngiris);
Button btnkayit = findViewById(R.id.btnkayit);
txtemail = findViewById(R.id.txtemail);
txtsifre = findViewById(R.id.txtsifre);
signInButton = findViewById(R.id.signin);
mAuth = FirebaseAuth.getInstance();
// signout = findViewById(R.id.sign_out);
btngiris.setOnClickListener(v -> {
String email=txtemail.getText().toString();
String pwd= txtsifre.getText().toString();
if(email.isEmpty()){
txtemail.setError("Lütfen email giriniz");
txtemail.requestFocus();
}
else if(pwd.isEmpty()){
txtsifre.setError("Lütfen şifre giriniz");
txtsifre.requestFocus();
}
else if(email.isEmpty() && pwd.isEmpty())
{
Toast.makeText(LoginActivity.this,"Bu alanlar boş bırakılamaz",Toast.LENGTH_LONG).show();
}
else if(!(email.isEmpty() && pwd.isEmpty())){
mAuth.signInWithEmailAndPassword(email,pwd).addOnCompleteListener(LoginActivity.this, task -> {
if(!task.isSuccessful()){
Toast.makeText(LoginActivity.this,"Giriş başarısız ,tekrar deneyiniz",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(LoginActivity.this,"Giriş başarılı",Toast.LENGTH_LONG).show();
txtemail.setText("");
txtsifre.setText("");
startActivity(new Intent(LoginActivity.this,AnasayfaActivity.class));
}
});
}
else{
Toast.makeText(LoginActivity.this,"Hata oluştu",Toast.LENGTH_LONG).show();
}
});
btnkayit.setOnClickListener(v -> {
Intent i= new Intent(LoginActivity.this,kayitol.class);
startActivity(i);
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("1088981466528-8pkjha8350r2uniqg2425nv5itvgpvr7.apps.googleusercontent.com")
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signInButton.setOnClickListener(v -> signIn());
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
startActivity(new Intent(LoginActivity.this, AnasayfaActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, 100);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
//handleSignInResult(task);
if (task.isSuccessful()) {
String s = "Google sign in Successful";
displayToast(s);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
Toast.makeText(getApplicationContext(), "giriş başarılı", Toast.LENGTH_LONG).show();
if (account != null) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(getApplicationContext(), AnasayfaActivity.class);
startActivity(intent);
}
}
});
}
} catch (ApiException e) {
e.printStackTrace();
}
}
}
}
private void displayToast(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
}
As you set the launch activity in mainfest to LoginActivity, the app starts normally with the LoginActivity, but before the LoginActivity is resumend (i.e. shown on the screen) you added a condition in onCreate() method to launch the AnasayfaActivity as below:
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
startActivity(new Intent(LoginActivity.this, AnasayfaActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
If the user is not null (i.e. already logged-in), then the app goes directly to AnasayfaActivity activity without showing the LoginActivity to the user.
And the reason when you go back; the app go to the LoginActivity, because the LoginActivity is still in the back stack. If you want to remove the LoginActivity from the back stack then add Intent.FLAG_ACTIVITY_CLEAR_TOP to the intent:
startActivity(new Intent(LoginActivity.this, AnasayfaActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));

Firebase Database not fetching data from Firebase Database Reference

Everything is working fine but DatabaseReference is not fetching data, it's like just ignoring my code to run and like my internet is not working please help i'm new here in this community below are my codes and images.
Previously it was working, but as i just changed some code to make only currentVersion >= vCode so that user can continue even if the value in database is < currentVersion but, after building it my app was not fetching data from firebase and the i tried to uninstall it, installed again from play store the older version it also was not fetching data please help. I don't know what wrong i did. Thus i am planning to install ParrotOS so maybe then it'll work but it's better to ask first from the experts
firebase database image
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView appName;
FirebaseUser firebaseUser;
String currentVersionName;
long currentVersionCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appName = findViewById(R.id.appName);
currentVersionName = BuildConfig.VERSION_NAME;
currentVersionCode = BuildConfig.VERSION_CODE;
animateAppName();
netConn();
FirebaseAuth.getInstance();
}
public void applyScreenChange(){
String sharedPerfId = "MyAppPref";
SharedPreferences sharedPreferences = getSharedPreferences(sharedPerfId,0);
boolean isAdvertiserLoggedIn = sharedPreferences.getBoolean("isAdvertiserLoggedIn",false);
boolean isCreatorLoggedIn = sharedPreferences.getBoolean("isCreatorLoggedIn",false);
if (isAdvertiserLoggedIn){
skipSetupToAdvertiser();
}
else if (isCreatorLoggedIn){
skipSetupToCreator();
}
else {
newActivity();
}
}
public void animateAppName(){
appName.setTranslationY(-1000f);
appName.animate().translationYBy(1000f).setDuration(500);
}
public void netConn(){
ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
assert connectivityManager != null;
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo == null || !networkInfo.isConnected() || !networkInfo.isAvailable()){
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("No Internet Connection");
alertDialog.setMessage("Connect to Network and Then try again");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.super.onBackPressed();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Retry", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
netConn();
}
});
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}else {
// Check older version
// applyScreenChange();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Version");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String vName = (String) snapshot.child("latestVersionName").getValue();
long vCode = (long) snapshot.child("latestVersionCode").getValue();
if (currentVersionName.equals(vName) && currentVersionCode >= vCode){
applyScreenChange();
// TODO: 16-08-2020 add condition to open app if version is higher
}else {
Toast.makeText(MainActivity.this, "Old Version", Toast.LENGTH_SHORT).show();
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("You're on Older Version");
alertDialog.setMessage("This Version is no more supported, Kindly update your App to Continue");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.super.onBackPressed();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.app_link))));
Toast.makeText(MainActivity.this, "Kindly Search Sponso on PlayStore and Update", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
public void newActivity(){
Intent intent = new Intent(MainActivity.this, AdvertiserCreatorChooser.class);
startActivity(intent);
finish();
}
public void skipSetupToAdvertiser(){
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser!=null) {
Intent intent = new Intent(MainActivity.this, AdvertiserHome.class);
startActivity(intent);
finish();
}else{
Intent intent = new Intent(MainActivity.this, AdvertiserLoginRegister.class);
startActivity(intent);
finish();
}
}
public void skipSetupToCreator(){
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser!=null) {
Intent intent = new Intent(MainActivity.this, CreatorHome.class);
startActivity(intent);
finish();
}else {
Intent intent = new Intent(MainActivity.this, CreatorLoginRegister.class);
startActivity(intent);
finish();
}
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.webroose.sponso">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:allowBackup="true"
android:theme="#style/AppTheme">
<activity android:name=".Advertiser.AdvertiserCampaignUpdate"/>
<activity android:name=".Advertiser.ui.main.AdvertiserSettings" />
<activity android:name=".Creator.CreatorRecentlyChat" />
<activity android:name=".Advertiser.AdvertiserRecentlyChat" />
<activity android:name=".Advertiser.AdvertiserChatActivity" />
<activity android:name=".Creator.CreatorChatActivity" />
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="#string/app_id" />
<activity android:name=".Creator.CreatorUserDetails" />
<activity android:name=".Creator.CreatorList" />
<activity android:name=".Common.AboutUs" />
<activity
android:name=".AdvertiserHome"
android:label="#string/title_activity_advertiser_home"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Advertiser.AdvertiserLoginRegister"
android:label="#string/title_activity_advertiser_login_register"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".Common.PrivacyPolicy" />
<activity android:name=".Common.ChangePassword" />
<activity android:name=".Creator.CreatorSettings" />
<activity android:name=".Common.ChangeEmail" />
<activity android:name=".Advertiser.AdvertiserUserDetails" />
<activity android:name=".Advertiser.AdvertiserList" />
<activity
android:name=".CreatorHome"
android:label="#string/title_activity_creator_home"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Creator.CreatorLoginRegister"
android:label="#string/title_activity_creator_login_register"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".AdvertiserCreatorChooser" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
</application>
</manifest>
dependency
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation 'com.google.android.material:material:1.2.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'com.google.firebase:firebase-database:19.4.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.navigation:navigation-fragment:2.3.0'
implementation 'androidx.navigation:navigation-ui:2.3.0'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'com.google.firebase:firebase-auth:19.3.2'
implementation 'com.google.firebase:firebase-database:19.4.0'
implementation 'com.firebaseui:firebase-ui-database:6.2.0'
implementation 'com.google.android.gms:play-services-ads:19.3.0'
implementation 'com.android.support:multidex:2.0.0'
implementation 'com.google.firebase:firebase-analytics:17.5.0'
implementation 'com.google.firebase:firebase-messaging:20.2.4'
implementation 'com.facebook.android:audience-network-sdk:5.10.1'
}
Change
DatabaseReference databaseReference =FirebaseDatabase.getInstance().getReference("Version");
To
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Version");
And the actual problem was with Firebase Database
Check below image with firebase database

How do you make Android redirect to a specific activity after pressing the email link?

I need my Android application to redirect to a specific activity upon pressing the email link using Firebase authentication.
My application currently redirects to the launcher activity. I would like it to redirect to the profile activity but am using the username activity for this example. Any help is appreciated.
My Code:
MainActivity.java
#Override
public void onEmailReadListener(String email) {
ActionCodeSettings actionCodeSettings = buildActionCodeSettings();
sendSignInLink(email, actionCodeSettings);
//StartActivityForResult(true, actionCodeSettings);
}
//Email Verification
public ActionCodeSettings buildActionCodeSettings() {
// [START auth_build_action_code_settings]
ActionCodeSettings actionCodeSettings =
ActionCodeSettings.newBuilder()
// URL you want to redirect back to. The domain (www.example.com) for this
// URL must be whitelisted in the Firebase Console.
.setUrl("https://example.page.link/nYJz")
// This must be true
.setHandleCodeInApp(true)
.setAndroidPackageName(
"com.example.AppName",
false, /* installIfNotAvailable */
"23" /* minimumVersion */)
.build();
// [END auth_build_action_code_settings]
return actionCodeSettings;
}
public void sendSignInLink(String email, ActionCodeSettings actionCodeSettings) {
// [START auth_send_sign_in_link]
FirebaseAuth auth = FirebaseAuth.getInstance();
auth.sendSignInLinkToEmail(email, actionCodeSettings)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email sent.");
}
else{
Log.e(TAG, "onComplete: Failed=" + task.getException().getMessage());
}
}
});
// [END auth_send_sign_in_link]
}
AndroidManifest.xml
<activity android:name=".Activities.Login.UserCreation.UsernameActivity">
<intent-filter android:autoVerify="true">
<category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.DEFAULT"/>
<action android:name="android.intent.action.VIEW"/>
<data android:host="atlas-cd0f2.firebaseapp.com/" android:scheme="https" />
<data android:host="https://example.page.link/" android:scheme="https" />
</intent-filter>
</activity>
UsernameActivity
public class UsernameActivity extends AppCompatActivity {
//create username for account
//TODO disable back; create cancel button
//TODO make ender button press next!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Button next;
TextInputEditText username;
Intent nextPass;
String mUsername;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_username);
next = findViewById(R.id.nextOne);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkUsername() == true) {
mUsername = username.getText().toString();
nextPass.putExtra("username", mUsername);
startActivity(nextPass);
}
else {
Toast.makeText(getApplicationContext(), "Invalid Username", Toast.LENGTH_LONG).show();
}
}
});
nextPass = new Intent(UsernameActivity.this, PasswordActivity.class);
}
public boolean checkUsername() {
Log.v("user0", "0");
username = findViewById(R.id.username);
int j;
String strUsername = username.getText().toString();
Log.v("user1", strUsername);
if (strUsername.length() >= 6 && strUsername.length() <= 30){
Log.v("user2", "2");
char[] chUsername = strUsername.toCharArray();
char[] badChar = {'&', '=', '_', '\'', '-', '+', ',', '<', '>', '.'};
for (int i = 0; i < chUsername.length; i++) {
Log.v("user3", String.valueOf(i));
Log.v("user3.2", String.valueOf(chUsername[i]));
for (j = 0; j < badChar.length; j++) {
Log.v("user3.5", String.valueOf(j));
if (chUsername[i] == badChar[j]) {
Log.v("user4", String.valueOf(j));
Log.v("user5", String.valueOf(i));
j = 0;
Log.v("user6", String.valueOf(j));
return false;
}
}
}
return true;
}
Log.v("user8", "8");
return false;
}
}
StartActivity in AndroidManifest This is the activity with the launcher designation
<activity android:name=".Activities.Login.StartActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
The data tags in the Manifest should look like this
<data
android:host="example.page.link"
android:scheme="https" />
<data
android:host="atlas-cd0f2.firebaseapp.com"
android:scheme="https" />
You have to make sure that the android:host exactly matches the host, without any scheme (such as https) or prefix (such as /something).

App login using Facebook is not working in development! It just loading and Closed- Android Studio

I have implemented an app and I have used facebook login to it. Application is running without crashing but facebook login is not working. When I open up the app and click the facebook login button it will show a progress bar and it will be disappeared immediately without doing anything. I have got the following error in the logcat.
2019-08-29 12:45:24.290 19304-19328/com.appic.testfbauth
E/GraphResponse:
{
HttpStatus: 400,
errorCode: 100,
subErrorCode: 33,
errorType: GraphMethodException,
errorMessage: Unsupported get request. Object with ID '742177629556035' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api
}
refer below for work I have done.
public class MainActivity extends AppCompatActivity {
private LoginButton loginButton;
private CircleImageView circleImageView;
private TextView txtName, txtEmail;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FacebookSdk.sdkInitialize(getApplicationContext());
loginButton = findViewById(R.id.login_button);
circleImageView = findViewById(R.id.profile_pic);
txtName = findViewById(R.id.profile_name);
txtEmail = findViewById(R.id.profile_email);
checkLoginStatus();
callbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
AccessTokenTracker tokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if(currentAccessToken == null) {
txtEmail.setText("");
txtName.setText("");
circleImageView.setImageResource(0);
Toast.makeText(MainActivity.this, "User Logged Out!", Toast.LENGTH_SHORT).show();
}
else loadUser(currentAccessToken);
}
};
private void loadUser(AccessToken newAccessToken) {
GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String email = object.getString("email");
String id = object.getString("id");
String image_url = "https://graph.facebook.com/"+ id +"/picture?type=normal";
txtEmail.setText(email);
txtName.setText(first_name +" "+ last_name);
RequestOptions requestOptions = new RequestOptions();
requestOptions.dontAnimate();
Glide.with(MainActivity.this).load(image_url).into(circleImageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name,last_name,email,id");
request.setParameters(parameters);
request.executeAsync();
}
private void checkLoginStatus() {
if(AccessToken.getCurrentAccessToken() != null) {
loadUser(AccessToken.getCurrentAccessToken());
}
}
}
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id"/>
<meta-data android:name="com.facebook.sdk.ApplicationName"
android:value="#string/app_name"/>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
</application>
I just want to integrate the facebook login and get email, name, image url, id.
I have no enough replication for comment so i paste answer. You just give me answers to my below questions.
You test your app in real device or emulator.?
Get the permission for image?
Please check your browser any facebook account already login there?
If you not getting email and name please try below code:
JSONObject res;
res = new JSONObject(json_object.toString());
String id = res.getString("id");
String name = res.getString("name");
String email = res.getString("email");
Update:
Please Uninstalled FB app from your device and try to login with FB in your app it's working fine.
Update 25/11/209
Also please update your hash key - Please follow this answer
After that convert hash key into base 64 - tomeko.net

Google Play Services - Activity Recognition Freezes After a Few Results

I have tried to simplify my code as much as possible, basically hte issue is that the ActivityRecognitionIntentService appears to be called a couple of times, then stalls out. It appears to be related to the requestCode in the PendingIntent, but I am not sure, can someone please advise me as to what is going wrong? Thanks.
Dashboard.java
public class Dashboard extends Activity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {
private BroadcastReceiver receiver;
private TextView tvActivity;
private GoogleApiClient mGoogleApiClient;
//String Locationp = "null";
//private LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
tvActivity = (TextView) findViewById(R.id.tvActivity);
int resp =GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resp == ConnectionResult.SUCCESS){
// Create a GoogleApiClient instance
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(ActivityRecognition.API)
//.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
else{
Toast.makeText(this, "Please install Google Play Service.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnected(Bundle arg0) {
Intent i = new Intent(this, ActivityRecognitionIntentService.class);
PendingIntent mActivityRecognitionPendingIntent = PendingIntent.getService(this, 2000, i, PendingIntent.FLAG_UPDATE_CURRENT);
Log.e("MAIN", "Connected to ActRec");
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient, 1000, mActivityRecognitionPendingIntent);
}
#Override
public void onConnectionSuspended(int arg0) {
Log.e("MAIN", "Connection suspended to ActRec");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e("MAIN", "Not Connected to ActRec");
}
ActivityRecognitionIntentService.java
public class ActivityRecognitionIntentService extends IntentService {
public ActivityRecognitionIntentService() {
super("ActivityRecognitionIntentService");
}
protected void onHandleIntent(Intent intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
DetectedActivity mostProbAct = result.getMostProbableActivity();
int confidence = mostProbAct.getConfidence();
String mostProbActName = getActivityName(mostProbAct.getType());
Intent i = new Intent("com.xxx.abc.ACTIVITY_RECOGNITION_DATA");
i.putExtra("act", mostProbActName);
i.putExtra("confidence", confidence);
Log.e("ARS", mostProbActName + "," + confidence);
//sendBroadcast(i);
} else
Log.e("ARS", "Intent had no ActivityRecognitionData");
}
private String getActivityName(int activityType) {
switch (activityType) {
case DetectedActivity.IN_VEHICLE:
return "in_vehicle";
case DetectedActivity.ON_BICYCLE:
return "on_bicycle";
case DetectedActivity.ON_FOOT:
return "on_foot";
case DetectedActivity.STILL:
return "still";
case DetectedActivity.UNKNOWN:
return "unknown";
case DetectedActivity.TILTING:
return "tilting";
}
return "unknown";
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tigerblood.com.node" >
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<service android:enabled="true" android:name="com.xxx.abc.ActivityRecognitionIntentService"></service>
<activity
android:name="com.tigerblood.node.Dashboard"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Categories

Resources