Firebase Query for RecyclerView - android

I want to get Date of "Friends" very 1st child/child. For this, i wrote query as
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Friends").child("SQyOq80egYehjqx4sgiyeNcW8P02");
in the above query, i want to specifically get date of "SQyOq80egYehjqx4sgiyeNcW8P02". How can i do that? Above query not working.
i've previously write these values by this code:
final String currentDate = DateFormat.getDateInstance().format(new Date());
mFriendDatabase.child(mCurrent_user.getUid()).child(user_id).setValue(currentDate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
mFriendDatabase.child(user_id).child(mCurrent_user.getUid()).setValue(currentDate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
mFriendReqDatabase.child(mCurrent_user.getUid()).child(user_id).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mFriendReqDatabase.child(user_id).child(mCurrent_user.getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mProfileSendReqBtn.setEnabled(true);
mCurrent_state = "friends";
mProfileSendReqBtn.setText("UnFriend");
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
}
});
}
});
}
});
}
});
}
Recycler code:
FirebaseRecyclerOptions<Friends> options =
new FirebaseRecyclerOptions.Builder<Friends>()
.setQuery(query, Friends.class)
.build();
Log.d("sdfsdfsdf", options.getSnapshots().toString());
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Friends, FriendsViewHolder>(options) {
#Override
public FriendsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter_users_activity_layout, parent, false);
return new FriendsViewHolder(view);
}
#Override
protected void onBindViewHolder(final FriendsViewHolder friendsViewHolder, int position, Friends friends) {
// Log.d("sdfsdfdf", friends.getDate().toString());
friendsViewHolder.setDate(friends.getDate());

If you want to find some value using Query
Query applyQuery = ref.child("Friends").orderByChild("Wed5qPTC.....").equalTo("Value for Check");
applyQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap: dataSnapshot.getChildren()) {
//You will get your value in snap
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("Realtime", "onCancelled", databaseError.toException());
}
});

Assuming that SQyOq80egYehjqx4sgiyeNcW8P02 is user the id of the user that is logged in, to get value of wed5 ... 43v1, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Friends").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String date = ds.getValue(String.class);
Log.d(TAG, date);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be:
Sept 29, 2018
If SQyOq80egYehjqx4sgiyeNcW8P02 is another random generated id, in this case please use the following reference:
DatabaseReference uidRef = rootRef.child("Friends").child("SQyOq80egYehjqx4sgiyeNcW8P02");

Related

RecyclerView items not Displayed in my MainActivity

I'm building a chat app which have post feature, When I create a post in NewPostActivity, the image and text are uploaded (because I can see them in firebase Database tree) but The problem is nothing is shown in my MainActivity which is supposed to display my posts.
I used Firebase UI for the Rv but I'm not sure is the problem lies in NewPostActivity or the MainActivity.
I tried to run the debugger to see but there is no error or null point exception.
NewPostActivity.java
btnPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startPosting();
}
});
}
private void startPosting() {
progressDialog=new ProgressDialog(NewPostActivity.this);
progressDialog.setTitle("Uploading Image");
progressDialog.setMessage("Please Wait while we process the image");
progressDialog.setCanceledOnTouchOutside(false);
final String desc_val=mPostDesc.getText().toString().trim();
if(!TextUtils.isEmpty(desc_val) && mImageUri!=null){
progressDialog.show();
String random_name= random();
StorageReference filepath = storageReference.child("Blog_Images").child(random_name);
filepath.putFile(mImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
Task<Uri> uriTask = task.getResult().getStorage().getDownloadUrl();
while (!uriTask.isComplete());
final Uri downloadUrl = uriTask.getResult();
final DatabaseReference newPost = mRootRef.child("Blog").push();
final String user_id= mCurrentUser.getUid();
mRootRef.child("Users").child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
newPost.child("desc").setValue(desc_val);
newPost.child("image").setValue(downloadUrl.toString());
newPost.child("user_id").setValue(user_id);
newPost.child("timestamp").setValue(ServerValue.TIMESTAMP);
newPost.child("username").setValue(dataSnapshot.child("name").getValue());
newPost.child("thumb_image").setValue(dataSnapshot.child("thumb_image").getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
progressDialog.dismiss();
startActivity(new Intent(NewPostActivity.this,MainActivity.class));
finish();
}
});
}
}
MainActivity.java
Query conversationQuery = mDatabase.orderByChild("timestamp");
FirebaseRecyclerOptions<Blog> options = new FirebaseRecyclerOptions.Builder<Blog>()
.setQuery(conversationQuery, Blog.class)
.build();
FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(options) {
#NonNull
#Override
public BlogViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.post_single_layout, parent, false);
mAuth = FirebaseAuth.getInstance();
return new BlogViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull final BlogViewHolder viewHolder, int position, #NonNull final Blog model) {
viewHolder.setContext(getApplicationContext());
final String list_blog_id = getRef(position).getKey();
viewHolder.setLikeBtns(list_blog_id);
Query lastMessageQuery = mDatabase.child(list_blog_id).limitToLast(1);
lastMessageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
viewHolder.setDesc(model.getDesc());
viewHolder.setImage(model.getImage());
viewHolder.setUsername(model.getUsername());
viewHolder.setStatus(model.getStatus());
viewHolder.setPostImage(model.getThumb_image());
viewHolder.setTime(model.getTimestamp());
userID = model.getUid();
}
#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) {
}
});
viewHolder.postImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent imageFullScreen = new Intent(getApplicationContext(), PhotoActivity.class);
imageFullScreen.putExtra("uid", list_blog_id);
imageFullScreen.putExtra("from", "RequestsFragment");
startActivity(imageFullScreen);
}
});
viewHolder.mLikeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessLike = true;
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike) {
if (dataSnapshot.child(list_blog_id).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseLike.child(list_blog_id).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessLike = false;
} else {
mDatabaseLike.child(list_blog_id).child(mAuth.getCurrentUser().getUid()).setValue("Lliked");
mProcessLike = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
};
mBlogList.setAdapter(firebaseRecyclerAdapter);
}
There is some parts of your code that are not shown, also as I don't see a screenshot of your database I don't know if I will give a correct answer, but obviously you need to start listening to the database before you get the data with firebase UI.
So before this:
mBlogList.setAdapter(firebaseRecyclerAdapter);
Add this:
firebaseRecyclerAdapter.startListening();
Refer to this to know more about how to set your firebase UI.

