Firebase Auth causing Fatal exeception: (java.lang.NullPointerException) - firebase

This worked perfectly fine from the time I created the project. But suddenly is starts crashing. The sign up activity works fine. But this sign in activity is crashing.
The error shown by the debugger.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.durden, PID: 7921
java.lang.NullPointerException
at com.example.durden.activity.SignInActivity.onCreate$lambda-2(SignInActivity.kt:49)
at com.example.durden.activity.SignInActivity.$r8$lambda$ZBrxDCm4vr69l-PuE690AA_KCF8(Unknown Source:0)
at com.example.durden.activity.SignInActivity$$ExternalSyntheticLambda1.onClick(Unknown Source:4)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
The signin Activity
class SignInActivity : AppCompatActivity() {
// getting the references from firebase
private var auth: FirebaseAuth? = null
private var firebaseUser: FirebaseUser? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// gets the view binding of sign_in_activity
val binding = ActivitySignInBinding.inflate(layoutInflater)
setContentView(binding.root)
// ends this activity and goes to sign up page if needed
binding.gotoSignUp.setOnClickListener {
val intent = Intent(
this#SignInActivity,
SignUpActivity::class.java
)
startActivity(intent)
finish()
}
binding.btnSignIn.setOnClickListener {
// storing the entered email and password
val email = binding.SImail.text.toString()
val password = binding.SIpass.text.toString()
// checks if the values are entered
if (TextUtils.isEmpty(email) && TextUtils.isEmpty(password)) {
Toast.makeText(applicationContext,"email and password are required", Toast.LENGTH_SHORT).show()
}
// signs in the user using firebase data
else {
auth!!.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) {
if (it.isSuccessful) {
binding.SImail.setText("")
binding.SIpass.setText("")
// after sign in takes to user page
val intent = Intent(
this#SignInActivity,
UserActivity::class.java
)
startActivity(intent)
finish()
}
else {
Toast.makeText( applicationContext, "Invalid password or email", Toast.LENGTH_SHORT).show()
}
}
}
}
}
}
Firebase Authentication causing Android fatal exception
This sounds similar to my problem but still, I couldn't figure why it happens so.

You never initialize auth, which means that by the time you execute auth!!.signInWithEmailAndPassword(email, password) you get an exception.
Initialize auth like shown in step 2 here in your onCreate to prevent the error.
// Initialize Firebase Auth
auth = Firebase.auth
NullPointerExceptions are very common, so I highly recommend learning how to troubleshoot these yourself. For that, check out:
What is the Kotlin double-bang (!!) operator?
Unfortunately MyApp has stopped. How can I solve this?
What is a NullPointerException, and how do I fix it?

You are inflating the view twice, which is just wrong:
val binding = ActivitySignInBinding.inflate(layoutInflater)
// setContentView(binding.root)

Related

iOS Push Notifications with Azure Notification Hub

