I have connected to Firebase shown under Save and Retrieve Data in Tools >> Firebase. My project is in android studios using Java.
This is the error I get from logcat and the code below:
12-16 11:42:42.699 2485-2550/? E/PlayCommon: [120] com.google.android.play.a.g.a(466): Failed to connect to server: java.net.UnknownHostException: Unable to resolve host "play.googleapis.com": No address associated with hostname
12-16 11:43:00.005 1534-1547/? E/memtrack: Couldn't load memtrack module
This package com.example.sammay.firebaseapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
EditText editTextName;
Button buttonAdd;
Spinner spinnerGenres;
DatabaseReference databaseArtist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// databaseArtist = FirebaseDatabase.getInstance().getReference("artists");
editTextName = (EditText)findViewById(R.id.editTextName);
buttonAdd = (Button)findViewById(R.id.buttonAddArtist);
spinnerGenres = (Spinner)findViewById(R.id.spinnerGenres);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("root");
myRef.setValue("Hello, World!");
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addArtist();
}
});
}
private void addArtist(){
String name = editTextName.getText().toString().trim();
String genre = spinnerGenres.getSelectedItem().toString();
if(!TextUtils.isEmpty(name)){
String id = databaseArtist.push().getKey();
Artist artist = new Artist(id, name, genre);
databaseArtist.child(id).setValue(artist);
Toast.makeText(this, "Artist added", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "You should enter a name", Toast.LENGTH_LONG).show();
}
}
}
I have also created the necessary class Artist with the said details.
Everything seems to look correct but I when I launch the app and enter details and click the button nothing happens to the real-time database.
Most common reason for getting the UnknownHostException is the missing Internet-Permission in your AndroidManifest.xml file. To solve this, please add the following line of code right after your package name:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Related
I'm trying to create Android Application using Android Studio and firebase. I connected my app to firebase and was trying to use Realtime database. Everything have seemed fine until I realized, that firebase was not creating any tables in the Realtime database. Authentication works without any problems and I can see the registered users on the Authentication Page on Firebase website. What's more, I can even use their data to log into application and everything works as it should. I guess, that if something However, nothing new appears in Realtime database. No Users table is created.
Realtime database rules:
{
"rules": {
".read": "true",
".write": "true"
}
}
RegisterUser Activity, which sends data to Firebase Realtime Database:
package com.kalarus.kaluzinski.kaczor;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
public class RegisterUser extends AppCompatActivity implements View.OnClickListener{
private TextView banner;
private Button registerUserButton;
private EditText editTextFullNameRegisterPage, editTextAgeRegisterPage ,editTextEmailRegisterPage, editTextPasswordRegisterPage;
private ProgressBar progressBarRegisterPage;
private FirebaseAuth kinoAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_user);
kinoAuth = FirebaseAuth.getInstance();
banner = (TextView) findViewById(R.id.banner);
banner.setOnClickListener(this);
registerUserButton = (Button) findViewById(R.id.registerUserButton);
registerUserButton.setOnClickListener(this);
editTextFullNameRegisterPage = (EditText) findViewById(R.id.editTextFullNameRegisterPage);
editTextAgeRegisterPage = (EditText) findViewById(R.id.editTextAgeRegisterPage);
editTextEmailRegisterPage = (EditText) findViewById(R.id.editTextEmailRegisterPage);
editTextPasswordRegisterPage = (EditText) findViewById(R.id.editTextPasswordRegisterPage);
progressBarRegisterPage = (ProgressBar) findViewById(R.id.progressBarRegisterPage);
progressBarRegisterPage.setVisibility(View.INVISIBLE);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.banner:
startActivity(new Intent(this, LoginPage.class));
break;
case R.id.registerUserButton:
registerUser();
break;
}
}
private void registerUser()
{
String email = editTextEmailRegisterPage.getText().toString().trim();
String password = editTextPasswordRegisterPage.getText().toString().trim();
String fullName = editTextFullNameRegisterPage.getText().toString().trim();
String age = editTextAgeRegisterPage.getText().toString().trim();
if(fullName.isEmpty())
{
editTextFullNameRegisterPage.setError("Full name is required!");
editTextFullNameRegisterPage.requestFocus();
return;
}
if(age.isEmpty())
{
editTextAgeRegisterPage.setError("Age is required!");
editTextAgeRegisterPage.requestFocus();
return;
}
if(email.isEmpty())
{
editTextEmailRegisterPage.setError("Email is required!");
editTextEmailRegisterPage.requestFocus();
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
{
editTextEmailRegisterPage.setError("Please provide valid email!");
editTextEmailRegisterPage.requestFocus();
return;
}
if(password.isEmpty())
{
editTextPasswordRegisterPage.setError("Password is required!");
editTextPasswordRegisterPage.requestFocus();
return;
}
if(password.length() < 6)
{
editTextPasswordRegisterPage.setError("Min password length should be 6 characters!");
editTextPasswordRegisterPage.requestFocus();
return;
}
progressBarRegisterPage.setVisibility(View.VISIBLE);
kinoAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
User user = new User(fullName, age, email);
FirebaseDatabase.getInstance().getReferenceFromUrl("https://console.firebase.google.com/project/kino-fcff3/database/kino-fcff3-default-rtdb/data/~2F")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(RegisterUser.this, "User has been registered successfully!", Toast.LENGTH_LONG).show();
progressBarRegisterPage.setVisibility(View.INVISIBLE);
}
else
{
Toast.makeText(RegisterUser.this, "Failed to register! Try again!", Toast.LENGTH_LONG).show();
progressBarRegisterPage.setVisibility(View.INVISIBLE);
}
}
});
}
else
{
Toast.makeText(RegisterUser.this, "Failed to register! Try again!", Toast.LENGTH_LONG).show();
progressBarRegisterPage.setVisibility(View.INVISIBLE);
}
}
});
}
}
User data is stored in User class:
package com.kalarus.kaluzinski.kaczor;
public class User {
public String fullName, age, email;
public User() {
}
public User(String fullName, String age, String email) {
this.fullName = fullName;
this.age = age;
this.email = email;
}
}
I tried many solutions, that I've found on the Internet but none of them solved the issue. Things I've done:
created new realtime database in firebase
enabled email/password authentication in firebase
changed the rules of realtime database to "true"
connected Android Studio project to Firebase and added appropriate SDKs (Authentication SDKs and realtime database SDKs)
checked if gradle is using appropriate dependencies
redownloaded google-services.json file and replaced the one in a project
created new clean project and connected it to firebase realtime database
The URL in getReferenceFromUrl() seems to be the problem. You are passing the console's URL instead of database URL. Try using getReference() instead:
FirebaseDatabase.getInstance().getReference()
.child("data")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(...)
If you want to use getReferenceFromUrl() then the URL must be:
https://<project_id><db-name?>.europe-west1.firebasedatabase.app/data
The domain might differ based on the database location but you can check the URL in console here followed by the path:
I'm working with firebase and i'm trying to click the login button but the home page doesn't show up it just says "please waiting!!!" run forever like:
. I can't find a solution to fix it. Help me please.
My realtime Database:
https://drive.google.com/file/d/1ckzM7NitXdPKGdIG6dbAv0IWhl1WgtZk/view?usp=sharing
In SignIn Class:
package com.example.eatit_new;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import com.example.eatit_new.Common.Common;
import com.example.eatit_new.Model.User;
import com.google.android.material.snackbar.Snackbar;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.eatit_new.databinding.ActivitySignInBinding;
import com.google.firebase.auth.OAuthCredential;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.rengwuxian.materialedittext.MaterialEditText;
public class SignIn extends AppCompatActivity {
EditText editPhone, editPassword;
Button btnSignIn;
#Override
protected void onCreate (Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_sign_in);
editPassword=(MaterialEditText)findViewById(R.id.editPassword);
editPhone= (MaterialEditText)findViewById(R.id.editPhone);
btnSignIn = (Button) findViewById(R.id.btnSignIn);
//init Database
final FirebaseDatabase database= FirebaseDatabase.getInstance();
final DatabaseReference table_user=database.getReference("User");
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ProgressDialog mDialog = new ProgressDialog(SignIn.this);
mDialog.setMessage("Please waiting....");
mDialog.show();
table_user.addValueEventListener( new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Check if user not exist in database
if (dataSnapshot.child(editPhone.getText().toString()).exists()) {
//Get User Information
mDialog.dismiss();
User user = dataSnapshot.child(editPhone.getText().toString()).getValue(User.class);
if (user.getPassword().equals(editPassword.getText().toString())) {
Intent homeIntent= new Intent(SignIn.this,Home.class);
Common.currentUser= user;
startActivity(homeIntent);
finish();
} else {
Toast.makeText(SignIn.this, "Wrong password!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(SignIn.this, "User not exists!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
}
}
Error In Run:
W/Parcel: Expecting binder but got null!
E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 324)
W/GmsClient: IGmsServiceBroker.getService failed
android.os.DeadObjectException: Transaction failed on small parcel; remote process probably died, but this could also be caused by running out of binder buffe
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(BinderProxy.java:584)
at com.google.android.gms.common.internal.zzac.getService(com.google.android.gms:play-services-basement##18.1.0:8)
at com.google.android.gms.common.internal.BaseGmsClient.getRemoteService(com.google.android.gms:play-services-basement##18.1.0:14)
at com.google.android.gms.common.internal.BaseGmsClient$LegacyClientCallbackAdapter.onReportServiceBinding(com.google.android.gms:play-services-basement##18.1.0:2)
at com.google.android.gms.common.internal.zzg.zzd(com.google.android.gms:play-services-basement##18.1.0:1)
at com.google.android.gms.common.internal.zza.zza(com.google.android.gms:play-services-basement##18.1.0:4)
at com.google.android.gms.common.internal.zzc.zze(com.google.android.gms:play-services-basement##18.1.0:3)
at com.google.android.gms.common.internal.zzb.handleMessage(com.google.android.gms:play-services-basement##18.1.0:31)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7898)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
D/FA: Service connection suspended
V/FA: Recording user engagement, ms: 6704
V/FA: onActivityCreated
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
V/FA: Activity paused, time: 31916685
D/AutofillManager: Fill dialog is enabled:false, hints=[]
V/FA: Activity resumed, time: 31916803
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
W/Parcel: Expecting binder but got null!
D/TrafficStats: tagSocket(107) with statsTag=0xffffffff, statsUid=-1
D/CompatibilityChangeReporter: Compat change id reported: 171228096; UID 10157; state: ENABLED
W/Parcel: Expecting binder but got null!
D/EGL_emulation: app_time_stats: avg=30.81ms min=2.94ms max=450.90ms count=28
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I Am creating a Login/Register Activity in my android app. When a user is registering the Firebase Authentication is working fine. After Registering a use is directed into Setup activity. Now the setup activity is to store data into Firebase Database. Whenever the user is completing setup and clicking on the button to update in the database. The app stops working.
private Button SaveInformation;
SaveInformation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
SaveAccountSetupInformation();
}
});
When the app is crashing the logcat is showing this error
enter image description here
The App is showing this error
The Code of my Setup Activity is:
package com.example.application;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
public class SetupActivity2 extends AppCompatActivity {
private EditText FirstName, LastName, Day, Month, Year;
private EditText Country, State;
private ImageView ProfilePic;
private Button SaveInformation;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef;
private ProgressDialog loadingBar;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup2);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
FirstName = (EditText) findViewById(R.id.setup_FirstName);
LastName = (EditText) findViewById(R.id.setup_LastName);
Day = (EditText) findViewById(R.id.setup_date);
Month = (EditText) findViewById(R.id.setup_month);
Year = (EditText) findViewById(R.id.setup_year);
Country = (EditText) findViewById(R.id.setup_country);
State = (EditText) findViewById(R.id.setup_state);
ProfilePic = (ImageView) findViewById(R.id.setup_profilePic) ;
SaveInformation = (Button) findViewById(R.id.setup_button);
loadingBar = new ProgressDialog(this);
SaveInformation.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
SaveAccountSetupInformation();
}
});
}
private void SaveAccountSetupInformation()
{
String firstName = FirstName.getText().toString().trim();
String lastName = LastName.getText().toString().trim();
String day = Day.getText().toString().trim();
String month = Month.getText().toString().trim();
String year = Year.getText().toString().trim();
String country = Country.getText().toString().trim();
String state = State.getText().toString().trim();
if(TextUtils.isEmpty(firstName))
{
Toast.makeText(this, "Please write your username...", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(lastName))
{
Toast.makeText(this, "Please write your full name...", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(country))
{
Toast.makeText(this, "Please write your country...", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(state))
{
Toast.makeText(this, "Please write your state...", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(day))
{
Toast.makeText(this, "Please write your full name...", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(month))
{
Toast.makeText(this, "Please write your month...", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(year))
{
Toast.makeText(this, "Please write your year...", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Saving Information");
loadingBar.setMessage("Please wait, while we are creating your new Account...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
HashMap userMap = new HashMap<>();
userMap.put("FirstName",firstName);
userMap.put("LastName",lastName);
userMap.put("day",Day);
userMap.put("month",Month);
userMap.put("year",Year);
userMap.put("country",country);
userMap.put("state",State);
userMap.put("Status","Hey There !! I am using Toodle.");
userMap.put("Gender","Default");
userMap.put("Institution","Default");
UsersRef.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener()
{
#Override
public void onComplete(#NonNull Task task)
{
if(task.isSuccessful())
{
SendUserToMainActivity();
Toast.makeText(SetupActivity2.this, "your Account is created Successfully.", Toast.LENGTH_LONG).show();
loadingBar.dismiss();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(SetupActivity2.this, "Error Occured: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
private void SendUserToMainActivity()
{
Intent mainIntent = new Intent(SetupActivity2.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
Error in My LOGCAT when the app crashes.
2020-09-13 11:05:00.540 20182-20182/com.example.application E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.application, PID: 20182
com.google.firebase.database.DatabaseException: Found conflicting getters for name: getText
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.<init>(CustomClassMapper.java:477)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.loadOrCreateBeanMapperForClass(CustomClassMapper.java:329)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(CustomClassMapper.java:166)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(CustomClassMapper.java:141)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToPlainJavaTypes(CustomClassMapper.java:65)
at com.google.firebase.database.DatabaseReference.updateChildrenInternal(DatabaseReference.java:412)
at com.google.firebase.database.DatabaseReference.updateChildren(DatabaseReference.java:392)
at com.example.application.SetupActivity2.SaveAccountSetupInformation(SetupActivity2.java:141)
at com.example.application.SetupActivity2.access$000(SetupActivity2.java:26)
at com.example.application.SetupActivity2$1.onClick(SetupActivity2.java:72)
at android.view.View.performClick(View.java:6312)
at android.view.View$PerformClick.run(View.java:24811)
at android.os.Handler.handleCallback(Handler.java:794)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6651)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
your error as shown in logcat is
Found conflicting getters for name: getText
the Firebase Database can only store JSON types but you send to it an Edit Text
the error exactly here
userMap.put("day",Day);
userMap.put("month",Month);
userMap.put("year",Year);
userMap.put("state",State);
you send Day ,Month ,Year and State as Edit Text not String
do it like these
userMap.put("day",day);
userMap.put("month",month);
userMap.put("year",year);
userMap.put("state",state);
and it will work fine
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I wanted to start my new and also first app, and it crashes every time i hit the button to login. It tells me that there is a NullPointerException, but i have no clue why. Could someone help me? Have been looking for solutions but can't find any helping ones so far.
package com.glowchat.app;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class LoginActivity extends AppCompatActivity {
private Button loginbtn;
private EditText email;
private EditText password;
private FirebaseAuth auth;
private FirebaseUser user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginbtn = (Button) findViewById(R.id.loginbtn);
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
email = (EditText) findViewById(R.id.inputEmailLogin);
password = (EditText) findViewById(R.id.inputPasswordLogin);
String loginemail = email.getText().toString();
String loginpassword = password.getText().toString();
if (loginemail.isEmpty() || loginpassword.isEmpty()) {
Toast.makeText(LoginActivity.this, "Please fill out all fields.", Toast.LENGTH_SHORT).show();
} else {
auth.signInWithEmailAndPassword(loginemail, loginpassword).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Authentication successfull.", Toast.LENGTH_SHORT).show();
user = auth.getCurrentUser();
} else {
Toast.makeText(LoginActivity.this, "Authentication failed. Check your input and your internet connection.", Toast.LENGTH_SHORT).show();
user = null;
}
}
});
}
}
});
}
}
This is what i get in the Run tab:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.glowchat.app, PID: 29274
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.tasks.Task com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(java.lang.String, java.lang.String)' on a null object reference
at com.glowchat.app.LoginActivity$1.onClick(LoginActivity.java:47)
at android.view.View.performClick(View.java:6935)
at android.widget.TextView.performClick(TextView.java:12742)
at android.view.View$PerformClick.run(View.java:26211)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:7000)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
You just declared FirebaseAuth auth but not init it so that you can't signInWithEmailAndPassword.
I think this Firebase docs will help you a little bit.
This question already has answers here:
How to sound notifications sound when new Message arrives from Firebase Realtime Data base
(4 answers)
Closed 4 years ago.
I'm using firebase data base to create my chat applicaiton. Now that I have sucessfully completed my chat application, but when new message arrives I would like to notify user with sound and NOtification in Notification bar even when the app is not running.
I used the below code to do that
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Notifications Example")
.setContentText("This is a test notification");
Intent notificationIntent = new Intent(this, MenuScreen.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
builder.setAutoCancel(true);
builder.setLights(Color.BLUE, 500, 500);
long[] pattern = {500,500,500,500,500,500,500,500,500};
builder.setVibrate(pattern);
builder.setStyle(new NotificationCompat.InboxStyle());
builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, builder.build());
But it only set alarm when i open the chat activity, then aftearwards when new message arrives it does nothing.
Here is my chat activity code
package com.nepalpolice.mnemonics.chat;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.media.ToneGenerator;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.RemoteMessage;
import com.nepalpolice.mnemonics.R;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Created by filipp on 6/28/2016.
*/
public class Chat_Room extends AppCompatActivity{
private Button btn_send_msg;
private EditText input_msg;
private TextView chat_conversation;
private Toolbar mainToolbar;
private String user_name,room_name;
private DatabaseReference root ;
private String temp_key;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_room);
btn_send_msg = (Button) findViewById(R.id.btn_send);
input_msg = (EditText) findViewById(R.id.msg_input);
chat_conversation = (TextView) findViewById(R.id.textView);
user_name = getIntent().getExtras().get("user_name").toString();
room_name = getIntent().getExtras().get("room_name").toString();
mainToolbar = (Toolbar) findViewById(R.id.main_chat);
setSupportActionBar(mainToolbar);
getSupportActionBar().setTitle(" Room - "+room_name);
root = FirebaseDatabase.getInstance().getReference().child(room_name);
btn_send_msg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Map<String,Object> map = new HashMap<String, Object>();
temp_key = root.push().getKey();
root.updateChildren(map);
DatabaseReference message_root = root.child(temp_key);
Map<String,Object> map2 = new HashMap<String, Object>();
map2.put("name",user_name);
map2.put("msg",input_msg.getText().toString());
message_root.updateChildren(map2);
input_msg.getText().clear();
}
});
root.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
append_chat_conversation(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
append_chat_conversation(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private String chat_msg,chat_user_name;
private void append_chat_conversation(DataSnapshot dataSnapshot) {
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()){
chat_msg = (String) ((DataSnapshot)i.next()).getValue();
chat_user_name = (String) ((DataSnapshot)i.next()).getValue();
chat_conversation.append(chat_user_name +" : "+chat_msg +" \n");
}
}
}
Here is my Firebase Data structure file
Firebase Data Structure
Any help is appreciated. Thanks in advance.
If you are using FCM, you need to understand this part of the doc before proceeding:
The onMessageReceived is provided for most message types, with the following exceptions which are listed below:
Notification messages delivered when your app is in the background. In this case, the notification is delivered to the device’s system tray. A user tap on a notification opens the app launcher by default
Messages with both notification and data payload, both background and foreground. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
So if you need to decide the type of payload you re sending to the android device. You may want to go for Message with both Notifications and data payload so that onMessageRecieved() is invoked at all times.
You can find more details Here