Firebase Realtime Database delete specific user

I wish to delete specific user with phone number X from my DB. And insted my code deletes all of them.
Here is my DB:
Code:
private static void deleteUser(final Context context, final String phoneNumber) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users");
Query usersQuery = databaseReference.orderByChild("phone").equalTo(phoneNumber);
usersQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.getRef().removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d(TAG, "Deleted");
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled", databaseError.toException());
}
});
}
Maybe it is not clear with my comment, so I am putting this as an answer, the full code that should not be having the problem you're facing, should look something like this:
usersQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
ds.getRef().removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d(TAG, "Deleted");
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled", databaseError.toException());
}
});
That's because you're using a singleValueEventListener. If the query matches multiple children, it returns a list of all those children.
Even if there's only a single matches child, it's still a list of one. And since you're calling getRef() on that list, you get the key of the location where you ran the query.

Firebase join using Android Studio

I need to do join operation for data using the unique key provided by the Firebase database.Table habitat is created under the unique key of snake table.And also need to retrive data for list view or recyclerview.
databaseSnake = FirebaseDatabase.getInstance().getReference()
.child("snake")
.orderByKey()
.addValueEventListener(
new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot child : dataSnapshot.getChildren())
{
// HERE CORRESPONDS TO JOIN
DatabaseReference Databasesnake = FirebaseDatabase.getInstance().getReference()
.child("habitat")
.orderByKey()
.addValueEventListener(
new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
// repeat!!
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}

Retrieving data from a firebase database with multiple nodes

I was trying to retrieve the data from user and time. But I can't access the data, it's not really accessing the database.
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_balance);
mFirebaseDatabase=FirebaseDatabase.getInstance();
cashRef=mFirebaseDatabase.getReference().child("ASSETS").child("cash_at_bank");
TextView view=(TextView)findViewById(R.id.view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cashRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int time=dataSnapshot.getValue(int.class);
int values =dataSnapshot.getValue(int.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
To get the time, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference cashAtBankRef = rootRef.child("ASSETS").child("Cash at bank");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Long time = ds.child("time").child("time").getValue(Long.class);
Log.d("TAG", time + "");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
cashAtBankRef.addListenerForSingleValueEvent(eventListener);
The output will be:
150555043995
//and so on

firebase, database, android studio: Not reading data from firebase database

I have data in database:
database in firebase
I want read all child (Belgia, Czechy, Polska...) and display it in Text Field, but AFTER click the button (I don't change data in database).
The button have assigned below function:
public void f_btn_zaczytaj_dane(View view) {
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
TextView txt_opis_panstwa = (TextView) findViewById(R.id.txt_opis_panstwa);
txt_opis_panstwa.setText(value);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Befrore i write in code:
FirebaseDatabase database;
DatabaseReference myRef;
database = FirebaseDatabase.getInstance();
myRef = database.getReference("kraj");
Unfortunately, when I press the button nothing happens.
I will be grateful for the help
Regards, Marcin
You have to iterate through your children
public void f_btn_zaczytaj_dane(View view) {
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
TextView txt_opis_panstwa = (TextView) findViewById(R.id.txt_opis_panstwa);
for (DataSnapshot country : dataSnapshot.getChildren()) {
txt_opis_panstwa.append(country.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference krajRef = rootRef.child("flagiistolice").child("kraj");
public void f_btn_zaczytaj_dane(View view) {
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
TextView txt_opis_panstwa = (TextView) findViewById(R.id.txt_opis_panstwa);
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String country = ds.getkey();
txt_opis_panstwa.append(country);
Log.d("TAG", country);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
krajRef.addListenerForSingleValueEvent(eventListener);
}

Categories

Resources