I am having absolutely no luck getting push notifications to work in iOS in a Xamarin Forms project.
In AppDelegate.cs, I am calling the following in the FinishedLaunching override:
MSNotificationHub.Start("Endpoint=sb://[redacted].servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=[redacted]",
"[redacted]");
After the user logs in further in the app lifecycle, I also register the user with their user tag as follows:
public async Task UpdateTags(string token)
{
await Task.Run(() =>
{
try
{
// No point registering tags until the user has signed in and we have a device token
if (CurrentAccount == null)
{
Console.WriteLine($"UpdateTags cancelled: Account is null");
return;
}
var tag = $"user:{CurrentAccount.UserName}";
Console.WriteLine($"Registering tag: {tag}");
MSNotificationHub.AddTag(tag);
}
catch (Exception e)
{
Console.WriteLine($"Error registering tag: {e.ToString()}");
}
});
}
I have properly configured the Apple (APNS) settings in the notification hub, using the Token authentication mode (verified the four fields several times). The certificate (signing identity) is "iOS Distribution", the identifier bundle matches exactly what I have in the configuration (not using wildcard), the key has Apple Push Notifications service (APNs) enabled, and the provisioning profile has Platform: iOS and Type: App Store.
I pushed the application to TestFlight, as I don't have access to a physical Mac (we use a Cloud mac for development). When I view the device logs from my personal iPhone with the app installed, I see the following when I run it:
<Notice>: Registered for push notifications with token: [redacted]
<Notice>: Registering tag: user:[redacted]
There are no instances of "Error registering tag" or "UpdateTags cancelled" in the logs at all, which tells me that the method calls are succeeding without an exception. However, when I attempt to send a test notification to either a blank/empty tag, or the specific tag for my test user, no notifications are received and the messaging simply shows "Message was successfully sent, but there were no matching targets."
Also, when I pull all of the registrations with var registrations = await hub.GetAllRegistrationsAsync(0);, I only see the FCM (Firebase/Android) registrations from my successful testing on the Android side of things.
I am at a complete loss and have hit a wall, as there are no exceptions being thrown, and seemingly no way to troubleshoot what is going on behind the scenes.
This is also my 2nd attempt - I was using a more complex SBNotificationHub implementation and had the same results - no exceptions and everything looked fine at face value.
Thanks to a comment pointing to another question, I have determined that all I needed to do was to ensure that my tag registration ran on the main UI thread. My updated code below is working:
public async Task UpdateTags(string token)
{
await Task.Run(() =>
{
Device.BeginInvokeOnMainThread(() =>
{
try
{
// No point registering tags until the user has signed in and we have a device token
if (CurrentAccount == null)
{
Console.WriteLine($"UpdateTags cancelled: Account: {Trico.OrbitalApp.App.CurrentAccount};");
return;
}
var tag = $"user:{CurrentAccount.UserName}";
Console.WriteLine($"Registering tag: {tag}");
MSNotificationHub.AddTag(tag);
}
catch (Exception e)
{
Console.WriteLine($"Error registering device: {e.ToString()}");
}
});
});
}
You can try implementing the MSInstallationLifecycleDelegate interface which will allow you to check and see if the installation is being saved on the back end with either success or failure.
// Set a listener for lifecycle management
MSNotificationHub.SetLifecycleDelegate(new InstallationLifecycleDelegate());
// Implementation of the lifecycle listener.
public class InstallationLifecycleDelegate : MSInstallationLifecycleDelegate
{
public InstallationLifecycleDelegate()
{
}
public override void DidFailToSaveInstallation(MSNotificationHub notificationHub, MSInstallation installation, NSError error)
{
Console.WriteLine($"Save installation failed with exception: {error.LocalizedDescription}");
}
public override void DidSaveInstallation(MSNotificationHub notificationHub, MSInstallation installation)
{
Console.WriteLine($"Installation successfully saved with Installation ID: {installation.InstallationId}");
}
}

Firebase Auth with unity creates new user in every start

I'm using firebase anonymous authantication for my unity project.
As i always did when project is started i'm sending request to firebase for authantication,
but on my last project (which uses firebase sdk 6.16.0) my request creates new user everytime.
Here is some code about how i'm sending my request
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
auth.SignInAnonymouslyAsync().ContinueWith((task =>
{
if (task.IsCanceled)
{
Debug.Log("task cancelled");
return;
}
if (task.IsFaulted)
{
Debug.Log("task cancelled");
return;
}
if (task.IsCompleted)
{
Firebase.Auth.FirebaseUser userr = task.Result;
firebaseUserId = userr.UserId;
Debug.Log("firebaseUserId");
Debug.Log(firebaseUserId);
//every opening returns new uniq id here.
}
}));
On firebase authantication panel i only activated anonymous login. any suggestions?
Or is there any way to downgrade unity firebase version? i've tried to import old version which i was using on my last game (sdk 6.15.2) but there is some errors on resolver.
Basically, every time you call SignInAnonymouslyAsync you'll create a new user and the last one will be basically lost (it's more or less a random hash - anonymous as it's name suggests).
I'll typically do something like:
using System;
using Firebase.Auth;
using UnityEngine;
using UnityEngine.Events;
public class Login : MonoBehaviour
{
public UnityEvent OnSignInFailed = new UnityEvent();
public UserSignedInEvent OnUserSignedIn = new UserSignedInEvent();
public async void TriggerLogin()
{
var auth = FirebaseAuth.DefaultInstance;
var user = auth.CurrentUser;
if (user == null)
{
try
{
user = await auth.SignInAnonymouslyAsync();
}
catch (Exception e)
{
Debug.LogException(e);
OnSignInFailed.Invoke();
return;
}
}
// user definitely should not be null!
if (user == null)
{
OnSignInFailed.Invoke();
Debug.LogWarning("User still null!?");
return;
}
var userName = user.UserId;
OnUserSignedIn.Invoke(userName);
Debug.Log($"Logged in as {userName}");
}
[Serializable]
public class UserSignedInEvent : UnityEvent<string>
{
}
}
Note that for this code snippet, TriggerLogin is a public method so I can chain it off of a UnityEvent in the Unity editor.
Try and Put it some kind of check to find if used is already logged in. If yes, then do a silent login, if no then use anonymous login.
Currently you are straightaway logging in user even if they logged in last time they opened the Application.
Try this link: https://github.com/firebase/quickstart-unity/issues/266#issuecomment-447981995

