Firebase Database Android Issues - android

I have recently been working with Android development. I have been developing a social networking app. For the app, I decided to create a separate helper class for all database methods. In my database, all users have a user id and their information is stored under this id. I have a (non-static) method in this class that would get certain User information when given a DatabaseReference to the user's information location. The method would simply take the reference, add a listener for single value event (addListenerForSingleValueEvent(ValueEventListener)). I was encountering problems with this so I tried putting a Log statement in the onDataChange() method of the ValueEventListener. Oddly enough, this Log method was never reached. Even more strange is the fact that, if I copy and paste the code from this method into one of the locations where I need it, the Log statement is reached. Does anyone have any idea as to why this happens? This is a method that I am using in multiple activities and copying and pasting the code everywhere would make the code very sloppy. Any help would be much appreciated. Thank you!
Update: It turns out the code works if placed in the Database class, but the Log statement will only run after the method is over. Below is the an outline of the class I am using to observe this.
Fragment Class
public class FragmentClass extends Fragment {
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDatabase = DatabaseManager.getInstance();
String userId = "userId";
mDatabase.getUserFromUserId(userId);
}
}
Database Class
public class DatabaseManager {
private static FirebaseDatabaseManager mInstance;
private static FirebaseDatabase mDatabase;
public static FirebaseDatabaseManager getInstance() {
if(mInstance == null) {
mInstance = new FirebaseDatabaseManager();
}
return mInstance;
}
private FirebaseDatabaseManager() {
mDatabase = FirebaseDatabase.getInstance();
}
public void getUserFromUserId(final String userId) {
DatabaseReference userReference = mDatabase.getReference(userId);
userReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("databaseTag", "reached");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.i("databaseTag", "reached");
}
});
while(true) { // if this part is commented out, the log statement will be executed; otherwise, it won't
}
}
}

Related

How to avoid downloading same data from firebase realtime database?

I'm creating an Android app with an activity with a bottom navigation control that lets the user navigate between different fragments. In these fragments i have lists of data coming from a firebase backend that i show with a RecyclerView.
The problem is that every time i navigate between these fragments all the data is downloaded again, while i would want to use cached data and just listen for changes.
What i have done so far is to use ViewModel and LiveData and they work fine. Moreover if i disconnect the phone from the Internet the data is showed (and of course is not downloaded), even if i navigate between the fragments.
In the fragment that shows the data i have:
LiveData<List<UncompletedTask>> taskLiveData = viewModel.getTaskLiveData();
taskLiveData.observe(this, new Observer<List<UncompletedTask>>() {
#Override
public void onChanged(List<UncompletedTask> uncompletedTasks) {
myAdapter.submitList(uncompletedTasks);
listener.onTodoListElementsLoaded(uncompletedTasks.size());
}
});
In the viewmodel i have:
private TodoTaskRepository repository;
#NonNull
public LiveData<List<UncompletedTask>> getTaskLiveData() {
return repository.getTaskLiveData();
}
In the TodoTaskRepository i initialize FirebaseQueryLiveData in the contructor and return it in getTaskLiveData().
Finally FirebaseQueryLiveData is like this:
public class FirebaseQueryLiveData extends LiveData<DataSnapshot> {
private static final String LOG_TAG = "FirebaseQueryLiveData";
private final Query query;
private final MyValueEventListener listener = new MyValueEventListener();
public FirebaseQueryLiveData(Query query) {
this.query = query;
}
#Override
protected void onActive() {
query.addValueEventListener(listener);
}
#Override
protected void onInactive() {
query.removeEventListener(listener);
}
private class MyValueEventListener implements ValueEventListener {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
setValue(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(LOG_TAG, "Can't listen to query " + query, databaseError.toException());
}
}
}
How can i download all the data the first time but then just listen for changes and don't download the same data while navigating between fragments if nothing is changed?
If you have enabled disk persistence then data will not be download again unless data has changed
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
When you run your ValueEventListener the first time data is downloaded alright, the second time the same ValueEventListener runs then data is coming from local cache persistent
Moreover if disconnect the phone from the Internet the data is indeed coming from the same local cache.

Simultaneous connections in firebase

