How to retrieve data from firebase , without changes in the data? - java

// This is the MainActivity, I have used firebase to store sample data, where I can update and retrieve.
But retrieval of data is possible only when there is a data change,but I want to see my data which is in firebase already
here is the data base structure]1
public class MainActivity extends
AppCompatActivity {
EditText name,weight;
Button uploadBtn;
TextView itemName,itemWeight;
DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference();
Map<String,String>values=new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=findViewById(R.id.inputItemName);
weight=findViewById(R.id.inputItemWeight);
uploadBtn=findViewById(R.id.uploadButton);
itemName=findViewById(R.id.resultName);
itemWeight=findViewById(R.id.resultWeight);
// Here as you can see I have used an ValueEventListener to show the retrieve values from database before uploading the new Values But it is not working , unless the values of data are changed (that is it works only after uploading new values).
ValueEventListener valueEventListener=new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String nameD=(String) dataSnapshot.child("Name").getValue();
String weightD = (String) dataSnapshot.child("Weight").getValue();
itemName.setText(nameD);
itemWeight.setText(weightD+" Kg");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
databaseReference.addListenerForSingleValueEvent(valueEventListener);
uploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
values.put("Name",name.getText().toString());
values.put("Weight",weight.getText().toString());
databaseReference.child("UToouch").setValue(values);
}
});
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String nameDb=(String) dataSnapshot.child("Name").getValue();
String weightDb = (String) dataSnapshot.child("Weight").getValue();
itemName.setText(nameDb);
itemWeight.setText(weightDb+" Kg");
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}

To be able to get values of your Name and Weight properties, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("UToouch");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("Name").getValue(String.class);
String weight = dataSnapshot.child("Weight").getValue(String.class);
Log.d(TAG, name + " / " + weight);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
ref.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be:
rittesh / pv

Related

Retrieve specific data

private TextView welcomeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
database = FirebaseDatabase.getInstance();
databaseReference = database.getReference("Users").child("name");
welcomeText = (TextView) findViewById(R.id.welcomeText);
getData();
}
private void getData() {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String name = snapshot.getValue(String.class);
welcomeText.setText("Welcome" + " " + name);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(ProfileActivity.this, "Fail to get data.", Toast.LENGTH_SHORT).show();
}
});
}
https://i.stack.imgur.com/RZkvW.png
So basically, I want to set the "welcomeText" to Welcome "name" from the Firebase.
But the outcome always come out Null.

Compare two different child nodes from two different parent nodes

I am trying to compare two different child nodes from two different parent nodes. The JSON structure is the following: Attending Event > postId > userId and the second one is structured as follows: Following > firebaseUserId > userId. The goal here is to compare the userId's and if I am following that userId and also that person / userId IS attending the event, then I want to populate a list with those users.
I already wrote two methods, one to get the users that I am following getFollowing(); and another to get the users that are attending the event getAttendingEvent();. Is there a way to compare the lists / usersIds from the two methods I have already written, or do I have to write a new method entirely?
I´m really not sure how to go about this… Am I on the right track with the getFriendsAttendingEvent(); method I just wrote?
FollowersActivity
public class FollowersActivity extends AppCompatActivity {
String mId;
String mTitle;
String mPostId;
List<String> mIdList;
RecyclerView mRecyclerView;
UserAdapter mUserAdapter;
List<User> mUserList;
FirebaseUser mFirebaseUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_followers);
mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
Intent intent = getIntent();
mId = intent.getStringExtra("id");
mTitle = intent.getStringExtra("title");
mPostId = intent.getStringExtra("postid");
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(mTitle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(v -> finish());
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUserList = new ArrayList<>();
mUserAdapter = new UserAdapter(this, mUserList, false);
mRecyclerView.setAdapter(mUserAdapter);
mIdList = new ArrayList<>();
switch (mTitle) {
case "Likes":
getLikes();
break;
case "Following":
getFollowing();
break;
case "Followers":
getFollowers();
break;
case "Attending Event":
getAttendingEvent();
case "Friends Attending":
// Create this method
}
}
private void getFriendsAttendingEvent(List<User> userList, List<User> userList1) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Attending Events").child(mPostId);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
userList.add(user);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference("Following").child(mFirebaseUser.getUid());
reference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user1 = snapshot.getValue(User.class);
userList1.add(user1);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
// Compare the two lists user's somehow..
if (userList.equals(userList1)) {
showUsers();
}
}
private void getLikes() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Likes").child(mPostId);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mIdList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mIdList.add(snapshot.getKey());
}
showUsers();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getAttendingEvent() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Attending Event").child(mPostId);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mIdList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mIdList.add(snapshot.getKey());
}
showUsers();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getFollowing() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Following").child(mFirebaseUser.getUid());
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mIdList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mIdList.add(snapshot.getKey());
}
showUsers();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getFollowers() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Followers").child(mId);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mIdList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mIdList.add(snapshot.getKey());
}
showUsers();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showUsers() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUserList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
for (String id : mIdList) {
if (user != null)
if (user.getId().equals(id)) {
mUserList.add(user);
}
}
}
mUserAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}

Firebase does not work at the first time?

