I want to take some values from the database (firebase realtime database) and use it with some calculations or display it in a TextView but when the user clicks the button my application doesn't get the value until the next click with all my methods, with a loop or not. outside of the onClick() method I can get the values just fine.
This is a code for getting data from database and display it in a TextView inside onClick()
DatabaseReference myRef;
private double avgrate;
private String category;
private Button button;
private Spinner categories;
private TextView ratetxt;
protected void onCreate(Bundle savedInstanceState) {
myRef = FirebaseDatabase.getInstance().getReference("user_account");
//initialize
avgrate = 0.0;
button = (Button) findViewById(R.id.button);
ratetxt = (TextView) findViewById(R.id.ratetxt);
ratetxt.setVisibility(View.GONE);
// for category adapter -- it works
myRef.child("(username)").child("category").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<String> propertyAddressList = new ArrayList<String>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String propertyAddress = ds.getKey();
if (propertyAddress != null) {
propertyAddressList.add(propertyAddress);
for (DataSnapshot ds2 : dataSnapshot.child(propertyAddress).getChildren()) {
String sub = (String) ds2.getValue();
if (sub != null && !sub.contains("null")) {
propertyAddressList.add(sub);
}
}
}
}
categories = (Spinner) findViewById(R.id.categ);
ArrayAdapter<String> addressAdapter = new ArrayAdapter<String>(myactivity.this, android.R.layout.simple_spinner_item, propertyAddressList);
addressAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categories.setAdapter(addressAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();
}
});
// ON CLICK
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
category = categories.getSelectedItem().toString();
if (category.isEmpty()) {
Toast.makeText(getApplicationContext(), "ERROR - CHOOSE CATEGORY", Toast.LENGTH_SHORT).show();
} else {
// take average rating -- HERE IS THE PROBLEM
myRef.child("(username)").child("rating").child(category).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String str = (String) dataSnapshot.child("avg").getValue(String.class);
if (str != null) {
avgrate = Double.parseDouble(str);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();
}
});
ratetxt.setVisibility(View.VISIBLE);
ratetxt.setText("AVG. RATE: "+avgrate+"");
}/*close else*/ }});// End of OnClick()
} // END OF OnCreate()
here is a code where I have to take the average rating for a chosen category, and set it in a text view, the first time I press the button the avg. will be 0.0 next time it will set the real value, if I don't initialize it, it will set null at first then the real value, I don't know how to fix it
Add these lines inside onDataChange() in button.setOnClickListener ()
Instead of writing outside the onDataChange ()
ratetxt.setVisibility(View.VISIBLE);
ratetxt.setText("AVG. RATE: "+avgrate+"");
Below are codes after making changes. Hope this help.
myRef.child("(username)").child("rating").child(category).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String str = (String) dataSnapshot.child("avg").getValue(String.class);
if (str != null) {
avgrate = Double.parseDouble(str);
ratetxt.setVisibility(View.VISIBLE);
ratetxt.setText("AVG. RATE: "+avgrate+"");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();
}
});
Related
I've just recently started to learn some coding, a little python and java.
I'm trying to make a whatsapp clone as a test, and I've hit a wall.
Basically I have a UID showing as the name of a group chat, and I want to swap it for a groupId I have saved in firebase at the same level as the Uid.
FirebaseDatabase.getInstance().getReference().child("chat").child(chatId).child("info").child("groupId)
I've been following simcoder youtube video and there's a lot of checks and balances happening between user and chat UIDs and I'm getting lost in the middle of all that.
I've tried adding groupId to the adapter and the chatObject, and I can see the data in debug, but I just can't get it to populate the recycler view. I've had a search of the forums here, but can't quite get it to work.
I'm hoping someone can help me out, many thanks
private RecyclerView mChatList;
private RecyclerView.Adapter mChatListAdapter;
private RecyclerView.LayoutManager mChatListLayoutManager;
ArrayList<ChatObject> chatList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_chat);
OneSignal.startInit(this).init();
OneSignal.setSubscription(true);
OneSignal.idsAvailable(new OneSignal.IdsAvailableHandler() {
#Override
public void idsAvailable(String userId, String registrationId) {
FirebaseDatabase.getInstance().getReference().child("user").child(FirebaseAuth.getInstance().getUid()).child("notificationKey").setValue(userId);
}
});
OneSignal.setInFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification);
Button mLogout = findViewById(R.id.logout);
Button mFindUser = findViewById(R.id.finduser);
mFindUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), FindUserActivity.class));
}
});
mLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OneSignal.setSubscription(false);
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
return;
}
});
getPermissions();
initializeRecyclerView();
getUserChatList();
}
private void getUserChatList(){
DatabaseReference mUserChatDB = FirebaseDatabase.getInstance().getReference().child("user").child(FirebaseAuth.getInstance().getUid()).child("chat");
mUserChatDB.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()){
ChatObject mChat = new ChatObject(childSnapshot.getKey());
boolean exists = false;
for (ChatObject mChatIterator : chatList){
if(mChatIterator.getChatId().equals(mChat.getChatId()))
exists = true;
}
if (exists)
continue;
chatList.add(mChat);
getChatData(mChat.getChatId());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getChatData(String chatId) {
DatabaseReference mChatDB = FirebaseDatabase.getInstance().getReference().child("chat").child(chatId).child("info");
mChatDB.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String chatId = "";
if(dataSnapshot.child("id").getValue() != null)
chatId = dataSnapshot.child("id").getValue().toString();
for(DataSnapshot userSnapshot : dataSnapshot.child("users").getChildren()){
for(ChatObject mChat : chatList)
if(mChat.getChatId().equals(chatId)){
UserObject mUser = new UserObject(userSnapshot.getKey());
mChat.addUserToArrayList(mUser);
getUserData(mUser);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getUserData(UserObject mUser) {
DatabaseReference mUserDb = FirebaseDatabase.getInstance().getReference().child("user").child(mUser.getUid());
mUserDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserObject mUser = new UserObject(dataSnapshot.getKey());
if(dataSnapshot.child("notificationKey").getValue() != null)
mUser.setNotificationKey(dataSnapshot.child("notificationKey").getValue().toString());
for(ChatObject mChat : chatList)
for(UserObject mUserIt : mChat.getUserObjectArrayList()){
if(mUserIt.getUid().equals(mUser.getUid())){
mUserIt.setNotificationKey(mUser.getNotificationKey());
}
}
mChatListAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void initializeRecyclerView() {
chatList = new ArrayList<>();
mChatList = findViewById(R.id.chatList);
mChatList.setNestedScrollingEnabled(false);
mChatList.setHasFixedSize(false);
mChatListLayoutManager = new LinearLayoutManager(getApplicationContext(), RecyclerView.VERTICAL,false);
mChatList.setLayoutManager(mChatListLayoutManager);
mChatListAdapter = new ChatListAdapter(chatList);
mChatList.setAdapter(mChatListAdapter);
}
From what I see you are passing to the adapter an empty list so that's why there's not data to be displayed.
And also, where you are using mChatListAdapter.notifyDataSetChanged();, you don't set before a populated list to the adapter.
I'm not sure which is the data you want to display but you have to collect in a list from the firebase all the information you want to display, for example, if UserObject is what you want, you have to make an ArrayList<UserObject>, to add there all the objects, pass it to the adapter and then call adapter.notifyDataSetChanged() .
You can make function in the adapter, like :
public void setData(ArrayList<YourObject> list){
yourAdapterList = list
this.notifyDataSetChanged()
}
And then call it from your activity/fragment like adapter.setData( /* your populated list */)
I'm using firebase to store the messages under a randomly generated node , messages are successfully added to this node but, it only displays the first message sent.
Here's my class containing the listeners.
I tried changing the Single event listener in get chat id to a value event listener but it didn't solve the problem.
when I close the chat and open it again it shows the first message only.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
currentUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
mMatchId = getIntent().getExtras().getString("MatchId");
mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserId).child("connections").child("matches").child(mMatchId).child("ChatId");
mDatabaseChat = FirebaseDatabase.getInstance().getReference().child("Chat");
getChatId();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setNestedScrollingEnabled(false);
mRecyclerView.setHasFixedSize(false);
mChatLayoutManager = new LinearLayoutManager(ChatActivity.this);
mRecyclerView.setLayoutManager(mChatLayoutManager);
mChatAdapter = new ChatAdapter(getDataSetChat(), ChatActivity.this);
mRecyclerView.setAdapter(mChatAdapter);
mSendEditText = (EditText) findViewById(R.id.message);
mSendButton = (Button) findViewById(R.id.send);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
});
}
private void sendMessage() {
String sendMessageText = mSendEditText.getText().toString();
if(!sendMessageText.isEmpty()){
DatabaseReference newMessageDb = mDatabaseChat.push();
Map newMessage = new HashMap();
newMessage.put("createdByUser", currentUserId);
newMessage.put("text", sendMessageText);
newMessageDb.setValue(newMessage);
}
mSendEditText.setText(null);
}
private void getChatId(){
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
chatId = dataSnapshot.getValue().toString();
mDatabaseChat = mDatabaseChat.child(chatId);
getChatMessages();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void getChatMessages() {
mDatabaseChat.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot t : dataSnapshot.getChildren()) {
String message = null;
String createdByUser = null;
if (t.child("text").getValue() != null) {
message = t.child("text").getValue().toString();
}
if (t.child("createdByUser").getValue() != null) {
createdByUser = t.child("createdByUser").getValue().toString();
}
if (message != null && createdByUser != null) {
Boolean currentUserBoolean = false;
if (createdByUser.equals(currentUserId)) {
currentUserBoolean = true;
}
ChatObject newMessage = new ChatObject(message, currentUserBoolean);
resultChat.add(newMessage);
mChatAdapter.notifyDataSetChanged();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Database image
it is because you first time open the activity and your getChatId() function is called a single time and give you one single id of your single message. and then you pass it on addChildEventListener. so thats y it gives you the single messagr to your recyclerview. if you show ur database schema i will provide youy more specific query
List<Chat> chatMessageList = new ArrayList<>();;
DatabaseReference database = FirebaseDatabase.getInstance()
.getReference()
.child(Common.CHATS);
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatMessageList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chat chat = snapshot.getValue(Chat.class);
assert chat != null;
chatMessageList.add(chat);
mChatAdapter = new ChatAdapter(context, chatMessageList);
mRecyclerView.setAdapter(mChatAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I am having trouble with my Firebase code to add a contact to a user profile. This exact code used to work fine, and now as of today it gets itself into an infinite loop and creates contacts repeatedly until I force kill the application. I can't work out where the loop is, or what may have changed!
Code:
public class AddContacts extends AppCompatActivity {
private EditText addContactNumber;
private Button btnAddContact;
private String userResult, searchPhone, ping_userID;
private FirebaseAuth pingAuth;
DatabaseReference ref;
private FirebaseAuth.AuthStateListener pingAuthListener;
addContactNumber = (EditText) findViewById(R.id.addContactNumber);
btnAddContact = (Button) findViewById(R.id.btnAddContact);
btnAddContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchPhone = addContactNumber.getText().toString();
ref = FirebaseDatabase.getInstance().getReference().child("Profiles");
ref.orderByChild("Phone").equalTo(searchPhone).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
userResult = datas.getKey();
if (userResult != null) {
ping_userID = pingAuth.getCurrentUser().getUid();
DatabaseReference newContact = FirebaseDatabase.getInstance().getReference().child("Profiles").child(ping_userID).child("Contacts");
newContact.setValue(userResult);
DatabaseReference newContactPing = FirebaseDatabase.getInstance().getReference().child("Profiles").child(ping_userID).child("Contacts").child(userResult).child("PingStatus");
newContactPing.setValue(false);
DatabaseReference addRef = FirebaseDatabase.getInstance().getReference().child("Profiles").child(userResult).child("Name");
addRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String resultName = dataSnapshot.getValue(String.class);
DatabaseReference addContactName = FirebaseDatabase.getInstance().getReference().child("Profiles").child(ping_userID).child("Contacts").child(userResult).child("Name");
addContactName.setValue(resultName);
Toast.makeText(getBaseContext(), "User: " + resultName + " added successfully.", Toast.LENGTH_SHORT).show();
ref.removeEventListener(this);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
Toast.makeText(getBaseContext(), "User not found.", Toast.LENGTH_SHORT).show();
ref.removeEventListener(this);
break;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
Also, perhaps as an aside, it never triggers the "User not found" event, even if I enter details that are not in the database.
Any ideas? I am sure it is staring me in the face but I don't see it.
#Peter Haddad Database as requested:
MyAppDatabase
-Profiles
-BCsuC4XAZqVhWj
-Name: "Simon"
-Phone: 123456
-Contacts
-pnYn1NhzzNQAm
-Name: "Bill"
-PingStatus: false
-pnYn1NhzzNQAm
-Name: "Bill"
-Phone: 987654
-Contacts
-BCsuC4XAZqVhWj
-Name: "Simon"
-PingStatus: false
Use addListenerForSingleValueEvent instead of addValueEventListener in both the cases.
I have this firebase database:
That has been created with this code:
private DatabaseReference mDatabase;
private EditText tbfirstname;
private EditText tblastname;
private EditText tbemail;
private Button btnSubmit;
private String str_firstname;
private String str_lastname;
private String str_email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
//GUI DECLARATIONS
tbfirstname = (EditText) findViewById(R.id.tb_firstname);
tblastname = (EditText) findViewById(R.id.tb_lastname);
tbemail = (EditText) findViewById(R.id.tb_email);
btnSubmit = (Button) findViewById(R.id.btn_register);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//HANDLES VALUES FROM TB TO STR
str_firstname = tbfirstname.getText().toString().trim();
str_lastname = tblastname.getText().toString().trim();
str_email = tbemail.getText().toString().trim();
HashMap<String, String> dataMap = new HashMap<String, String>();
dataMap.put("Firstname", str_firstname);
dataMap.put("Lastname", str_lastname);
dataMap.put("Email", str_email);
mDatabase.push().setValue(dataMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this,"Registered Successfully!",Toast.LENGTH_LONG).show();
tbfirstname.setText("");
tblastname.setText("");
tbemail.setText("");
} else {
Toast.makeText(MainActivity.this, "There was an Error. Try Again!", Toast.LENGTH_LONG).show();
}
}
});
}
});
}
It's actually a simple app that let users register some data. What I wanna do is I want to create a search textboxthat will locate specific data in the database based on what the user has entered in that textbox and returns a value.
For example I'll search steve#sample.com, if there is an email in the database that has the same value, I want it to return its root value namely L4JyRA77YKldmMWM-C7. If somehow there is no said record, I want it to return with false or something.
Requirements:I'm really a beginner in Android and Firebase so if you could make the code newbie-friendly, that'll really be a great help. Thanks!
first of all you need to fetch all records from firebase database List<User>
create copy of list List<User> temp = new ArrayList();
you can add particular searchable user detail in temp - temp.add(users.get(i));
Now you can get useremail like this email = temp.get(i).getEmailId();
FirebaseDatabase.getInstance().getReference().child("Your table name").orderByChild("email").equalTo(your searchable emailid ).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
List<User> users = new ArrayList<>();
while (dataSnapshots.hasNext()) {
DataSnapshot dataSnapshotChild = dataSnapshots.next();
User user = dataSnapshotChild.getValue(User.class);
users.add(user);
}
String userids = "";
List<User> temp = new ArrayList();
try {
for (int i = 0; i < users.size(); i++) {
if (users.get(i).getEmailid().equals("your searchable email")) {
temp.add(users.get(i));
//Here you can find your searchable user
Log.e("temp", "+" + temp.get(i).getFirebaseId());
email = temp.get(i).getEmailId();
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e("Logs", e.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("Users").orderByChild("Email").equalTo("editext.getText()");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Some general things to remember is never name nodes with Capital letters
I am developing an android recipe app, User's have the option to only view vegan recipes. I am using Firebase as my Database where I am storing a variable "vegan", in my activity which displays the recipes I am retrieving the value of "vegan" from my database, which can be either "yes" or "no" (line: 54) and then the if statement (line: 65) checks if the user want's vegan recipes or not, however vegan = user.Vegan; does not seem to be changing the variable vegan, I know I am getting the value from the database but it won't change the value of vegan, can anyone tell me where I'm going wrong?
public class SwipeActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
private DatabaseReference mRecipeReference;
private DatabaseReference newRef;
private DatabaseReference myRef3;
private DatabaseReference veganRef;
private TextView editTextName;
private TextView editTextCategory;
private ImageView profileImageView;
private ImageButton Back;
private ImageButton Like;
private ImageButton Dislike;
private DatabaseReference databaseReference;
private DatabaseReference userRef;
String imgURL;
String recipeKey;
Map<String, Recipe> likedRecipes = new HashMap<String,Recipe>();
String user = FirebaseAuth.getInstance().getCurrentUser().getUid();
String vegan = "no"; //Here is the variable declaration
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe);
databaseReference = FirebaseDatabase.getInstance().getReference();
userRef = FirebaseDatabase.getInstance().getReference().child("user").child(user);
mRecipeReference = FirebaseDatabase.getInstance().getReference().child("recipe");
editTextName = (TextView) findViewById(R.id.editTextName);
editTextCategory = (TextView) findViewById(R.id.editTextCategory);
profileImageView = (ImageView) findViewById(R.id.profileImageView);
Back = (ImageButton) findViewById(R.id.Back);
Back.setOnClickListener(this);
Like = (ImageButton) findViewById(R.id.Like);
Like.setOnClickListener(this);
Dislike = (ImageButton) findViewById(R.id.Dislike);
Dislike.setOnClickListener(this);
}
#Override
public void onStart() {
super.onStart();
ValueEventListener userListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
vegan = user.Vegan; //Here I am retrieving the string from firebase database, which is either "yes" or "no"
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
userRef.addValueEventListener(userListener);
if (vegan == "yes") { //Here I am checking if the user is vegan or not
veganRef = databaseReference.child("recipe");
veganRef.orderByChild("Category").equalTo("Vegan").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot recipeSnapshot : dataSnapshot.getChildren()) {
Recipe recipe = recipeSnapshot.getValue(Recipe.class);
recipeKey = recipeSnapshot.getKey();
editTextName.setText(recipe.Name + ", " + recipe.Calories);
editTextCategory.setText(recipe.Category);
imgURL = recipe.Img;
Picasso.with(getApplicationContext()).load(imgURL)//download URL
.placeholder(R.drawable.placeholder_image)//use default image
.error(R.drawable.placeholder_image)//if failed
.into(profileImageView);//imageview
likedRecipes.put(recipeKey, recipe);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
}
}
}
The problem is more than likely that onDataChange hasn't been called by time you check vegan in that if statement. Callbacks like that are asynchronous so you will need to wait for callback before performing any logic that's dependent on result.
In general what you're running in to is something many people moving to Firebase from SQL background encounter when trying to map over "joins" like this to the nested queries that Firebase requires. Probably outside scope of this particular question but use of RxJava makes managing set of operations like this much easier (for example that have async responses and 2nd query needs to use response of first one).
In your onStart() do something like this
#Override
public void onStart() {
super.onStart();
ValueEventListener userListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
vegan = user.Vegan;
if (vegan == "yes") { //Here I am checking if the user is vegan or not
veganRef = databaseReference.child("recipe");
veganRef.orderByChild("Category").equalTo("Vegan").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot recipeSnapshot : dataSnapshot.getChildren()) {
Recipe recipe = recipeSnapshot.getValue(Recipe.class);
recipeKey = recipeSnapshot.getKey();
editTextName.setText(recipe.Name + ", " + recipe.Calories);
editTextCategory.setText(recipe.Category);
imgURL = recipe.Img;
Picasso.with(getApplicationContext()).load(imgURL)//download URL
.placeholder(R.drawable.placeholder_image)//use default image
.error(R.drawable.placeholder_image)//if failed
.into(profileImageView);//imageview
likedRecipes.put(recipeKey, recipe);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
userRef.addValueEventListener(userListener);
}