If I set scoresRef.keepSynced(false) and use Disk Persistence, FirebaseDatabase.getInstance().setPersistenceEnabled(true); to store the data locally, will it lower down the number of "Simultaneous connections" to firebase DB as there will be no active listeners(or it isn't?) ? what may be the consequences?
Codes:
I have a custom adapter "firebaseadapter" and a class "firebasestore" with getter/setter methods. Since "calls to setPersistenceEnabled must be made before any other usage of firebase Database instance", I have made a different class extending Application(or using it in main activity class with static {} is better?).
Utility.calculateNoOfColumns is calculating the number grids to be shown based on screen size.
Moreover, Will the data get updated in client side in real time if I make any changes in firebase DB if the set scoresRef.keepSynced(false)?
public class ThreeFragment extends Fragment {
View viewThree;
ArrayList<firebasestore> list;
DatabaseReference mdatabase;
GridLayoutManager gridLayoutManager;
private firebaseAdapter firebaseAdapter1;
FirebaseDatabase database;
public ThreeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseApp.initializeApp(getContext());
database= FirebaseDatabase.getInstance();
mdatabase=database.getReference().child("DBName");
mdatabase.keepSynced(false);
list = new ArrayList<>();
loadStoreDetails();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
viewThree = inflater.inflate(R.layout.fragment_three, container, false);
int mNoOfColumns = Utility.calculateNoOfColumns(getContext());
RecyclerView firebaseRecyclerView = (RecyclerView)
viewThree.findViewById(R.id.recyclerview_threeFragment1);
firebaseRecyclerView.setHasFixedSize(true);
firebaseAdapter1 = new firebaseAdapter(getContext(), list);
firebaseRecyclerView.setLayoutManager(gridLayoutManager);
firebaseRecyclerView.setAdapter(firebaseAdapter1);
return viewThree;
}
// get data from firebase DB
private void loadStoreDetails() {
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list.clear(); // CLAER DATA BEFORE CHANGING. IF NOT DONE, IT WILL SHOW DUPLICATE DATA
for(DataSnapshot ds : dataSnapshot.getChildren()) {
list.add(ds.getValue(firebasestore.class));
}
firebaseAdapter1.notifyDataSetChanged(); // NOTIFY ADAPTER TO SHOW DATA IN VIEW WITHOUT RELOAD
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("LogFragment", "loadLog:onCancelled", databaseError.toException());
}
};
mdatabase.limitToLast(20).addValueEventListener(valueEventListener);
}
}
If there are no active listeners for a minute, the Firebase client will indeed close its connection to the server.
In your code you call loadStoreDetails attaches a listener with addValueEventListener from onCreate. Since you never remove that listener, it will stay active permanently from the moment ThreeFragment is created until the program exits.
To prevent this, and ensure the data is only synchronized (and the connection kept open) while the user has the fragment open, detach the listener in onDestroyView or onDestroy of the fragment.
For that, add a member field to the fragment:
ValueEventListener mFragmentListener;
Then keep a reference to the listener when you attach it:
mFragmentListener = mdatabase.limitToLast(20).addValueEventListener(valueEventListener);
And finally remove the listener when the fragment is destroyed:
#Override
public void onDestroyView() {
mdatabase.limitToLast(20).removeEventListener(mFragmentListener);
}
On a separate note: the call to mdatabase.keepSynced(false); is not needed in your code, as that is the default behavior already.

Android - Firebase reading from database doesn't work

I can't get to work this code to read (getUser method) from my Firebase DB. I have searched for answer for 2 hours, tried different tutorials and nothing helped. Problem is that it looks like the onDataChange method is never actually called (tested with Log) and I don't know what am I doing wrong. Writing to DB (saveUser method) is working as it should.
Code:
public class UserDatabase {
private User user;
private DatabaseReference databaseReference;
public UserDatabase() {
databaseReference = FirebaseDatabase.getInstance().getReference();
}
public void saveUser(User user) {
databaseReference.child("users").child(user.getUid()).setValue(user);
}
public User getUser(String uid) {
databaseReference = FirebaseDatabase.getInstance().getReference().child("users").child(uid);
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
user = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return user;
} }
Thanks for answer
As I see in your comment, you are saying that "eventually gets the data" but I tell you that the way in which you are trying to use the getUser() method which has as a return type the User class, is not the correct way to solve this problem, especially when it comes to asynchronous methods. You cannot return something now that hasn't been loaded yet. onDataChange() method has an asynchronous behaviour. A quick fix to your problem would be to use those user objects that you are getting from the database only inside onDataChange() method or, if you want to use those objects outside, please see the last part of my answer from this post, in which I explain the way in which you can use a callback in order to achieve this.

Android Firebase - Reading data from firebase prior to inflating layout