I want to generate a report pdf counting on total Orders and orders with status wanted
I have this code to create pdf and fill table out
private TemplatePDF templatePDF;
FirebaseDatabase database;
DatabaseReference reference;
Button btnRatio1;
ArrayList<String[]> rowqa=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reportes);
database=FirebaseDatabase.getInstance();
reference=database.getReference("Requests");
btnRatio1=findViewById(R.id.Quality);
btnRatio1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reference.orderByChild("date").startAt("1530002755582").endAt("1530504865654").
addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
createTemplate(rowqa);
}
});
}
private void showData(DataSnapshot dataSnapshot){
int total=(int)dataSnapshot.getChildrenCount();
int count=0;
String[]row;
for (DataSnapshot myDataSnapshot : dataSnapshot.getChildren())
{
Request rq = myDataSnapshot.getValue(Request.class);
if (rq.getStatuscali().equals("0"))
{
count++;
}
}
row= new String[]{Common.getDate(Long.parseLong("1529945980802")),String.valueOf(count),String.valueOf(total),""+ count/total};
addRow(row);
}
private void createTemplate(ArrayList<String[]> rowqa) {
TemplatePDF templatePDF1 = new TemplatePDF(getApplicationContext());
templatePDF1.openDocument("Quality");
templatePDF1.addTitles("Frutifelles E.I.R.L.","Calidad de pedidos generados","25/06/2018");
templatePDF1.createTable(header,rowqa);
templatePDF1.closeDocument();
templatePDF1.viewPDF();
}
private void addRow(String[]row){
rowqa.add(row);
}
The first time show me my pdf this way
But the second time show me correctly
It seems like first time it doesn't work
just as #Jen Person said, you should put the createTemplate(rowqa) inside the onDataChange callback, else when you click the button at the first time, the rowqa is empty, so createTemplate(rowqa) will get an empty PDF.
an example:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reportes);
btnRatio1=findViewById(R.id.Quality);
btnRatio1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// dateStart, dateEnd should be instance fields
queryData(dateStart, dateEnd);
}
});
}
private void queryData(String dateStart, String dateEnd) {
database=FirebaseDatabase.getInstance();
reference=database.getReference("Requests");
reference.orderByChild("date")
.startAt(dateStart)
.endAt(dateEnd)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
showData(dataSnapshot);
createTemplate(rowqa);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}

Getting child count in Firebase

Please how do I simply get the child count from a firebase Query. For example Let's say I use a database query with 10 children, how do I get that value because I tried using onChildChanged and getting the value from the snapshot, but it does not work well. This is because at first it will get the number, then it will query again because it has to continuously sync, but because there is not actual child change at the second query it return a value if zero which will replace the original correct value. :/
databaseReference.child("PrinterView").child(uni).child(phone).orderByChild("done").equalTo("No").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Toast.makeText(getActivity(),"Number:"+String.valueOf(dataSnapshot.getChildrenCount()),Toast.LENGTH_LONG).show();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Both don't work
databaseReference.child("PrinterView").child(uni).child(phone).orderByChild("done").equalTo("No").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Toast.makeText(getActivity(),"Number:"+String.valueOf(dataSnapshot.getChildrenCount()),Toast.LENGTH_LONG).show();
Vendor_view_Home_fragment.printIndicator.setText(String.valueOf(dataSnapshot.getChildrenCount()));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Assuming that PrinterView is a direct child of your Firebase root, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("PrinterView").child("Covenant University").child("588");
Query query = yourRef.orderByChild("done").equalTo("No");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long count = dataSnapshot.getChildrenCount();
Log.d("TAG", String.valueOf(count));
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(eventListener);
The problem was this line:
databaseReference.child("PrinterView").child(uni).child(phone).orderByChild("done").equalTo("No").addValueEventListener(new ValueEventListener()
The variable "uni" and "phone" was also provided by a firebase Query E.G It was to get the University and phone number of the current user so I could not just put a static string there.
databaseReference.child("Users").child(mAuth.getCurrentUser().getUid()).child("Phone").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
phone = dataSnapshot.getValue().toString();
// Toast.makeText(getActivity(), phone, Toast.LENGTH_LONG).show();
setPendingList();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
So the issue was that, if the network connection was slow or if the queries were not done yet, those two variables would be empty thereby making the dataSnapshot empty. I will have to sort that out by only allowing that to be queried when the rest are sure to be done. :)

Firebase database how to get some value from 1 reference and equals to 2 reference to get its keys and values

I have users info as show below
I want to to check if commentWriterUid is equals to one from users key to get its info
I tried this:
Query query = mDatabaseReference_comments.orderByChild("commentWriterUid").equalTo(FirebaseUtil.getUsersReference().getKey());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userModel = dataSnapshot.getValue(UserModel.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mFirebaseRecyclerAdapter = new FirebaseRecyclerAdapter<CommentModel, CommentViewHolder>(CommentModel.class,
R.layout.layout_comment,
CommentViewHolder.class,
mDatabaseReference_comments) {
#Override
protected void populateViewHolder(CommentViewHolder viewHolder, CommentModel model, int position) {
Glide.with(PostCommentActivity.this)
.load(userModel.getUserImageUrl())
.into(viewHolder.mCircleImageView_commentWriterImage);
viewHolder.mTextView_commentWriterName.setText(userModel.getUserName());
viewHolder.bindToPost(PostCommentActivity.this, model);
}
};
But I get these errors:
03-04 02:24:34.558 31063-31063/com.app E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.app.PostCommentActivity$4.populateViewHolder(PostCommentActivity.java:119)
at com.app.PostCommentActivity$4.populateViewHolder(PostCommentActivity.java:113)
No one answer my question so i figured it my own and answer this so it may be helpful for others
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
final DatabaseReference root_ref = firebaseDatabase.getReference();
root_ref.child("comments").child("KeKwGa5btKuDYr3yYq5").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String commentWriterUid = dataSnapshot.child("commentWriterUid").getValue().toString();
root_ref.child("users").equalTo(commentWriterUid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Do all stuff you went
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Categories

Resources