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:
Related
This question already has an answer here:
Firebase Have to upload image twice to get it to display
(1 answer)
Closed 1 year ago.
I'm creating an app for my school project, my coding is not that advanced so I apologise in advance for my bad coding. So I'm trying to get the download Uri, so once the user completes the form with the picture, I can upload the details to realtime database to be used in my other parts of my app.
//I use this code below, I got it from the Firebase documents//
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// picUri is a globally declared string and I use it to set my database values,
picUri=(uri.toString());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
I believe it has to do with the fact that Firebase method is asynchronous? So the uri.toString() doesnt get parsed into the global string variable? Because I've been playing around and I realised that when I do the .setValue(object) to write my object to realtime database, the uri does get captured, but that would be too messy and then I wouldnt be able to capture the other values. Ive read around that I need to write a callback, theres alot of guides out there that I've really confused myself here.
Could someone people direct me to a guide or a youtube tutorial on how to understand callbacks and implement a callback to get this value , or issit something else that I'm doing wrong, please advice , thank you.
The photos and the other parameters are being recorded succesfully, its only the picture's uri that I'm unable to capture. (I've temporarily replaced the categoryinput with picUri to run tests easier)
I'm a new user so i cant upload pics but the pic for database and layout is:
https://i.ibb.co/YbdSzwB/databasestack.png
https://i.ibb.co/SVG2zxL/stackoverflow.png
I'll input my entire code just for info
package com.example.giventake;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.*;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.IOException;
public class ListPage extends AppCompatActivity {
/*Declare all variables I'll be using*/
private EditText title, category, description;
private ImageView image, image2, image3;
private FirebaseAuth mAuth;
private FirebaseStorage storage;
private StorageReference storageReference;
private FirebaseDatabase rootNode;
private DatabaseReference referenceItems;
private Uri filePath;
private Uri filePath2;
private Uri filePath3;
private final int PICK_IMAGE_REQUEST = 1;
private final int PICK_IMAGE2_REQUEST = 2;
private final int PICK_IMAGE3_REQUEST = 3;
String picUri;
/*Declare all variables I'll be using*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
/*Initialise all instances of variables*/
title = (EditText) findViewById(R.id.editTextItemTitle);
category = (EditText) findViewById(R.id.editTextItemCategory);
description = (EditText) findViewById(R.id.editTextItemDescription);
image = (ImageView) findViewById(R.id.imgViewPic);
image2 = (ImageView) findViewById(R.id.imgViewPic2);
image3 = (ImageView) findViewById(R.id.imgViewPic3);
image.setImageResource(R.drawable.ic_baseline_list_24);
image2.setImageResource(R.drawable.ic_baseline_list_24);
image3.setImageResource(R.drawable.ic_baseline_list_24);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
mAuth = FirebaseAuth.getInstance();
rootNode = FirebaseDatabase.getInstance();
referenceItems = rootNode.getReference("Items");
/*Initialise all instances of variables*/
}
/*This is to upload images from your phones direction*/
public void onFirstPicClick(View view) {
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(i, "Select Picture"), PICK_IMAGE_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*This is to upload images from your phones direction*/
public void onSubmitClicked(View view) {
//Fetching data
String titleInput = title.getText().toString().trim();
//String categoryInput = category.getText().toString().trim();
String descriptionInput = description.getText().toString().trim();
String itemId = referenceItems.child(mAuth.getCurrentUser().getUid()).push().getKey();
referenceItems = referenceItems.child(mAuth.getCurrentUser().getUid()).child(itemId);
if (filePath != null) {
StorageReference ref = storageReference.child("Images").child(mAuth.getCurrentUser().getUid()).child(itemId).child("Pic1");
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Toast.makeText(ListPage.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ListPage.this, "Picture upload failed" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot
.getTotalByteCount());
}
});
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Got the download URL for 'users/me/profile.png'
picUri=(uri.toString());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
}
//ItemsHelperClass item = new ItemsHelperClass(titleInput, categoryInput, descriptionInput, itemId);
ItemsHelperClass item = new ItemsHelperClass(titleInput,picUri,descriptionInput,itemId);
referenceItems.setValue(item).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent i = new Intent(ListPage.this, MainActivity.class);
startActivity(i);
finish();
// getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit();
} else {
//If it fails to add
Toast.makeText(ListPage.this, "Something went wrong, please try again", Toast.LENGTH_LONG).show();
}
}
}
);
}
}
The Java Firebase Android SDK makes heavy use of Task objects (which are similar to JavaScript Promise objects) where you can chain a number of actions together that need to interact with asynchronous APIs.
A Task object, has many methods to attach listeners, the main ones you'll encounter are:
addOnSuccessListener - When the task completes successfully, run the given code.
addOnFailureListener - When the task fails, run the given code.
addOnCompleteListener - When the task completes (either successfully or has failed), run the given code.
onSuccessTask - When the task completes successfully, start another task.
continueWith - When the task completes (either successfully or has failed), start another task.
Sometimes if you are dealing with multiple tasks at a time, you'll need to make use of methods on the Tasks utility class.
For what you are trying to do, here is a list of the steps you need to take once the user clicks the submit button:
Get the values of any inputs (title, description, category, image file path, etc)
Validate the inputs (make sure each has a value, no invalid characters, etc) and if invalid, show an error.
Create the private references you need: a DatabaseReference and a StorageReference
Upload the image file
If the upload was successful, get a download URL
If getting a download URL was successful, save information to the database.
If any of the tasks in step 4, 5, or 6 fail, show an error.
As this is a school project, I'm not going to dive in any further. Study the links above, and you should be able to combine that knowledge with these steps to find the solution.
However, I will point out this bug that will get you into hot water:
String itemId = referenceItems.child(mAuth.getCurrentUser().getUid()).push().getKey();
referenceItems = referenceItems.child(mAuth.getCurrentUser().getUid()).child(itemId);
You assign to referenceItems here which messes up your code the next time you hit submit and will quickly make your database look like:
{
"Items": {
"-MYu4i_5q-GUETw4WV1i": {
"title": "my first image",
"uri": "https://firebasestorage.googleapis.com/...",
"description": "some description",
"category": "some category",
"-MYu5jNs2MMJJGB2L7jJ": {
"title": "my second image",
"uri": "https://firebasestorage.googleapis.com/...",
"description": "some description",
"category": "some category",
"-MYu72gLxsi4M6J9aBAr": {
"title": "my third image",
"uri": "https://firebasestorage.googleapis.com/...",
"description": "some description",
"category": "some category",
"-MYu78gFeoWhV6OSiF9I": ...
}
}
}
}
}
or, if you had a syntax error rather than a successful upload, you might end up with:
{
"Items": {
"-MYu4i_5q-GUETw4WV1i": {
"-MYu5jNs2MMJJGB2L7jJ": {
"-MYu72gLxsi4M6J9aBAr": {
"title": "my first image",
"uri": "https://firebasestorage.googleapis.com/...",
"description": "some description",
"category": "some category"
}
}
}
}
}
Instead, save and use the reference returned by push():
DatabaseReference itemDataRef = referenceItems.child(mAuth.getCurrentUser().getUid()).push();
String itemId = itemDataRef.getKey();
/* ... */
StorageReference itemStorageRef = storageReference.child("Images").child(mAuth.getCurrentUser().getUid()).child(itemId).child("Pic1");
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
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>
I have a mobile application where you need to login with either gmail or Facebook. The app is now available on google play, but I'm having a technical problem.
When I plug my android device in my laptop and run the app the Gmail login works fine but when I download the app from google play and try logging in through gmail nothing happens; the app remains on the login screen. Anyone knows why I'm having this problem?
Here is my Authentication .java file:
package com.hallak.billdozer.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginManager;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
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.hallak.billdozer.R;
import java.util.Arrays;
import java.util.Map;
/**
* Created by Team Budget 2 on 2/28/17.
* That class deals with authentication using Facebook and Gmail
*/
public class AuthActivity extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener {
/**
* Invokes Facebook login button
*/
private LoginButton mLoginButton;
/**
* Registers a callback for changes to packages in current and managed profiles.
*/
protected CallbackManager mCallbackManager;
/**
* Listens to any change in the user's authentication
*/
private FirebaseAuth.AuthStateListener mAuthListener;
/**
* The entry point of the Firebase Authentication SDK.
*/
private FirebaseAuth mAuth;
/**
* Invokes the GMail sign in button
*/
private SignInButton mSignInButton;
/**
* The main entry point for Google Play services integration.
*/
private GoogleApiClient mGoogleApiClient;
/**
* The entry point for accessing a Firebase Database.
*/
private FirebaseDatabase mDatabase;
/**
* A Firebase reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
*/
private DatabaseReference mDatabaseReference;
private static final int RC_SIGN_IN = 9001;
/**
* This tag is used to be able to log events that happen in this activity
*/
private static final String TAG = "Auth Activity";
/**
* Basic application startup logic that should happen only once for the entire life of the activity.
* #param savedInstanceState Bundle object containing the activity's previously saved state. If the activity has never existed before, the value of the Bundle object is null.
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
// Call the super class onCreate to complete the creation of activity like the view hierarchy
super.onCreate(savedInstanceState);
//Initialize facebook SDK
FacebookSdk.sdkInitialize(getApplicationContext());
// Set the user interface layout for this Activity
// The layout file is defined in the project res/layout/main_activity.xml file
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mDatabase.getReference();
// 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 gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.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 /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Set the dimensions of the sign-in button.
mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
mSignInButton.setSize(SignInButton.SIZE_WIDE);
//Initialize callback manager
mCallbackManager = CallbackManager.Factory.create();
//Assign the views to the corresponding variables
mLoginButton = (LoginButton) findViewById(R.id.login_button);
//Assign the button permissions
mLoginButton.setReadPermissions(Arrays.asList("email", "public_profile"));
mAuth = FirebaseAuth.getInstance();
//Set an action listener to the sign in buton
findViewById(R.id.sign_in_button).setOnClickListener(this);
//Listens to any change in the user's authentication
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
//Get currently logged in user
final FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
//Check if any change occurs in the user's profile
mDatabaseReference.child("users").child(user.getUid()).addValueEventListener(new ValueEventListener() {
/**
* Called on data change, logs the changed value
* #param dataSnapshot get the data
*/
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
Map<String, Object> value = (Map<String, Object>) dataSnapshot.getValue();
Log.d(TAG, "Value is: " + value);
}
/**
* If we cannot read the changed values
* #param error the error thrown by Firebase
*/
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
updateUI(user);
}
};
//Assign the button a task
}
/**
* Google Sign In
*/
protected void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
updateUI(null);
}
}
//Result returned from facebook
else {
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
}
/**
* Handles Facebook Login
* #param token User's access token
*/
protected void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
//Listen to the sign in process
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(AuthActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
//If signing in succeeds, then store the user's information in the database
else {
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
}
}
});
}
/**
* Handles Google's Login
* #param acct Google account used to login
*/
protected void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
//Listen to the sign in process
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(AuthActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
//If signing in succeeds, then store the user's information in the database
else{
FirebaseUser user = mAuth.getCurrentUser();
Log.d(TAG, "Saving user in Firebase");
updateUI(user);
}
// ...
}
});
}
/**
* Handle clicks on Facebook and Google's buttons
* #param v
*/
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
case R.id.com_facebook_button_xout:
signOut();
break;
}
}
/**
* Upon success/failure of the authentication return the desired page
* #param user
*/
protected void updateUI(FirebaseUser user){
if(user != null){
Intent i = new Intent(AuthActivity.this, SplashScreen.class);
i.putExtra("userId",user.getUid());
i.putExtra("userEmail", user.getEmail());
i.putExtra("userName", user.getDisplayName());
startActivity(i);
}
else{
}
}
/**
* Called upon the success of the authentication, listens to the User's auth state
*/
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
/**
* Called upon the failure of the authentication, stops listening to the user's auth state
*/
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
/**
* Method called when an unresolvable error has occurred and Google APIs (including Sign-In) will not be available
* #param connectionResult result of the connection to Google's APIs
*/
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
/**
* Sign out from the application
*/
protected void signOut() {
mAuth.signOut();
LoginManager.getInstance().logOut();
updateUI(null);
}
}
And those are my dependencies in my build.gradle:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.3.0'
compile 'com.google.firebase:firebase-core:9.6.0'
compile 'com.google.firebase:firebase-crash:9.6.0'
compile 'com.google.firebase:firebase-auth:9.6.0'
compile 'com.google.android.gms:play-services-auth:9.6.0'
compile 'com.google.firebase:firebase-database:9.6.0'
compile 'com.facebook.android:facebook-android-sdk:4.8.2'
compile 'com.android.support:design:25.3.0'
compile 'com.github.IntruderShanky:scatter-piechart:1.0.0'
testCompile 'junit:junit:4.12'
}
I was going through a tutorial to create a voice recorder which will then upload the recording to Firebase. I watched the tutorial many times and made sure the app is connected to Firebase; however, the app will not open right now most likely due to this issue. I'm pretty new to Java programming. Can someone please provide me with some guidance? Thank you
package bfb.ess.myapplicationbfb;
import android.app.ProgressDialog;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.IOException;
public class speakp extends AppCompatActivity {
private Button mRecordBtn;
private TextView mRecordlabel;
private MediaRecorder mRecorder;
private String mFileName = null;
private static final String LOG_TAG = "Record_log";
private StorageReference mStorage;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recordpage);
mStorage = FirebaseStorage.getInstance().getReference();
mRecordlabel = (TextView) findViewById(R.id.recordlabel);
mRecordBtn =(Button) findViewById(R.id.recordBtn);
mProgress = new ProgressDialog(this);
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName +="/recorded_audio.3gp";
mRecordBtn.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
startRecording();
mRecordlabel.setText("Recording Started ...");
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
stopRecording();
mRecordlabel.setText("Recording Stopped ...");
}
return false;
}
});
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
uploadAudio();
}
private void uploadAudio() {
mProgress.setMessage("Uploading Audio ...");
mProgress.show();
StorageReference filepath = mStorage.child("Audio").child("new_audio.3gp");
Uri uri = Uri.fromFile(new File(mFileName));
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
mRecordlabel.setText("Uploading Finished");
}
});
}
}
Go to Firebase console and update read and write rules for storage
You can look into the Google Firebase Sample: Storage Sample
Please check the URI of audio file if its proper. Because I guess lastPathSegment of uri is getting faulty.
By Default:
service firebase.storage {
match /b/<name_of_app>/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
Update it to:
service firebase.storage {
match /b/<name_of_app>/o {
match /{allPaths=**} {
allow read;
allow write;
}
}
}
NOTE:
This update will allow you to store the data even if you are not authorised.
It is only for development purpose because it can cause security issue of accessing the data without getting authorised.
So take care when uploading the app to play store, update this parameter and change according to your requirement.
You need to update the read and write rules for storage in your firebase console,
Go to Firebase console, select storage
Click on the Rules tab
By Default:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
Change to:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
as Mohom.R said
NOTE: This update will allow you to store the data even if you are not authorised. It is only for development purpose because it can cause security issue of accessing the data without getting authorised. So take care when uploading the app to play store, update this parameter and change according to your requirement.