I'm trying to retrieve some simple data from my database as an Admin, the data has been retrieved, but nothing is shown on the recyclerview.
In the other hand, i was trying to assign a value (String) from the database to a TextView, i was recieving the value, but the TextView was empty, i went to the .xml file and changed the layout_width from android:layout_width="wrap_content" to android:layout_width="match_parent" and it worked! Before that with the simple Firebase Client SDK it was showing the texte even with android:layout_width="wrap_content"
PS: Since i started using the Firebase Admin SDK, I didn't had any issues with writing data to the Realtime database, Or with creating Users. I tried both of them and they works fine.
Here's the retrieving function :
private void RetriveClasses() {
// Get a reference to our posts
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("Classrooms");
mclassrooms.clear();
// Attach a listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
Classroom post = snapshot.getValue(Classroom.class);
if (!post.getDeleted().equals("true"))
{
mclassrooms.add(post);
}
mAdapter.notifyDataSetChanged();
System.out.println(post.getClassName());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
}
The System.out.println(post.getClassName()); Shows :
I/System.out: L1 ST 2022-2023
L1 ST 2021-2022
L1 ST 2015-2016
These are the class names i'm looking for, which means the reading is succeed, but the recyclerview still won't show any items.
here's my Adapter:
public class ClassroomsAdapter extends RecyclerView.Adapter<ClassroomsAdapter.ViewHolder> {
private Context c;
public List<Classroom> mclassrooms;
public ClassroomsAdapter(List<Classroom> mclassrooms) {
this.mclassrooms = mclassrooms;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
this.c = parent.getContext();
View view = LayoutInflater.from(c).inflate(R.layout.classroom_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final Classroom classroom = mclassrooms.get(position);
if (classroom.getClassName().length() >= 20)
{
String className = classroom.getClassName();
holder.classroom_name.setText(className.substring(0,19) + "...");
}
else
{
holder.classroom_name.setText(classroom.getClassName());
}
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(c, R.style.BottomSheetDialogTheme);
View eview = LayoutInflater.from(c).inflate(R.layout.bottom_menu_classroom, null);
eview.findViewById(R.id.Delete_Comment_Btn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ProgressDialog progressDialog = new ProgressDialog(c, R.style.MyAlertDialogStyle);
progressDialog.setTitle("Suppression");
progressDialog.setMessage("Traitement...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
DatabaseReference mRoot = FirebaseDatabase.getInstance().getReference("Classrooms");
mRoot.child(classroom.getClassId()).child("deleted").setValue("true", new DatabaseReference.CompletionListener(){
#Override
public void onComplete(DatabaseError error, DatabaseReference ref) {
progressDialog.dismiss();
Toast.makeText(c, "Suppression avec succès!", Toast.LENGTH_SHORT).show();
bottomSheetDialog.dismiss();
}
});
}
});
eview.findViewById(R.id.copy_comment_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final BottomSheetDialog bs = new BottomSheetDialog(c, R.style.BottomSheetDialogTheme);
View aview = LayoutInflater.from(c).inflate(R.layout.edit_class_name, null);
EditText name_et = aview.findViewById(R.id.Edition_Comment_Input_Field);
name_et.setText(classroom.getClassName());
aview.findViewById(R.id.update_comment).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (name_et.getText().toString().isEmpty()) {
Toast.makeText(c, "Ce champ est requis*", Toast.LENGTH_SHORT).show();
} else {
final ProgressDialog progressDialog = new ProgressDialog(c, R.style.MyAlertDialogStyle);
progressDialog.setTitle("Mise à jour");
progressDialog.setMessage("Traitement...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
DatabaseReference mRoot = FirebaseDatabase.getInstance().getReference("Classrooms");
mRoot.child(classroom.getClassId()).child("className").setValue(name_et.getText().toString(), new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError error, DatabaseReference ref) {
progressDialog.dismiss();
Toast.makeText(c, "Mise à jour avec succès!", Toast.LENGTH_SHORT).show();
bs.dismiss();
bottomSheetDialog.dismiss();
}
});
}
}
});
aview.findViewById(R.id.close_edit_comment).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bs.dismiss();
}
});
bs.setContentView(aview);
bs.show();
}
});
bottomSheetDialog.setContentView(eview);
bottomSheetDialog.show();
return false;
}
});
}
#Override
public int getItemCount() {
return mclassrooms.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView classroom_name;
public ViewHolder(#NonNull View itemView) {
super(itemView);
classroom_name = itemView.findViewById(R.id.class_name);
}
}
}
Thanks for your time.
Related
I have CardViews in RecyclerView and each one has a delete button, when clicked it deletes data from database, remove item from ArrayList on that position and runs the animation.
When deleted it dissapears and creates a copy of it self ,Toast shows that ArrayList is empty/ without that item, but its still there I can click on it and everything, only after refreshing fragment(Changing to another fragment in bottom navigation tab or clicking on the same one) it dissapears.
This is my Adapter:
public class KitAdapter extends RecyclerView.Adapter<KitAdapter.MyViewHolder> {
Context context;
ArrayList<Kit> kitList;
OnKitClickListener clickListener;
FirebaseFirestore db;
FirebaseAuth mAuth;
FirebaseStorage FS;
String userID, saveShare;
ArrayList<String> DRList;
public KitAdapter(Context context, ArrayList<Kit> kitList, OnKitClickListener clickListener, String saveShare, ArrayList<String> DRList) {
this.context = context;
this.kitList = kitList;
this.clickListener = clickListener;
this.saveShare = saveShare;
this.DRList = DRList;
}
public ArrayList<Kit> getKitList() {
return kitList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.kitview, parent, false);
return new MyViewHolder(v, clickListener);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Kit kit = kitList.get(position);
db = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
FS = FirebaseStorage.getInstance();
this.userID = kit.getUserID();
holder.Name.setText(kit.getName());
holder.kcal.setText(kit.getKcalM() / kit.getSavedDays() + "kcal");
holder.prot.setText(kit.getProtM() / kit.getSavedDays() + "g");
holder.uh.setText(kit.getUhM() / kit.getSavedDays() + "g");
holder.mast.setText(kit.getMastM() / kit.getSavedDays() + "g");
holder.numOfDays.setText("Broj dana " + kit.getSavedDays() + "");
holder.NameS = kit.getName();
holder.kcalS = String.valueOf(kit.getKcalM());
holder.protS = String.valueOf(kit.getProtM());
holder.uhS = String.valueOf(kit.getUhM());
holder.mastS = String.valueOf(kit.getMastM());
holder.dayNums = kit.getSavedDays();
holder.DRlist = this.DRList;
holder.userID = this.userID;
if(saveShare.equals("Saved")){
if(kit.getShared().equals("No")) {
holder.saveShare.setImageResource(R.drawable.ic_upload_black_24dp);
holder.saveShare.setTag(R.drawable.ic_upload_black_24dp);
}else{
holder.saveShare.setImageResource(R.drawable.ic_file_download_done_black_24dp);
holder.saveShare.setTag(R.drawable.ic_file_download_done_black_24dp);
}
if(!userID.equals(mAuth.getCurrentUser().getUid())){
holder.saveShare.setVisibility(View.GONE);
}
}else if(saveShare.equals("Search")){
holder.saveShare.setImageResource(R.drawable.ic_file_download_black_24dp);
holder.saveShare.setTag(R.drawable.ic_file_download_black_24dp);
holder.delete.setVisibility(View.GONE);
if(DRList.contains(holder.NameS)){
holder.saveShare.setImageResource(R.drawable.ic_file_download_done_black_24dp);
holder.saveShare.setTag(R.drawable.ic_file_download_done_black_24dp);
}
}
db.collection("Users Data")
.document(this.userID)
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
User user = task.getResult().toObject(User.class);
String userName = user.getUsername();
holder.userName.setText(userName);
}
});
FS.getReference().child(this.userID + ".jpg")
.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(#NonNull Uri uri) {
Picasso.get().load(uri).into(holder.pfp);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
holder.pfp.setImageResource(R.drawable.ic_person_black_24dp);
}
});
}
#Override
public int getItemCount() {
return kitList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView Name, numOfDays, kcal, prot, uh, mast, userName;
ImageView saveShare, delete;
String NameS, kcalS, protS, uhS, mastS, userID;
int dayNums;
OnKitClickListener onKitListener;
CircleImageView pfp;
ArrayList<String> DRlist;
public MyViewHolder(#NonNull View itemView, OnKitClickListener onKitListener) {
super(itemView);
Name = itemView.findViewById(R.id.kitName);
numOfDays = itemView.findViewById(R.id.dayNum);
kcal = itemView.findViewById(R.id.kcal);
prot = itemView.findViewById(R.id.prot);
uh = itemView.findViewById(R.id.uh);
mast = itemView.findViewById(R.id.mast);
userName = itemView.findViewById(R.id.userName);
pfp = itemView.findViewById(R.id.pfp);
saveShare = itemView.findViewById(R.id.saveShare);
delete = itemView.findViewById(R.id.delete);
this.onKitListener = onKitListener;
itemView.setOnClickListener(this);
saveShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onKitListener.onKitAdd(getAdapterPosition(), saveShare, Name.getText().toString());
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onKitListener.onKitDelete(getAdapterPosition(), (CardView) itemView, userID);
}
});
}
#Override
public void onClick(View v) {
onKitListener.onKitClick(getAdapterPosition(), NameS, kcalS, protS, uhS, mastS, dayNums);
}
}
public interface OnKitClickListener{
void onKitClick(int position, String NameS, String kcalS, String protS, String uhS, String mastS, int dayNums);
void onKitAdd(int position, ImageView addShare, String NameS);
void onKitDelete(int position, CardView card, String userID);
}
}
This is part of code in fragment that deletes item:
#Override
public void onKitDelete(int position, CardView card, String userID) {
Handler handler = new Handler();
if(userID.equals(mAuth.getCurrentUser().getUid())) {
db.collection("Users Data")
.document(userID)
.collection("Kits")
.whereEqualTo("name", kitlist.get(position).getName())
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (!task.isSuccessful()) {
return;
}
task.getResult().getDocuments().get(0).getReference()
.delete();
}
});
}else{
db.collection("Users Data")
.document(mAuth.getCurrentUser().getUid())
.collection("Saved Kits")
.document(kitlist.get(position).getName())
.delete();
}
Toast.makeText(getContext(), kitlist.toString(), Toast.LENGTH_SHORT).show();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Animation anim = AnimationUtils.loadAnimation(getContext(), R.anim.zoomout);
card.startAnimation(anim);
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(kitlist.isEmpty()){
emptTxt.setVisibility(View.VISIBLE);
kitlist.remove(position);
rec.removeViewAt(position);
adapter.notifyItemRemoved(position);
}
}
},300);
}
}, 150);
}
I tried these combinations:
kitlist.remove(position);
rec.removeViewAt(position);
adapter.notifyItemRemoved(position);
//This one you can see in code above
kitlist.remove(position);
adapter.notifyDataSetChange(position)
And tried making onKitDelete default and using notfiy()/notifyAll()
public interface OnKitClickListener{
void onKitClick(int position, String NameS, String kcalS, String protS, String uhS, String mastS, int dayNums);
void onKitAdd(int position, ImageView addShare, String NameS);
default void onKitDelete(int position, CardView card, String userID){
notify();
}
}
I always get same resoult.
that's easy to update your recycler view with
android ViewModel architechtureAndroid ViewModel Docs
This is my firebase storage image and I want to display all images from url into gridview by taking the current user id
This is my main activity onstart() that leads to adapter class.
I want to show all the images under current user id like grid view.
How to display all user image posts in grid view from firebase above image.
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
uploads = new ArrayList<Blog>();
if (currentUser != null && !currentUser.isAnonymous()) {
mUserf.child("online").setValue("true");
mProgressbar.setMessage("Welcome.....");
mProgressbar.show();
mProgressbar.dismiss();
ConnectivityManager check = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = check.getActiveNetworkInfo(); //for checking whether app is connected to a network or not..
if(info!=null && info.isConnected()) {
//Toast.makeText(MainActivity.this, "network available", Toast.LENGTH_SHORT).show();
firebaseAuth.addAuthStateListener(authStateListener);
mProgressbar.setMessage("Fetching Blogs.....");
mProgressbar.show();
mProgressbar.dismiss();
list = new ArrayList<>();
adapter = new MyCustomAdapter(this,list,firebaseAuth,mdatabaseReference,likesdatabaseReference);
recyclerView = (RecyclerView) findViewById(R.id.blog_list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
alpha = FirebaseDatabase.getInstance().getReference().child("Blog").child(mAuth.getCurrentUser().getUid());
mchildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
mProgressbar.dismiss();
String j = dataSnapshot.getKey();
Log.v("GETKEYZZZ", j);
Blog friendlyMessage = dataSnapshot.getValue(Blog.class);
friendlyMessage.setPostkey(j);
list.add(friendlyMessage);
adapter.notifyDataSetChanged();
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
public void onChildRemoved(DataSnapshot dataSnapshot){}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
public void onCancelled(DatabaseError databaseError) {}
};
mquery.addChildEventListener(mchildEventListener);
} else {
//Toast.makeText(MainActivity.this, "No network available", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"Please Check Your Internet Connection", Toast.LENGTH_LONG).show();
}
// mDatabseUsers.child("online").setValue("true");
} else {
Intent user1 = new Intent(MainActivity.this, LoginActivity.class);
startActivity(user1);
}
}
This is my adapter class where
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.myviewholder> {
Context context;
ArrayList<Blog> list;
List <String> imageUrls;
//List<String> imageUrls ;
LayoutInflater inflator;
int lastPosition = 1;
boolean mprogressLike = true,mprogressview = true;
DatabaseReference likeDatabaseReference;
FirebaseAuth firebaseAuth;
DatabaseReference blogDatabaseReference;
public MyCustomAdapter(Context context, ArrayList<Blog> list,FirebaseAuth firebaseAuth,DatabaseReference blogDatabaseReference, DatabaseReference likeDatabaseReference) {
this.context=context;
this.list=list;
inflator=LayoutInflater.from(context);
this.likeDatabaseReference=likeDatabaseReference;
this.firebaseAuth=firebaseAuth;
this.blogDatabaseReference=blogDatabaseReference;
}
#Override
public myviewholder onCreateViewHolder(ViewGroup parent, int position) {
View v=inflator.inflate(R.layout.posts,parent,false);//this view will contain appearance of each layout i.e each row..
myviewholder holder=new myviewholder(v);// we are passing the view of each row to the myviewholder class
return holder;
}
#Override
public void onBindViewHolder(final myviewholder holder, int position) {//here we will inflate datas in the widgets i.e image and title..
//It is called for each row..so every row is inflated here..
final Blog p=list.get(position);
holder.title.setText(p.getTitle());
holder.username.setText(p.getUsername());
holder.viewno.setText(p.getTimestamp());
/*int count = 0;
for(HospitalModel.Images images: hospitalModelList.get(position).getImagesList()) {
count += images.size();
}*/
for(Blog model : list) {
imageUrls = new ArrayList<>();;
imageUrls.addAll(model.getUrl());
Log.v("IMURLSSS", String.valueOf(imageUrls));
Picasso.with(context).load(imageUrls.get(position)).into(holder.imageview);
Log.v("IMGGPOS", imageUrls.get(position));
}
Picasso.with(context).load(p.getImage()).into(holder.userdp);
}
#Override
public int getItemCount() {
return list.size();
}
public class myviewholder extends RecyclerView.ViewHolder implements View.OnClickListener {
// It contains the elements in each row that we will inflate in the recyclerView..
TextView title,desc,username,likeno,viewno;
ImageView imageview,userdp, over, comments, likes;
ImageButton likebtn,viewbtn;
public myviewholder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.blog_desc);//here we link with the elements of each view i.e each row and
// desc = (TextView) itemView.findViewById(R.id.postdesc);//here we link with the elements of each view i.e each row and
username = (TextView) itemView.findViewById(R.id.blog_user_name);
viewno = (TextView) itemView.findViewById(R.id.blog_date);
likeno = (TextView) itemView.findViewById(R.id.blog_like_count);
userdp = (ImageView) itemView.findViewById(R.id.blog_user_image);
imageview = (ImageView) itemView.findViewById(R.id.blog_image);
comments = (ImageView) itemView.findViewById(R.id.blog_comment_icon);
//here we link with the elements of each view i.e each row and
// likebtn = (ImageButton)itemView.findViewById(R.id.likebtn);
// viewbtn = (ImageButton)itemView.findViewById(R.id.viewbtn);
comments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mprogressview = true;
int pos = getAdapterPosition();
Blog b = list.get(pos);
Intent intent = new Intent(context,CommentBox.class);
Bundle bundle = new Bundle();
bundle.putString("post_key",b.getUid().toString());
intent.putExtras(bundle);
context.startActivity(intent);
}
});
over = (ImageView) itemView.findViewById(R.id.overflow);
over.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFilterPopup(v);
}
});
});
itemView.setOnClickListener(this);
}
}
To display all those url's, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference urlRef = rootRef.child("Blog").child(uid).child("url");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String url = ds.getValue(String.class);
Log.d("TAG", url);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
urlRef.addListenerForSingleValueEvent(valueEventListener);
And here is a recommended way in which you can retrieve data from a Firebase Realtime database and display it in a RecyclerView using FirebaseRecyclerAdapter.
Edit:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Blog").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String uid = dataSnapshot.child("uid").getValue(String.class);
String title = dataSnapshot.child("title").getValue(String.class);
String timestamp = dataSnapshot.child("timestamp").getValue(String.class);
Log.d("TAG", uid + " / " + title + " / " + timestamp);
for(DataSnapshot ds : dataSnapshot.child("url").getChildren()) {
String url = ds.getValue(String.class);
Log.d("TAG", url);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
I have an adapter class where I am able to load all video from Firebase. But the problem is I can't load both, image and video in one RecyclerView
See what I have done:
I am using toro library to auto play video if your wondering and ExoPlayer to play video
This is my adapter class
public class MainFeedAdapter extends RecyclerView.Adapter<TestAdapter.MyViewHolder> {
private static final String TAG = "MainfeedAdapter";
private List<Photo> moviesList;
private DatabaseReference mReference;
private Context mContext;
private String currentUsername = "";
private int mLayoutResource;
private LayoutInflater mInflater;
private Photo photo;
private MyViewHolder mHolder;
public class MyViewHolder extends RecyclerView.ViewHolder implements ToroPlayer{
static final int LAYOUT_RES = R.layout.main_list;
private ExoPlayerViewHelper helper;
private CircleImageView profile_image;
//private String likeString;
private TextView username,time,caption,likes,comment,stars;
private SquareImageView image;
private LikeButton mHeart,Star;
private UserAccountSettings userAccountSettings = new UserAccountSettings();
private User user = new User();
private StringBuilder users;
private String mLIkeString;
private String mStarString;
private boolean likeByCurrentUSer;
private boolean starbycurrentuser;
private DatabaseReference mNotification;
private ImageView commentBubble;
private Uri mediaUri;
#BindView(R.id.main_post_image2)
PlayerView playerView;
private CardView video;
public MyViewHolder(View view) {
super(view);
profile_image = (CircleImageView)view.findViewById(R.id.post_profile_photo);
username = (TextView) view.findViewById(R.id.main_username);
time = (TextView) view.findViewById(R.id.main_image_time_posted);
caption = (TextView) view.findViewById(R.id.main_image_caption);
likes = (TextView) view.findViewById(R.id.main_likes);
comment = (TextView) view.findViewById(R.id.main_showcomments);
image = (SquareImageView) view.findViewById(R.id.main_post_image);
mHeart = (LikeButton) view.findViewById(R.id.main_heart);
Star = (LikeButton) view.findViewById(R.id.main_star);
stars= (TextView)view.findViewById(R.id.stars);
commentBubble = (ImageView)view.findViewById(R.id.main_comments) ;
mNotification = FirebaseDatabase.getInstance().getReference().child("notification");
mReference = FirebaseDatabase.getInstance().getReference();
ButterKnife.bind(this, itemView);
video = (CardView)view.findViewById(R.id.video_posts);
}
#NonNull
#Override
public View getPlayerView() {
return playerView;
}
#NonNull
#Override
public PlaybackInfo getCurrentPlaybackInfo() {
return helper != null ? helper.getLatestPlaybackInfo() : new PlaybackInfo();
}
#Override
public void initialize(#NonNull Container container, #Nullable PlaybackInfo playbackInfo) {
if (helper == null) {
helper = new SimpleExoPlayerViewHelper(container, this, mediaUri);
}
helper.initialize(playbackInfo);
}
// called from Adapter to setup the media
void bind( Uri item, List<Photo> payloads) {
if (item != null) {
mediaUri = item;
}else {
video.setVisibility(View.GONE);
}
}
#Override
public void play() {
if (helper != null) helper.play();
}
#Override
public void pause() {
if (helper != null) helper.pause();
}
#Override
public boolean isPlaying() {
return helper != null && helper.isPlaying();
}
#Override
public void release() {
if (helper != null) {
helper.release();
helper = null;
}
}
#Override
public boolean wantsToPlay() {
return ToroUtil.visibleAreaOffset(this, itemView.getParent()) >= 0.85;
}
#Override
public int getPlayerOrder() {
return getAdapterPosition();
}
#Override
public void onSettled(Container container) {
}
}
public TestAdapter(List<Photo> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.main_list, parent, false);
mContext = parent.getContext();
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
photo = moviesList.get(position);
mHolder = holder;
holder.users = new StringBuilder();
getCurrentUsername();
getLikesString(mHolder);
getStarString(mHolder);
holder.bind(Uri.parse(photo.getVideo_path()),moviesList);
//get the profile image and username
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(mContext.getString(R.string.dbname_user_account_settings))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(getItem(position).getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
// currentUsername = singleSnapshot.getValue(UserAccountSettings.class).getUsername();
Log.d(TAG, "onDataChange: found user: "
+ singleSnapshot.getValue(UserAccountSettings.class).getUsername());
holder.username.setText(singleSnapshot.getValue(UserAccountSettings.class).getUsername());
holder.username.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to profile of: " +
holder.user.getUsername());
Intent intent = new Intent(mContext, Profile_Activity.class);
intent.putExtra(mContext.getString(R.string.calling_activity),
mContext.getString(R.string.home_activity));
intent.putExtra(mContext.getString(R.string.intent_user), holder.user);
mContext.startActivity(intent);
}
});
imageLoader.displayImage(singleSnapshot.getValue(UserAccountSettings.class).getProfile_photo(),
holder.profile_image);
holder.profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to profile of: " +
holder.user.getUsername());
Intent intent = new Intent(mContext, Profile_Activity.class);
intent.putExtra(mContext.getString(R.string.calling_activity),
mContext.getString(R.string.home_activity));
intent.putExtra(mContext.getString(R.string.intent_user), holder.user);
mContext.startActivity(intent);
}
});
holder.userAccountSettings = singleSnapshot.getValue(UserAccountSettings.class);
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((HomeActivity)mContext).onCommentThreadSelected(getItem(position),mContext.getString(R.string.home_activity));
//another thing?
((HomeActivity)mContext).hideLayout();
}
});
holder.commentBubble.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((HomeActivity)mContext).onCommentThreadSelected(getItem(position),mContext.getString(R.string.home_activity));
//another thing?
((HomeActivity)mContext).hideLayout();
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Query userQuery = mReference
.child(mContext.getString(R.string.dbname_users))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(getItem(position).getUser_id());
userQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found user: " +
singleSnapshot.getValue(User.class).getUsername());
holder.user = singleSnapshot.getValue(User.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private boolean rechedendoflist(int position){
return position == getItemCount() -1;\
}
#Override
public int getItemCount() {
return moviesList.size();
}
public Photo getItem(int position) {
return moviesList.get(position);
}
private void getCurrentUsername(){
Log.d(TAG, "getCurrentUser: ");
Log.d(TAG, "getCurrentUsername: retrieving user account settings");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(mContext.getString(R.string.dbname_users))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
currentUsername = singleSnapshot.getValue(UserAccountSettings.class).getUsername();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Please help me guys!. Thanks in Advance!.
TheRecyclerView has ability to show items in multiple types.
In your case you can define two ViewType. one for Images and another for Videos.
Search about RecyclerView with multiple view types.
Take a look at here and this.
Also here is a question and answers about it.
How could I view the posts, only from friends?
in this example I would like to display in RecyclerView only the posts of my friends. In this case the user 15. (certainly is several friends, I put only one to exemplify)
Structure - database:
USERS
-user01 (current user)
-name: John
-age: 20
--friends
----user10
----user15
-POSTS
--idpost_98685754
---user_post: user15
---title_post: Title
---photo: link
-posts
--idpost_41254d4554s1
---user_post: user40
---title_post: Title
---photo: link
-posts
--idpost_121221sss1
---user_post: user15
---title_post: Title 2
---photo: link 2
-posts
--idpost_9865565555
---user_post: user15
---title_post: Title 3
---photo: link 3
I currently use only the simple order and limit functions explained in the documentation. This is the first time I need to do something like that.
EDIT:
CODE - FRAGMENT:
/*Firebase*/
mDb = FirebaseFirestore.getInstance();
mQuery = mDb.collection("Posts");
Query mQueryNew = mQuery.orderBy("timestamp", Query.Direction.DESCENDING);
/* Recycler */
mCardFeedList = (RecyclerView) view.findViewById(id.cardFeedUser_list);
mCardFeedList.setHasFixedSize(true);
mCardFeedList.setItemViewCacheSize(20);
mCardFeedList.setDrawingCacheEnabled(true);
mAdapter = new PostsAdapter(mQueryNew, this){
#Override
protected void onDataChanged() {
if (getItemCount() == 0) {
mCardFeedList.setVisibility(View.GONE);
} else {
mCardFeedList.setVisibility(View.VISIBLE);
}
}
};
llmanager = new LinearLayoutManager(getActivity());
mCardFeedList.setLayoutManager(llmanager);
mCardFeedList.setAdapter(mAdapter);
/*START*/
if (mAdapter != null) {
mAdapter.startListening();
}
ADAPTER:
public class PostsAdapter extends FirestoreAdapter<PostsAdapter.ViewHolder> {
public interface OnPostsListner{
void onPostSelected(DocumentSnapshot post);
void onLikeSelected(DocumentSnapshot like);
void onCurtidasSelected(DocumentSnapshot curtidas);
void onFotoSelected(DocumentSnapshot foto);
void onCommentsSelected(DocumentSnapshot coments);
}
private OnPostsListner mListner;
public PostsAdapter (Query query, OnPostsListner listner){
super(query);
mListner = listner;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new ViewHolder(inflater.inflate(R.layout.card_feed_user_row, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(getSnapshot(position), mListner);
}
static class ViewHolder extends RecyclerView.ViewHolder {
private Boolean mIsliked = false;
#BindView(R.id.tvCardFeedUser_nome)
TextView nomeUser;
#BindView(R.id.tvCardFeedUser_horario)
TextView horaFeed;
#BindView(R.id.tvCardFeedUser_desc)
TextView descFeed;
#BindView(R.id.ivCardFeedUser_image)
ImageView imageFeed;
#BindView(R.id.secaoLike)
LinearLayout curtir;
#BindView(R.id.secaoComments)
LinearLayout comentarios;
#BindView(R.id.tv_card_feed_linear_curtidas)
LinearLayout linear_curtidas;
#BindView(R.id.idBtnLike)
TextView btnLike;
#BindView(R.id.tv_card_feed_numero_curtidas)
TextView curtidas;
#BindView(R.id.tv_card_feed_nome_curtida)
TextView nome_curtidas;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bind(final DocumentSnapshot snapshot,
final OnPostsListner listener) {
final Posts ref = snapshot.toObject(Posts.class);
FirebaseFirestore db = FirebaseFirestore.getInstance();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
final FirebaseUser mCurrentUser = mAuth.getCurrentUser();
nomeUser.setText(ref.getNome_user());
descFeed.setText(ref.getDesc());
//Foto
Picasso.with(itemView.getContext()).load(ref.getImage()).placeholder(R.drawable.bck_padrao).networkPolicy(NetworkPolicy.OFFLINE).into(imageFeed, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(itemView.getContext()).load(ref.getImage()).placeholder(R.drawable.bck_padrao).into(imageFeed);
}
});
SimpleDateFormat formatter = new SimpleDateFormat("dd/M/yy HH:mm");
String novaData = formatter.format(ref.getTimestamp());
horaFeed.setText(novaData);
/*CLICKS*/
curtir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onLikeSelected(snapshot);
}
}
});
imageFeed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onFotoSelected(snapshot);
}
}
});
comentarios.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onCommentsSelected(snapshot);
}
}
});
linear_curtidas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onCurtidasSelected(snapshot);
}
}
});
// Click listener
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onPostSelected(snapshot);
}
}
});
}
}
}
To achieve this, you need to query your database twice using nested query. First of all you need to query the database to get all the friends id that correspond to a single user and then based on those ids to query the database for the second time to display only the post de correspond to those particular friends.
One thing to note is that this cannot be done in a single query.
I am developing application which keeps user expenses, I wrote CustomAdapter
public class CustomAdapter extends BaseAdapter{
Context c;
ArrayList<Income> incomes;
public CustomAdapter(){}
public CustomAdapter(Context c,ArrayList<Income> incomes){
this.incomes=incomes;
this.c=c;
}
#Override
public int getCount() {
return incomes.size();
}
#Override
public Object getItem(int position) {
return incomes.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView= LayoutInflater.from(c).inflate(R.layout.model,parent,false);
}
TextView nameTxt= (TextView) convertView.findViewById(R.id.nameTxt);
TextView propTxt= (TextView) convertView.findViewById(R.id.aciklama);
TextView descTxt= (TextView) convertView.findViewById(R.id.descTxt);
Income s= (Income) this.getItem(position);
nameTxt.setText(s.getName());
propTxt.setText(s.getType());
descTxt.setText((String.valueOf(s.getMiktar())));
return convertView;
}
and implemented on the activity
public class ExpenseActivity extends Activity{
DatabaseReference db;
FloatingActionButton fab;
ExpenseAdapter adapter;
ListView lv;
Boolean saved;
EditText nameEditTxt, propTxt, descTxt;
ArrayList<Expense> expenselist = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.expense_content);
//Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
lv = (ListView) findViewById(R.id.listview);
db = FirebaseDatabase.getInstance().getReference();
//isa
adapter = new ExpenseAdapter(ExpenseActivity.this, getExpenses());
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayInput();
}
});
}
public Boolean save(Expense expense){
if(expense==null){
saved=false;
}else{
try{
db.child("Expense").push().setValue(expense);
saved=true;
}catch (Exception ex){
ex.printStackTrace();;
saved=false;
}
}
return saved;
}
public void fetchData(DataSnapshot dataSnapshot)
{
expenselist.clear();
for (DataSnapshot ds : dataSnapshot.getChildren())
{
Expense expense=ds.getValue(Expense.class);
expenselist.add(expense);
adapter.notifyDataSetChanged();
}
}
public ArrayList<Expense> getExpenses(){
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return expenselist;
}
private void displayInput() {
final Dialog d=new Dialog(this);
d.setTitle("Gelir Girin");
d.setContentView(R.layout.expense_layout);
nameEditTxt = (EditText) d.findViewById(R.id.name);
propTxt = (EditText) d.findViewById(R.id.kategori);
descTxt = (EditText) d.findViewById(R.id.miktar);
Button saveBtn = (Button) d.findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = nameEditTxt.getText().toString();
String type = propTxt.getText().toString();
String amount= String.valueOf(descTxt.getText().toString());
Expense expense=new Expense(name,type,amount);
if (name != null && name.length() > 0) {
//THEN SAVE
if (save(expense)) {
//IF SAVED CLEAR EDITXT
d.cancel();
nameEditTxt.setText("");
propTxt.setText("");
descTxt.setText("");
}
} else {
Toast.makeText(ExpenseActivity.this, "Name Must Not Be Empty", Toast.LENGTH_SHORT).show();
}
}
});
d.show();
}
but even I have some data saved in firebase it returns null and passes null to fields(textview) at first but when I add new item it show existing data in the Firebase. One of my friend said that I am calling data asnychronously but I didn't understand it.I want to data be shown directly whenever activity is opened. Any help is appreciated,Thanks
When I open activity:
After I add new data:
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
fetchdata();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This will fetch appropriate data
Your problem is that your are initializing your adapter before fetching the data from the db.
adapter = new ExpenseAdapter(ExpenseActivity.this, getExpenses());
The getExpenses() method is performing an asynchronous operation
Try passing instead the list directly and call the getExpenses method as well
adapter = new ExpenseAdapter(ExpenseActivity.this, expenselist);
getExpenses()
Then when the notifyDatasetChanged is called in the fetchData method it will update the list.