I'm trying to get a user's profile from a Firebase DB. Then using the user's information I want to set TextViews in my Fragment's layout to reflect the user's individual stats.
The problem is that the rootViw is being returned prior to having recieved the user's profile. And so I get a null object reference error.
My understanding of the fragment's life cycle is that onCreate() is created first and so I tried placing the DB code there but I get the same problem. I then figured that if accessing the DB is slower than my onCreateView() I'll place a Thread.sleep() timer to wait for the DB call to complete and then perform the rest of my code. Which I know is a stupid solution but just wanted to test my theory; that also failed so obviously my understanding is wrong.
Where should I place my DB call so that it completes prior to returning my rootView? Why does placing the DB listener in OnCreate() not work and why does the Thread.sleep() delay not work?
Leaderboard Fragment
public class Leaderboard extends Fragment{
private FirebaseAuth mFirebaseAuth;
private DatabaseReference mUserDatabaseReference;
private User user;
private TextView scoreView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_leaderboard,
container, false);
scoreView = rootView.findViewById(R.id.leaderboard_score);
mFirebaseAuth = FirebaseAuth.getInstance();
final String userUID = mFirebaseAuth.getCurrentUser().getUid();
mUserDatabaseReference =
FirebaseDatabase.getInstance().getReference("users");
mUserDatabaseReference.addListenerForSingleValueEvent(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.hasChildren()) {
for (DataSnapshot messageSnap: snapshot.getChildren()) {
if(messageSnapshot.getKey().equals(userUID)) {
user = messageSnapshot.getValue(User.class);
}}}}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
//Causes error because user==null
scoreView.setText("Score: " + user.getScore());
return rootView;
}
}
All Firebase APIs are asynchronous. You should expect that listeners may be called after any amount of time, based on the quality of the hardware and its network connection. Don't ever use Thread.sleep() to try to control the timing of things - that is an anti-pattern.
My suggestion to you is to inflate a "loading" screen in onCreateView() to display immediately, so the user doesn't have to look at a blank screen when your fragment starts. Then, when your listener is called with the data you want to display, add or update other views as needed.
Why not set the score after you get the DB result ?
mUserDatabaseReference.addListenerForSingleValueEvent(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.hasChildren()) {
for (DataSnapshot messageSnap: snapshot.getChildren()) {
if(messageSnapshot.getKey().equals(userUID)) {
user = messageSnapshot.getValue(User.class);
}
}
scoreView.setText("Score: " + user.getScore());
}}
#Override
public void onCancelled(DatabaseError databaseError) {}
});

DatabaseException on using getUid() function in Firebase Authentication

I am trying to get the id of the logged in user and use it in two fragments. In the fragment I am using first, id gets retrieved and stored in my global variable properly but when I access the other fragment after that, my app crashes saying that getUid() is generating a null pointer exception in the other activity.
Here is my code (Both fragments have identical codes except for different variable names. LDQApp is my class for global variables)
public class RecruitmentFragment extends Fragment {
private DatabaseReference mDatabase;
EditText name_text,reg_text,year_txt, mob_txt,interest_txt;
Button button;
public RecruitmentFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_recruitment, container, false);
name_text = (EditText)rootView.findViewById(R.id.editText2);
reg_text = (EditText)rootView.findViewById(R.id.editText3);
year_txt = (EditText)rootView.findViewById(R.id.editText4);
mob_txt = (EditText)rootView.findViewById(R.id.editText5);
interest_txt = (EditText)rootView.findViewById(R.id.editText6);
button = (Button)rootView.findViewById(R.id.button2);
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
mDatabase=FirebaseDatabase.getInstance().getReference("recruitment");
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
LDQApp.uid = firebaseUser.getUid();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String name,regNo,mobNo,interest;
int year;
name = name_text.getText().toString();
regNo = reg_text.getText().toString();
year = Integer.parseInt(year_txt.getText().toString());
mobNo = mob_txt.getText().toString();
interest = interest_txt.getText().toString();
RecruitUser recruitUser = new RecruitUser(name,regNo,year,mobNo,interest);
mDatabase.child(LDQApp.uid).setValue(recruitUser);
mDatabase.child(LDQApp.uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
RecruitUser sUser = dataSnapshot.getValue(RecruitUser.class);
Toast.makeText(getContext(),"Submitted successfully",Toast.LENGTH_SHORT).show();
Log.d(TAG, "User name: " + name + ", Registration No: " + regNo);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
});
return rootView;
}
}
This is the log as requested
Get your FirebaseDatabase like this:
you don't need to call that and assign new value again an again use a static one;
public class Util {
private static FirebaseDatabase database;
public static FirebaseDatabase getDatabase() {
if (database == null) {
database = FirebaseDatabase.getInstance();
database.setPersistenceEnabled(true);
}
return database;
}
}
then you can access this as Util.getDatabase() or you can do it keeping a static boolean too as i said in that comment, but this avoids more code redundancy too.
read documentation
This is quite easy just create a new class that extends Application
public class FireApp extends Application {
#Override
public void onCreate() {
super.onCreate();
/* Enable disk persistence */
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
}
connect it to your project in the manifest file by adding the name attribute
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:name=".FireApp"
android:supportsRtl="true"
android:theme="#style/AppTheme">
Don't assume, when using Firebase Authentication, that once a user is logged in, that the user will always be logged in. Don't store the UID in a global like that. Wherever you need to know the login status of the user, you typically should use an AuthStateListener to keep track of that. The callback you pass it will always be invoked with the correct login status of the user, and you can react to that information accordingly.
Also, if you are going to use getCurrentUser() to try to get the currently logged in user, note that it can return null when the user is not logged in. That's probably what's happening to you, and why calling getUid() is throwing an NPE for you.

Categories

Resources