Xamarin android: Async await calls not working when app open by clicking push notification

When I open app by tapping on FCM push notification, The API service calls I am making by using await keyword those are not working. Entire app not returning data.
Code for API calling
var result = await objHomework.GetHomeWorksForStudentPagesAsync(studentId.ToString());
result returning null. if app already open, everything working fine. See the Image below screenshot of app
Notification messages are delivered to OnMessageReceived callback only when the app is in the foreground.
Override the HandleIntent Method of the FirebaseMessageService to work for background as well
public override void HandleIntent(Intent intent)
{
try
{
if (intent.Extras != null)
{
var builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
foreach (string key in intent.Extras.KeySet())
{
builder.AddData(key, intent.Extras.Get(key).ToString());
}
this.OnMessageReceived(builder.Build());
}
else
{
base.HandleIntent(intent);
}
}
catch (Exception)
{
base.HandleIntent(intent);
}
}
Actually, I was missing some keys which is necessary for service call authentication in my project. I am getting those keys in MaiActivity but notification click even starting app from somewhere else therefore keys values was null and service calls was not happening.

Permission error on auth logout: firebase/ionic/angularfire2

I have an ionic3 application using angularfire2 and firebase. I use firbase auth to login to my application, and for retrieving an object from firebase about "currentChallenges". When I use the logout function an error is thrown from Firebase.
Error message:
permission_denied at /currentChallenge: Client doesn't have permission
to access the desired data.
I use the following function for my logout, in my auth.service.ts:
logout() {
this.isLoggedIn = false;
this.firebaseAuth
.auth
.signOut().then(() => {
this.appCtrl.getRootNav().popToRoot(); //root is login page
});
}
I am not sure where/what exactly is causing the error. In my challenges.service.ts is where I make the initial observable object:
private dbCurrentChallengesObservable: FirebaseObjectObservable <any>;
constructor(db: AngularFireDatabase) {
this.dbCurrentChallengesObservable = db.object('/currentChallenge');
}
public getCurrentChallenges(){
return this.dbCurrentChallengesObservable;
}
And then, I use this object in my model (challenges.ts) like this:
ionViewCanEnter(): boolean{
return this.authService.isAuthenticated();
}
ionViewDidLoad() {
this.currentChallenge = this.challengesService.getCurrentChallenges();
this.currentChallenge.subscribe(data => {
if(data.challenge1completed > 0) this.challenge1Completed = true;
if(data.challenge2completed > 0) this.challenge2Completed = true;
});
}
At first I thought it was related to the subscribe and I added an subscribe().unsubscribe() in an on-ion-leave function in the challenges.ts, but that did not stop the error. But something must still be listening to firebase, which must be stopped upon or even before logout. I just don't know what/where/how.
Any help would be appreciated.
private afDatabase: AngularFireDatabase,//blabla
this.afDatabase.database.goOffline();//To solve the permission denied 문제.
add above statement before signout();
I too took a lot of time on this problem and not a single clue found.
Hope this helps

How to retrieve docs using Google Drive SDK in Asp.Net

I am working on a project that retrieve Google Drive docs list using ASP.NET, but I'm getting an error:
An error occurred: Google.Apis.Requests.RequestError Daily Limit for
Unauthenticated Use Exceeded. Continued use requires signup. [403]
This is my site (getting error on this link) : http://www.netdesklive.com/
I am trying DrEdit code for this, but not working proper.
I set all the credential as per https://developers.google.com/drive/examples/dotnet but still i m getting an error
So Please, Suggest me
Code :
-> I am getting null value in state and code
public ActionResult Index(string state, string code)
{
try
{
IAuthenticator authenticator = Utils.GetCredentials(code, state);
// Store the authenticator and the authorized service in session
Session["authenticator"] = authenticator;
Session["service"] = Utils.BuildService(authenticator);
}
catch (CodeExchangeException)
{
if (Session["service"] == null || Session["authenticator"] == null)
{
Response.Redirect(Utils.GetAuthorizationUrl("", state));
}
}
catch (NoRefreshTokenException e)
{
Response.Redirect(e.AuthorizationUrl);
}
DriveState driveState = new DriveState();
if (!string.IsNullOrEmpty(state))
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
driveState = jsonSerializer.Deserialize<DriveState>(state);
}
if (driveState.action == "open")
{
return OpenWith(driveState);
}
else
{
return CreateNew(driveState);
}
}
Your error message suggests that your requests are not authorized. You should authorize them using Oauth2 :
Authorizing Drive requests
Google Oauth2 documentation

Resources