Reputation: 4817
Hi I am running some operation that copies data drom Firebase DB to local room DB. Here is doInBackground part from my AsyncTask.
@Override
protected Void doInBackground(Void... voids) {
contactList = getContactListFromPhone();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot : dataSnapshot.getChildren())
{
User user = userSnapshot.getValue(User.class);
if (contactList.containsKey(user.getPhone()))
{
UserDB userDB = new UserDB();
userDB.setName(user.getName());
userDB.setPhone(user.getPhone());
userDB.setToken(user.getToken());
//adding to database
DatabaseClient.getInstance(context.getApplicationContext()).getAppDatabase().userDao().insert(userDB);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
return null;
}
But on line "DatabaseClient.getInstance...." I receiving an error:
Cannot access database on the main thread since it may potentially lock the UI for a long period of time
But I am already in AsyncTask, why is that?
Upvotes: 0
Views: 55
Reputation: 6862
It's not about AsyncTask but about Firebase. Firebase's onDataChange
will be called in the MainThread and hence you DatabaseClient.getInstance
is running in the MainThread.
You don't have to perform your Firebase calls in separate thread as Firebase client deals with it. But when you get a response from Firebase, it's onDataChange
will be performed in the MainThread
.
I suggest you to call Firebase in the MainThread and then after getting the data in onDataChanged
, call your AsyncTask that has calls DatabaseClient.getInstance
.
Upvotes: 1