This question already has an answer here:
Firestore whereEqualTo, orderBy and limit(1) not working
(1 answer)
Closed 3 years ago.
I create the project in firebase using a cloud database and I want to compare empUID field which store in a document with current UID.
I created one query which gets the data when current UID and empUID is match but failed to get data.
Please guide is my Query right or am I need to changes in my code
MY Subcollection Path
Employer(root Collection)-->Job Post(Sub collection)-->Job Applicant
Details(sub collection of Job post)
Logcat
2020-02-10 10:38:36.239 29836-29895/com.example.part_time_job I/Adreno: Build Config : S P 6.0.7 AArch64
2020-02-10 10:38:36.231 29836-29836/com.example.part_time_job W/RenderThread: type=1400 audit(0.0:9359): avc: denied { search } for name="proc" dev="debugfs" ino=16085 scontext=u:r:untrusted_app:s0:c183,c257,c512,c768 tcontext=u:object_r:qti_debugfs:s0 tclass=dir permissive=0
2020-02-10 10:38:36.242 29836-29895/com.example.part_time_job I/Adreno: PFP: 0x016ee180, ME: 0x00000000
2020-02-10 10:38:36.231 29836-29836/com.example.part_time_job W/RenderThread: type=1400 audit(0.0:9360): avc: denied { search } for name="ctx" dev="debugfs" ino=16114 scontext=u:r:untrusted_app:s0:c183,c257,c512,c768 tcontext=u:object_r:qti_debugfs:s0 tclass=dir permissive=0
2020-02-10 10:38:36.245 29836-29895/com.example.part_time_job I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
2020-02-10 10:38:36.245 29836-29895/com.example.part_time_job I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
2020-02-10 10:38:36.245 29836-29895/com.example.part_time_job D/libEGL: eglInitialize: exit(res=1)
2020-02-10 10:38:36.245 29836-29895/com.example.part_time_job I/OpenGLRenderer: Initialized EGL, version 1.4
2020-02-10 10:38:36.246 29836-29895/com.example.part_time_job D/OpenGLRenderer: Swap behavior 2
2020-02-10 10:38:36.241 29836-29836/com.example.part_time_job W/RenderThread: type=1400 audit(0.0:9361): avc: denied { search } for name="ctx" dev="debugfs" ino=16114 scontext=u:r:untrusted_app:s0:c183,c257,c512,c768 tcontext=u:object_r:qti_debugfs:s0 tclass=dir permissive=0
2020-02-10 10:38:36.369 29836-29894/com.example.part_time_job W/e.part_time_jo: Accessing hidden method Ljava/security/spec/ECParameterSpec;->setCurveName(Ljava/lang/String;)V (light greylist, reflection)
2020-02-10 10:38:36.391 29836-29894/com.example.part_time_job W/e.part_time_jo: Accessing hidden method Ldalvik/system/BlockGuard;->getThreadPolicy()Ldalvik/system/BlockGuard$Policy; (light greylist, linking)
2020-02-10 10:38:36.391 29836-29894/com.example.part_time_job W/e.part_time_jo: Accessing hidden method Ldalvik/system/BlockGuard$Policy;->onNetwork()V (light greylist, linking)
2020-02-10 10:38:37.656 29836-29836/com.example.part_time_job E/RecyclerView: No adapter attached; skipping layout
2020-02-10 10:38:38.262 29836-29836/com.example.part_time_job E/Register4: Received an exception FAILED_PRECONDITION: The query requires an index. You can create it here: https://console.firebase.google.com/v1/r/project/part-time-job-74d92/firestore/indexes?create_composite=Cmxwcm9qZWN0cy9wYXJ0LXRpbWUtam9iLTc0ZDkyL2RhdGFiYXNlcy8oZGVmYXVsdCkvY29sbGVjdGlvbkdyb3Vwcy9Kb2IgQXBwbGljYW50IERldGFpbHMvaW5kZXhlcy9DSUNBZ09qWGg0RUsQAhoKCgZlbXBVSUQQARoKCgZ1c2VySWQQARoMCghfX25hbWVfXxAB
2020-02-10 10:38:38.263 29836-29877/com.example.part_time_job W/Firestore: (21.3.1) [Firestore]: Listen for Query(target=Query( collectionGroup=Job Applicant Details where userId == uOQXpA8WSgWb5DeDqXxLsdEz0G22 and empUID == null order by __name__);limitType=LIMIT_TO_FIRST) failed: Status{code=FAILED_PRECONDITION, description=The query requires an index. You can create it here: https://console.firebase.google.com/v1/r/project/part-time-job-74d92/firestore/indexes?create_composite=Cmxwcm9qZWN0cy9wYXJ0LXRpbWUtam9iLTc0ZDkyL2RhdGFiYXNlcy8oZGVmYXVsdCkvY29sbGVjdGlvbkdyb3Vwcy9Kb2IgQXBwbGljYW50IERldGFpbHMvaW5kZXhlcy9DSUNBZ09qWGg0RUsQAhoKCgZlbXBVSUQQARoKCgZ1c2VySWQQARoMCghfX25hbWVfXxAB, cause=null}
2020-02-10 10:38:41.232 29836-29870/com.example.part_time_job V/FA: Inactivity, disconnecting from the service
My Java Code
package com.example.part_time_job;
import android.location.Address;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
import model.FInalApplyNotification;
import model.Jobpost;
import ui.JournalRecyclerAdapterNotificationEmp;
import util.JournalApi;
/**
* A simple {#link Fragment} subclass.
*/
public class HistoryFragment extends Fragment {
private static final String TAG = "Register4";
private FirebaseUser user;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private List<FInalApplyNotification> journalList;
private String empid;
private String title;
private String currentUserId;
private RecyclerView recyclerViewnotifyemp;
private JournalRecyclerAdapterNotificationEmp journalRecyclerAdapterNotificationEmp;
private CollectionReference collectionReference=db.collection("Employer");
private TextView no_listnotifyemp;
public HistoryFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_history, container, false);
firebaseAuth= FirebaseAuth.getInstance();
user =firebaseAuth.getCurrentUser();
no_listnotifyemp= view.findViewById(R.id.no_listnotifyemp);
journalList=new ArrayList<>();
recyclerViewnotifyemp=view.findViewById(R.id.recyclerViewnotifyemp);
recyclerViewnotifyemp.setHasFixedSize(true);
recyclerViewnotifyemp.setLayoutManager(new LinearLayoutManager(getActivity()));
currentUserId=JournalApi.getInstance().getUserId();
return view;
}
#Override
public void onStart() {
super.onStart();
if (journalList!=null){
journalList.clear();
}
FInalApplyNotification fInalApplyNotification=new FInalApplyNotification();
fInalApplyNotification.setTitle(title);
fInalApplyNotification.setUserId(currentUserId);
db.collectionGroup("Job Applicant Details").whereEqualTo("userId",currentUserId).whereEqualTo("empUID",fInalApplyNotification.getEmpUID())
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
for (QueryDocumentSnapshot journals : queryDocumentSnapshots) {
FInalApplyNotification fInalApplyNotification = journals.toObject(FInalApplyNotification.class);
journalList.add(fInalApplyNotification);
}
journalRecyclerAdapterNotificationEmp = new JournalRecyclerAdapterNotificationEmp(getActivity(), journalList);
recyclerViewnotifyemp.setAdapter(journalRecyclerAdapterNotificationEmp);
journalRecyclerAdapterNotificationEmp.notifyDataSetChanged();
} else {
no_listnotifyemp.setVisibility(View.VISIBLE);
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "Received an exception " + e.getMessage() );
}
});
}
}
My Query
db.collectionGroup("Job Applicant Details").whereEqualTo("userId",currentUserId).whereEqualTo("empUID",fInalApplyNotification.getEmpUID())
Firebase firestore have mainly 2 types of queries
Simple queries
Compound queries
Simple queries have only where condition, so they don't need database indexes, like
FirebaseFirestore.getInstance().collection("cities")
.whereEqualTo("capital", true)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
Your query is compound query which has multiple Where queries chained together which needs composite index, you can either create composite index in firebase console or create composite index using error message, creating index using error message is easier one, which is printed in your log message, as it handles the fields and sorting order and directly creates index for you
As the exception states, you must create an index for the query you are performing.
FAILED_PRECONDITION: The query requires an index. You can create it here: {some link}
The link provided by the exception, when entered into a browser will load the Firebase Console with all the details you need to create the index needed for the query. So you just need to visit the link and follow the instructions.
Related
This app should show the current username on screen, but when I run just shows "null". I know it's something related to null safety, but i'm new to flutter.
On classes user.dart, auth_methods, mobile_screen_layout.dart I tried to enter some if-else or ? and ! to check the null safety, but didn't work.
Currently I was able to solve the problem of app does not even building because of "building errors", but now is just showing null on screen.
On the web version, it starts with the login screen, so I log in and shows null as well. I can see that the authentication is being correctly when I look at firebase console, so the username is not null.
P.S. I also tried almost everything on internet, but as I am new to flutter, maybe I'm not applying correctly.
I will paste the code and the error below.
DEBUG CONSOLE
Restarted application in 2.077ms.
W/stagram_flutte( 2889): Accessing hidden method Ldalvik/system/CloseGuard;->close()V (greylist,core-platform-api, linking, allowed)
W/DynamiteModule( 2889): Local module descriptor class for com.google.android.gms.providerinstaller.dynamite not found.
I/DynamiteModule( 2889): Considering local module com.google.android.gms.providerinstaller.dynamite:0 and remote module com.google.android.gms.providerinstaller.dynamite:0
W/ProviderInstaller( 2889): Failed to load providerinstaller module: No acceptable module com.google.android.gms.providerinstaller.dynamite found. Local version is 0 and remote version is 0.
W/stagram_flutte( 2889): Accessing hidden method Lsun/misc/Unsafe;->putLong(Ljava/lang/Object;JJ)V (greylist, linking, allowed)
W/stagram_flutte( 2889): Accessing hidden method Lsun/misc/Unsafe;->getObject(Ljava/lang/Object;J)Ljava/lang/Object; (greylist, linking, allowed)
W/stagram_flutte( 2889): Accessing hidden method Lsun/misc/Unsafe;->putObject(Ljava/lang/Object;JLjava/lang/Object;)V (greylist, linking, allowed)
2
W/stagram_flutte( 2889): Accessing hidden method Lsun/misc/Unsafe;->getInt(Ljava/lang/Object;J)I (greylist, linking, allowed)
W/stagram_flutte( 2889): Accessing hidden method Lsun/misc/Unsafe;->putLong(Ljava/lang/Object;JJ)V (greylist, linking, allowed)
I/chatty ( 2889): uid=10134(com.example.instagram_flutter) FirestoreWorker identical 1 line
W/stagram_flutte( 2889): Accessing hidden method Lsun/misc/Unsafe;->putLong(Ljava/lang/Object;JJ)V (greylist, linking, allowed)
W/stagram_flutte( 2889): Accessing hidden method Lsun/misc/Unsafe;->getLong(Ljava/lang/Object;J)J (greylist,core-platform-api, linking, allowed)
user.dart
import 'package:cloud_firestore/cloud_firestore.dart';
class User {
final String email;
final String uid;
final String photoUrl;
final String username;
final String bio;
final List followers;
final List following;
const User({
required this.email,
required this.uid,
required this.photoUrl,
required this.username,
required this.bio,
required this.followers,
required this.following,
});
static User fromSnap(DocumentSnapshot snap) {
var snapshot = snap.data() as Map<String, dynamic>;
return User(
username: snapshot["username"],
uid: snapshot["uid"],
email: snapshot["email"],
photoUrl: snapshot["photoUrl"],
bio: snapshot["bio"],
followers: snapshot["followers"],
following: snapshot["following"],
);
}
//converte a classe para Object Files - Json
Map<String, dynamic> toJson() => {
'username': username,
'uid': uid,
'email': email,
'photoUrl': photoUrl,
'bio': bio,
'followers': followers,
'following': following,
};
}
auth_methods.dart
import 'dart:typed_data';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:instagram_flutter/models/user.dart' as model;
import 'package:instagram_flutter/resources/storage_methods.dart';
class AuthMethods {
final FirebaseAuth _auth = FirebaseAuth.instance;
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
Future<model.User> getUserDetails() async {
User currentUser = _auth.currentUser!;
DocumentSnapshot snap =
await _firestore.collection('users').doc(currentUser.uid).get();
return model.User.fromSnap(snap);
}
//Function - sign up user
Future<String> signUpUser({
required String email,
required String password,
required String username,
required String bio,
required Uint8List? file,
}) async {
String res = "Some error ocurred";
try {
if (email.isNotEmpty ||
password.isNotEmpty ||
username.isNotEmpty ||
bio.isNotEmpty ||
file != null) {
//register user
UserCredential cred = await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
print(cred.user!.uid);
String photoUrl = await StorageMethods()
.uploadImageToStorage('profilePics', file!, false);
//add user to database
//create user model
model.User user = model.User(
username: username,
uid: cred.user!.uid,
email: email,
bio: bio,
followers: [],
following: [],
photoUrl: photoUrl,
);
await _firestore.collection('users').doc(cred.user!.uid).set(
user.toJson(),
);
//Another way to save to database
// await _firestore.collection('users').add({
// 'username': username,
// 'uid': cred.user!.uid,
// 'email': email,
// 'bio': bio,
// 'followers': [],
// 'following': [],
// });
res = 'success';
}
// validações de mensagens de erro
// } on FirebaseAuthException catch (err) {
// if (err.code == 'invalid-email') {
// res = 'The email is badly formated.';
// } else if (err.code == 'email-already-in-use') {
// res = 'The email address is already in use by another account.';
// } else if (err.code == 'weak-password') {
// res = 'Password should be at least 6 characters';
// }
} catch (err) {
res = err.toString();
}
return res;
}
//logging in user
Future<String> loginUser({
required String email,
required String password,
}) async {
String res = "Some error ocurred";
try {
if (email.isNotEmpty || password.isNotEmpty) {
await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
res = "success";
} else {
res = "Please enter all the fields";
}
}
// Tratando erros direito do firebase
// on FirebaseAuthException catch(e){
// if(e.code == 'user-not--found'){
// }
// }
catch (err) {
res = err.toString();
}
return res;
}
}
user_provider.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:instagram_flutter/models/user.dart';
import 'package:instagram_flutter/resources/auth_methods.dart';
class UserProvider with ChangeNotifier {
User? _user;
final AuthMethods _authMethods = AuthMethods();
User? get getUser => _user;
Future<void> refreshUser() async {
User user = await _authMethods.getUserDetails();
_user = user;
notifyListeners();
}
}
mobile_screen_layout.dart
import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart';
//import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:instagram_flutter/providers/user_provider.dart';
import 'package:provider/provider.dart';
import 'package:instagram_flutter/models/user.dart' as model;
class MobileScreenLayout extends StatefulWidget {
const MobileScreenLayout({super.key});
#override
State<MobileScreenLayout> createState() => _MobileScreenLayoutState();
}
class _MobileScreenLayoutState extends State<MobileScreenLayout> {
#override
Widget build(BuildContext context) {
model.User? user = Provider.of<UserProvider>(context).getUser;
return Scaffold(
body: Center(
child: Text((user?.username).toString()),
),
);
}
}
responsive_layout_screen.dart
import 'package:flutter/material.dart';
import 'package:instagram_flutter/providers/user_provider.dart';
import 'package:instagram_flutter/utils/dimensions.dart';
import 'package:provider/provider.dart';
class ResponsiveLayout extends StatefulWidget {
final Widget webScreenLayout;
final Widget mobileScreenLayout;
const ResponsiveLayout({
super.key,
required this.webScreenLayout,
required this.mobileScreenLayout,
});
#override
State<ResponsiveLayout> createState() => _ResponsiveLayoutState();
}
class _ResponsiveLayoutState extends State<ResponsiveLayout> {
#override
void initState() {
// TODO: implement initState
super.initState();
addData();
}
addData() async {
UserProvider _userProvider = Provider.of(context, listen: false);
await _userProvider.refreshUser();
}
#override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth > webScreenSize) {
return widget.webScreenLayout;
}
return widget.mobileScreenLayout;
},
);
}
}
this question is not duplicate for firebase.database is not function.
I installed firebase and import as follow
import React, { Component } from 'react'
import { View } from 'react-native'
import Card from '../components/card'
import firebase from 'firebase/compat/app'
import database from 'firebase/compat/database'
export default class Home extends Component {
state = {
profileIndex: 0,
profiles: [],
}
UNSAFE_componentWillMount() {
firebase.database().ref().child('Users').once('value', (snap) => {
let profiles = []
snap.forEach((profile) => {
const {name, bio, birthday, id} = profile.val()
profiles.push({name, bio, birthday, id})
})
this.setState({profiles})
})
}
when not import this
import database from 'firebase/compat/database'
show error as
firebase.daatabase is not function
but when import this
import database from 'firebase/compat/database'
error is gone and work but actually database is not using in code
I want to know the solution for this
How can use this method
firebase.database()
what need to import in react native
thanks
https://rnfirebase.io/database/usage
Installation
#react-native-firebase/app
#react-native-firebase/database
pod install
cd ios/ && pod install && cd ..
import database from '#react-native-firebase/database';
i am using firebase database and wanted to match a value (the schoolcode) of the user being added to contacts with current users value ( schoolcode) and when i added the code user1.getSchoolCode it started crashing any ideas?
if i pass just a simple string like if (user.getSchoolcode().equals("001")) {
users.add(user);
} it works but user1.getSchoolCode dont work
RecyclerView recyclerView;
UserAdapter userAdapter;
List<User> users;
FirebaseUser firebaseUser;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts_parent);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
users = new ArrayList<>();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("teacher");
readUsers();
}
private void readUsers() {
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
users.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
DataSnapshot snapshot1 = dataSnapshot.child(firebaseUser.getUid());
User user = snapshot.getValue(User.class);
User user1 = snapshot1.getValue(User.class);
assert user != null;
if (user.getSchoolcode().equals(user1.getSchoolcode())) {
users.add(user);
}
}
userAdapter= new UserAdapter(getApplicationContext(), users);
recyclerView.setAdapter(userAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
thanks in advance
this is the logcat
2020-04-15 16:01:44.851 15021-15021/net.gobz.gobz D/AndroidRuntime: Shutting down VM
2020-04-15 16:01:44.852 15021-15021/net.gobz.gobz E/AndroidRuntime: FATAL EXCEPTION: main
Process: net.gobz.gobz, PID: 15021
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String net.gobz.gobz.Model.User.getSchoolcode()' on a null object reference
at net.gobz.gobz.parent.ContactsParentActivity$1.onDataChange(ContactsParentActivity.java:69)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.2.1:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##19.2.1:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##19.2.1:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7099)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
2020-04-15 16:01:44.864 15021-15021/net.gobz.gobz I/Process: Sending signal. PID: 15021 SIG: 9
i dont know if you need this too
2020-04-15 15:55:56.298 15021-15021/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2020-04-15 15:55:56.298 15021-15021/? E/Zygote: accessInfo : 1
2020-04-15 15:55:56.304 15021-15021/? I/net.gobz.gobz: Late-enabling -Xcheck:jni
2020-04-15 15:55:56.336 15021-15021/? I/net.gobz.gobz: report jit thread pid = 15027
2020-04-15 15:55:56.966 15021-15021/net.gobz.gobz I/MultiDex: VM with version 2.1.0 has multidex support
2020-04-15 15:55:56.967 15021-15021/net.gobz.gobz I/MultiDex: Installing application
2020-04-15 15:55:56.967 15021-15021/net.gobz.gobz I/MultiDex: VM has multidex support, MultiDex support library is disabled.
2020-04-15 15:55:57.011 15021-15057/net.gobz.gobz W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
2020-04-15 15:55:57.029 15021-15021/net.gobz.gobz D/FirebaseAuth: Notifying id token listeners about user ( RvM1ycqh35Vxzi4M8NzHGaFERMp1 ).
2020-04-15 15:55:57.034 15021-15021/net.gobz.gobz I/FirebaseInitProvider: FirebaseApp initialization successful
2020-04-15 15:55:57.042 15021-15059/net.gobz.gobz W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
2020-04-15 15:55:57.051 15021-15059/net.gobz.gobz I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to gms implementation
2020-04-15 15:55:57.114 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden method Landroid/graphics/drawable/Drawable;->getOpticalInsets()Landroid/graphics/Insets; (light greylist, linking)
2020-04-15 15:55:57.114 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden field Landroid/graphics/Insets;->left:I (light greylist, linking)
2020-04-15 15:55:57.114 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden field Landroid/graphics/Insets;->right:I (light greylist, linking)
2020-04-15 15:55:57.114 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden field Landroid/graphics/Insets;->top:I (light greylist, linking)
2020-04-15 15:55:57.114 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden field Landroid/graphics/Insets;->bottom:I (light greylist, linking)
2020-04-15 15:55:57.141 15021-15021/net.gobz.gobz W/Glide: Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:compiler in your application and a #GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored
2020-04-15 15:55:57.193 15021-15021/net.gobz.gobz I/DecorView: createDecorCaptionView >> DecorView#a917524[], isFloating: false, isApplication: true, hasWindowDecorCaption: false, hasWindowControllerCallback: true
2020-04-15 15:55:57.228 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
2020-04-15 15:55:57.229 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
2020-04-15 15:55:57.295 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden method Landroid/widget/TextView;->getTextDirectionHeuristic()Landroid/text/TextDirectionHeuristic; (light greylist, linking)
2020-04-15 15:55:57.339 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden field Landroid/view/View;->mAccessibilityDelegate:Landroid/view/View$AccessibilityDelegate; (light greylist, reflection)
2020-04-15 15:55:57.572 15021-15021/net.gobz.gobz D/OpenGLRenderer: Skia GL Pipeline
2020-04-15 15:55:57.578 15021-15021/net.gobz.gobz D/EmergencyMode: [EmergencyManager] android createPackageContext successful
2020-04-15 15:55:57.641 15021-15021/net.gobz.gobz D/InputTransport: Input channel constructed: fd=64
2020-04-15 15:55:57.642 15021-15021/net.gobz.gobz D/ViewRootImpl#98b94c[MainParentActivity]: setView = DecorView#a917524[MainParentActivity] TM=true MM=false
2020-04-15 15:55:57.670 15021-15066/net.gobz.gobz D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2020-04-15 15:55:57.676 15021-15066/net.gobz.gobz D/NetworkManagementSocketTagger: tagSocket(62) with statsTag=0xffffffff, statsUid=-1
2020-04-15 15:55:57.734 15021-15021/net.gobz.gobz D/ViewRootImpl#98b94c[MainParentActivity]: Relayout returned: old=[0,0][1080,2340] new=[0,0][1080,2340] result=0x7 surface={true 537833799680} changed=true
2020-04-15 15:55:57.751 15021-15065/net.gobz.gobz I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
2020-04-15 15:55:57.752 15021-15065/net.gobz.gobz I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
2020-04-15 15:55:57.752 15021-15065/net.gobz.gobz I/OpenGLRenderer: Initialized EGL, version 1.4
2020-04-15 15:55:57.752 15021-15065/net.gobz.gobz D/OpenGLRenderer: Swap behavior 2
2020-04-15 15:55:57.766 15021-15065/net.gobz.gobz D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
2020-04-15 15:55:57.766 15021-15065/net.gobz.gobz D/OpenGLRenderer: eglCreateWindowSurface = 0x7d3d346e00, 0x7d39648010
2020-04-15 15:55:57.832 15021-15021/net.gobz.gobz D/ViewRootImpl#98b94c[MainParentActivity]: Relayout returned: old=[0,0][1080,2340] new=[0,0][1080,2340] result=0x3 surface={true 537833799680} changed=false
2020-04-15 15:55:57.967 15021-15021/net.gobz.gobz D/ViewRootImpl#98b94c[MainParentActivity]: MSG_RESIZED: frame=[0,0][1080,2340] ci=[0,83][0,126] vi=[0,83][0,126] or=1
2020-04-15 15:55:57.968 15021-15021/net.gobz.gobz D/ViewRootImpl#98b94c[MainParentActivity]: MSG_WINDOW_FOCUS_CHANGED 1 1
2020-04-15 15:55:57.968 15021-15021/net.gobz.gobz D/InputMethodManager: prepareNavigationBarInfo() DecorView#a917524[MainParentActivity]
2020-04-15 15:55:57.969 15021-15021/net.gobz.gobz D/InputMethodManager: getNavigationBarColor() -855310
2020-04-15 15:55:57.979 15021-15021/net.gobz.gobz D/InputMethodManager: prepareNavigationBarInfo() DecorView#a917524[MainParentActivity]
2020-04-15 15:55:57.979 15021-15021/net.gobz.gobz D/InputMethodManager: getNavigationBarColor() -855310
2020-04-15 15:55:57.979 15021-15021/net.gobz.gobz V/InputMethodManager: Starting input: tba=net.gobz.gobz ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false
2020-04-15 15:55:57.979 15021-15021/net.gobz.gobz D/InputMethodManager: startInputInner - Id : 0
2020-04-15 15:55:57.979 15021-15021/net.gobz.gobz I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
2020-04-15 15:55:57.990 15021-15040/net.gobz.gobz D/InputTransport: Input channel constructed: fd=84
2020-04-15 15:55:57.990 15021-15021/net.gobz.gobz D/InputMethodManager: prepareNavigationBarInfo() DecorView#a917524[MainParentActivity]
2020-04-15 15:55:57.991 15021-15021/net.gobz.gobz D/InputMethodManager: getNavigationBarColor() -855310
2020-04-15 15:55:57.991 15021-15021/net.gobz.gobz V/InputMethodManager: Starting input: tba=net.gobz.gobz ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false
2020-04-15 15:55:57.991 15021-15021/net.gobz.gobz D/InputMethodManager: startInputInner - Id : 0
2020-04-15 15:56:00.294 15021-15021/net.gobz.gobz W/ClassMapper: No setter/field for studentname found on class net.gobz.gobz.Model.User
2020-04-15 15:56:00.295 15021-15021/net.gobz.gobz W/ClassMapper: No setter/field for grade found on class net.gobz.gobz.Model.User
2020-04-15 15:56:00.295 15021-15021/net.gobz.gobz W/ClassMapper: No setter/field for section found on class net.gobz.gobz.Model.User
2020-04-15 15:56:00.296 15021-15021/net.gobz.gobz W/ClassMapper: No setter/field for status found on class net.gobz.gobz.Model.User
here is a screenshot of my database
i have one more problem now when i touch the contact and open the messaging activity it is crashing again
this is my messages activity
CircleImageView imageView;
FirebaseUser firebaseUser;
DatabaseReference reference;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
final Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
imageView = findViewById(R.id.profile_image);
intent = getIntent();
String userid = intent.getStringExtra("userid");
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("parent").child(userid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if (user.getImageURL().equals("default")) {
imageView.setImageResource(R.drawable.ic_user);
}else {
Glide.with(MessageActivity.this).load(user.getImageURL()).into(imageView);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
and this is the intent i was calling for
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, MessageActivity.class);
intent.putExtra("userid", user.getId());
context.startActivity(intent);
}
});
first get current user from Firebase
private void getCurrentUser(String userID) {
Log.("UserId==>",userID+"");//do check this value in teacher database
FirebaseDatabase.getInstance().getReference("parent").child(userID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try{ if(dataSnapshot != null){ Log.e("UserVal==>", snapshot.getValue(JSONObject.class));
User user1 = snapshot.getValue(User.class);
readUsers(user1.getSchoolcode());}} catch (Exception e){e.printstacktrace(); Log.e("getusererror",e.getMessage());}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
And update your readUsers method like this , you can also change parameter to pass User instead of schoolCode
private void readUsers(String schoolCode) {
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try{ users.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
assert user != null;
if (user.getSchoolcode().equals(schoolCode)) {
users.add(user);
}
}
userAdapter= new UserAdapter(getApplicationContext(), users);
recyclerView.setAdapter(userAdapter);} catch (Exception e){e.printstacktrace(); Log.e("readError",e.getMessage());}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
first Call the getCurrentUser method
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("teacher");
getCurrentUser(firebaseUser.getUid());// readUsers()
I'm developing one small demo project which uses Firebase Auth and Database.
I have the following rule configured for my firebase database
{
"rules": {
"users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
Through this rule, I want an authenticated user to have a read and write access for their data only.
Below is the java code which is trying to save data.
DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference().child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("basic");
{
DemoModel demoModel=new DemoModel();
demoModel.setId(databaseReference.push().getKey());
demoModel.setUser("demoUser"); databaseReference.child(demoModel.getId()).setValue(demoModel).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(DemoActivity.this, Constants.SUCCESSFUL, Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(DemoActivity.this, Constants.FAILED, Toast.LENGTH_SHORT).show();
}
}
});
}
Error I'm getting: W/RepoOperation: setValue at /xgjCUqcasda444WkgZFHTNRUB3/basic/-Lywe44rft566hhyYYfDS failed: DatabaseError: Permission denied
W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
My database looks like:
demoProject-dd4568
xgjCUqcasda444WkgZFHTNRUB3
-basic
-LE3gdfdffdfaza
id:"-LE3gdfdffdfaza"
user: "asdasd"
Where I'm going wrong. I don't have much clue. when I change the rule to
{
"rules": {
".read":"auth != null",
".write":"auth != null"
}
}
it works fine. but it's not secure then.
Your rules don't match your database structure at all. Your rules are protecting child nodes under users, but you don't have a users node in your database.
You should probably be changing the location of the write to include users in the path.
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference root = FirebaseDatabase.getInstance().getReference();
//providing uid
DatabaseReference ref = root.child("users").child(uid).child("basic");
Performing the get() function in security rules is not working.
It returns permission denied on the client, but passes in simulation.
The config/permissions layout is an array structure:
config/permissions-->
---------------------------> CollectionName1 :
----------------------------------------------------> 0 : UID1
----------------------------------------------------> 1 : UID2
---------------------------> CollectionName2 :
----------------------------------------------------> 0 : UID3
----------------------------------------------------> 1 : UID4
I also tried to use single key/value fields in the config/permissions as so
config/permissions-->
---------------------------> CollectionName1 : UID1
---------------------------> CollectionName2 : UID3
with the rule
allow read: if request.auth.uid == get(/config/permissions).data[c] and this passed simulation and failed on the app. If I hardcode the UID instead of request.auth.uid it gives the same result.
UID is definitely correct on the app. This was tested by using the following rule, where it passed in simulation AND the app.
allow read: if request.auth.uid == 'USER_ID_HERE'
and by comparing the logcat output of the UID to the one above.
Please help. This is the Nth day of trying to find a suitable way to structure and query Firestore. I'm certain this is an issue with either the get() call or the way I am writing the call.
Android Code:
FirebaseFirestore db = FirebaseFirestore.getInstance();
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.setTimestampsInSnapshotsEnabled(true)
.build();
db.setFirestoreSettings(settings);
Log.d("UID", FirebaseAuth.getInstance().getCurrentUser().getUid());
DocumentReference docRef = db.collection(collection).document("X153#111");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d("FIREBASE", "DocumentSnapshot data: " + document.getData());
} else {
Log.d("FIREBASE", "No such document");
}
} else {
Log.d("FIREBASE", "get failed with ", task.getException());
}
}
});