I'm doing saving post feature now. I want display all saved post in one activity. I have made an activity where is RecyclerView in which I store all of posts and I have made made PostRow activity already. I have this databse:
. I want to get all post which user has saved and i dont know how to get them from database. I have made PostAdapter:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder>{
private List<Post> mPostList;
private boolean mProcessLike = false;
private String mSinglePostId;
private Context mCtx;
private DatabaseReference mDatabaseUsers;
private FirebaseUser mCurrentUser;
public PostAdapter (List<Post> postList, DatabaseReference databaseUsers, Context ctx){
this.mPostList = postList;
this.mDatabaseUsers = databaseUsers;
this.mCtx = ctx;
this.mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
}
#Override
public PostAdapter.PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.post_row, parent, false);
PostViewHolder postViewHolder = new PostViewHolder(v);
return postViewHolder;
}
#Override
public void onBindViewHolder(final PostAdapter.PostViewHolder holder, int position) {
Post post = mPostList.get(position);
holder.setTitle(post.getTitle());
holder.setImage(post.getImage());
holder.setPostId(post.getPostId());
holder.setLikeButton(holder.getPostId());
holder.getView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent postSingle = new Intent(mCtx, SinglePostActivity.class);
postSingle.putExtra("postId", holder.getPostId());
mCtx.startActivity(postSingle);
}
});
holder.getLikeBtn().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProcessLike = true;
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike){
if(dataSnapshot.child("saved").hasChild(holder.getPostId())){
mDatabaseUsers.child("saved")
.child(holder.getPostId())
.removeValue();
mProcessLike = false;
}else {
mDatabaseUsers.child("saved")
.child(holder.getPostId())
.setValue("saved");
mProcessLike = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
#Override
public int getItemCount() {
return mPostList.size();
}
public static class PostViewHolder extends RecyclerView.ViewHolder{
private TextView mPostTitle;
private ImageView mPostImage;
private Context mCtx;
private DatabaseReference mDatabaseUsers;
private FirebaseUser mCurrentUser;
private ImageButton mLikeBtn;
private String postId;
private View mView;
public PostViewHolder(View itemView) {
super(itemView);
this.mPostTitle = (TextView) itemView.findViewById(R.id.post_title);
this.mPostImage = (ImageView) itemView.findViewById(R.id.post_image);
this.mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
this.mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUser.getUid());
this.mLikeBtn = (ImageButton) itemView.findViewById(R.id.like_btn);
this.mCtx = itemView.getContext();
this.mView = itemView;
}
public void setTitle(String title){
mPostTitle.setText(title);
}
public void setImage(String image){
Picasso.with(mCtx).load(image).into(mPostImage);
}
public void setPostId(String id){
this.postId = id;
}
public String getPostId(){
return this.postId;
}
public void setLikeButton(final String postKey) {
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child("saved").hasChild(postKey)){
mLikeBtn.setImageResource(R.drawable.ic_favorite_pink_48dp);
}else{
mLikeBtn.setImageResource(R.drawable.ic_favorite_black_24dp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public ImageButton getLikeBtn() {
return this.mLikeBtn;
}
public View getView() {
return this.mView;
}
}
}
I recommend changing your database structure, more specifically on the books node, to something like this:
{
"books":{
"2ExF2vKltibqCbE0oVOEHkYSRi2":{ /* the user key*/
/*list of books saved by that user*/
"-L2L2UgB...":{
"title":"Title goes here"
},
"-anotherBookKey":{
"title":"Title goes here"
}
},
"anotherUserKey":{
"hisSavedBookKey":{
"title":"Title goes here"
}
}
},
"users" : {
"2ExF2vKltibqCbE0oVOEHkYSRi2" : {
"image" : "...",
"name" : "Karol546",
"saved" : {
"-L2L2UgB...":"saved"
},
"thumb_image" : "default"
},
}
}
And when you want to list all books saved by the user 2ExF2vKltibqCbE0oVOEHkYSRi2, you'd use this DatabaseReference:
String userId = "2ExF2vKltibqCbE0oVOEHkYSRi2";
DatabaseReference savedRef = FirebaseDatabase.getInstance()
.getReference().child("books").child(userId);
Related
I use Firebase to send messages between users, and I'd like to use a new unread message badge and the number of unread messages.
I want to help solve this problem so I can get the number of unread messages when they are received from the other user and displayed in the user's list
like this
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
Typeface MR,MRR;
private Context mContext;
private List<Chat> mChat;
private String imageurl;
public View view_click;
FirebaseUser fuser;
public MessageAdapter(Context mContext, List<Chat> mChat, String imageurl){
this.mChat = mChat;
this.mContext = mContext;
this.imageurl = imageurl;
MRR = Typeface.createFromAsset(mContext.getAssets(), "fonts/myriadregular.ttf");
MR = Typeface.createFromAsset(mContext.getAssets(), "fonts/myriad.ttf");
}
#NonNull
#Override
public MessageAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == MSG_TYPE_RIGHT) {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_right, parent, false);
return new MessageAdapter.ViewHolder(view);
} else {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_left, parent, false);
return new MessageAdapter.ViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull MessageAdapter.ViewHolder holder, int position) {
Chat chat = mChat.get(position);
holder.show_message.setTypeface(MRR);
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
chat.setSelected(!chat.isSelected());
holder.view.setBackgroundColor(chat.isSelected() ? Color.TRANSPARENT : Color.WHITE);
FirebaseDatabase.getInstance("https://pineka-social-media-mast-da52a-default-rtdb.firebaseio.com/"
).getReference("Chats")
.child(chat.getChatid())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
View view;
final Snackbar snackbar = Snackbar.make(holder.lyt_parent, "", Snackbar.LENGTH_LONG);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.snack_delete, null);
snackbar.getView().setBackgroundColor(Color.TRANSPARENT);
Snackbar.SnackbarLayout snackBarView = (Snackbar.SnackbarLayout) snackbar.getView();
snackBarView.setPadding(0, 0, 0, 0);
snackBarView.addView(view, 0);
snackbar.show();
// Toast.makeText(mContext, "Deleted! ="+chat.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
return false;
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view_click) {
// holder.delete.setVisibility(View.VISIBLE);
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.po);
LinearLayout copy = dialog.findViewById(R.id.copy);
LinearLayout share = dialog.findViewById(R.id.share);
LinearLayout reply = dialog.findViewById(R.id.reply);
LinearLayout delete = dialog.findViewById(R.id.remove_item);
copy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", chat.getMessage());
clipboard.setPrimaryClip(clip);
View view;
final Snackbar snackbar = Snackbar.make(holder.lyt_parent, "", Snackbar.LENGTH_LONG);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.snack, null);
snackbar.getView().setBackgroundColor(Color.TRANSPARENT);
Snackbar.SnackbarLayout snackBarView = (Snackbar.SnackbarLayout) snackbar.getView();
snackBarView.setPadding(0, 0, 0, 0);
snackBarView.addView(view, 0);
snackbar.show();
dialog.dismiss();
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent2 = new Intent(); intent2.setAction(Intent.ACTION_SEND);
intent2.setType("text/plain");
intent2.putExtra(Intent.EXTRA_TEXT, chat.getMessage() );
mContext. startActivity(Intent.createChooser(intent2, "Share via"));
dialog.dismiss();
}
});
reply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view_click) {
FirebaseDatabase.getInstance("https://pineka-social-media-mast-da52a-default-rtdb.firebaseio.com/"
).getReference("Chats")
.child(chat.getChatid())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
View view;
final Snackbar snackbar = Snackbar.make(holder.lyt_parent, "", Snackbar.LENGTH_LONG);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.snack_delete, null);
snackbar.getView().setBackgroundColor(Color.TRANSPARENT);
Snackbar.SnackbarLayout snackBarView = (Snackbar.SnackbarLayout) snackbar.getView();
snackBarView.setPadding(0, 0, 0, 0);
snackBarView.addView(view, 0);
dialog.dismiss();
snackbar.show();
// Toast.makeText(mContext, "Deleted! ="+chat.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
dialog.setCancelable(true);
dialog.show();
/*
*/
}
}
);
holder.show_message.setText(chat.getMessage());
if(chat.getTime()!=null && !chat.getTime().trim().equals("")) {
holder.time_tv.setText(holder.convertTime(chat.getTime()));
}
if (imageurl.equals("default")){
holder.profile_image.setImageResource(R.drawable.ic_profile_outline_40);
} else {
Glide.with(mContext).load(imageurl).into(holder.profile_image);
}
if (position == mChat.size()-1){
if (chat.isIsseen()){
// holder.seen.setImageResource(R.drawable.ic_baseline_check_24);
} else {
// holder.seen.setImageResource(R.drawable.ic_baseline_check_24_read);
}
} else {
// holder.seen.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return mChat.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView show_message;
public ImageView profile_image,seen,delete;
public TextView time_tv;
public Dialog myDialog;
public View view_click;
public LinearLayout lyt_parent;
private View view;
public ViewHolder(View itemView) {
super(itemView);
show_message = itemView.findViewById(R.id.show_message);
profile_image = itemView.findViewById(R.id.profile_image);
time_tv = itemView.findViewById(R.id.time_tv);
seen = itemView.findViewById(R.id.seen);
view = itemView;
lyt_parent= itemView.findViewById(R.id.lyt_parent);
}
public String convertTime(String time){
SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
String dateString = formatter.format(new Date(Long.parseLong(time)));
return dateString;
}
}
#Override
public int getItemViewType(int position) {
fuser = FirebaseAuth.getInstance().getCurrentUser();
if (mChat.get(position).getSender().equals(fuser.getUid())){
return MSG_TYPE_RIGHT;
} else {
return MSG_TYPE_LEFT;
}
}
}
item Uaer Massage
public class UserAdaptermsg extends RecyclerView.Adapter<UserAdaptermsg.ViewHolder> {
private Context mContext;
private List<User> mUsers;
private boolean ischat;
private OnItemClick onItemClick;
Typeface MR,MRR;
String theLastMessage;
boolean isopend ;
public UserAdaptermsg(Context mContext, OnItemClick onItemClick, List<User> mUsers, boolean ischat){
this.onItemClick = onItemClick;
this.mUsers = mUsers;
this.mContext = mContext;
this.ischat = ischat;
if(mContext!=null) {
MRR = Typeface.createFromAsset(mContext.getAssets(), "fonts/myriadregular.ttf");
MR = Typeface.createFromAsset(mContext.getAssets(), "fonts/myriad.ttf");
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.user_item_msg, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final User user = mUsers.get(position);
// holder.username.setTypeface(MR);
holder.last_msg.setTypeface(MRR);
holder.badg_massage.setVisibility(View.GONE);
holder.username.setText(user.getFullname());
if (user.getImageurl().equals("default")){
holder.profile_image.setImageResource(R.drawable.ic_profile_outline_40);
} else {
Glide.with(mContext).load(user.getImageurl()).into(holder.profile_image);
}
if (ischat){
lastMessage(user.getId(), holder.last_msg);
count(user.getId(),true);
// holder.badg_massage.setVisibility(View.VISIBLE);
// holder.badg_massage.setText(mUsers.size()+"");
} else {
holder.last_msg.setVisibility(View.GONE);
}
if (ischat){
if (user.getStatus().equals("online")){
holder.img_on.setVisibility(View.VISIBLE);
holder.img_off.setVisibility(View.GONE);
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.GONE);
}
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, MessageActivity.class);
intent.putExtra("userid", user.getId());
mContext.startActivity(intent);
}
});
holder.profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClick.onItemCLick(user.getId(),view);
}
});
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView username;
public ImageView profile_image;
private ImageView img_on;
private ImageView img_off;
private TextView last_msg;
private TextView badg_massage;
public ViewHolder(View itemView) {
super(itemView);
username = itemView.findViewById(R.id.username);
profile_image = itemView.findViewById(R.id.profile_image);
img_on = itemView.findViewById(R.id.img_on);
img_off = itemView.findViewById(R.id.img_off);
last_msg = itemView.findViewById(R.id.last_msg);
badg_massage = itemView.findViewById(R.id.badg_massage);
}
}
//check for last message
private void lastMessage(final String userid, final TextView last_msg){
theLastMessage = "default";
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (firebaseUser != null && chat != null) {
if (chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(firebaseUser.getUid())) {
theLastMessage = chat.getMessage();
}
}
}
switch (theLastMessage){
case "default":
last_msg.setText("No Message");
break;
default:
last_msg.setText(theLastMessage);
break;
}
theLastMessage = "default";
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void count(final String userid, final Boolean count){
isopend = false;
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (firebaseUser != null && chat != null) {
if (chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(firebaseUser.getUid())) {
isopend = chat.isIsopened();
}
}
}
if (isopend == false) {
Toast.makeText(mContext, "notopent", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "isopend", Toast.LENGTH_SHORT).show();
}
isopend = true;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
model Chat
package com.Model;
public class Chat {
private String sender;
private String receiver;
private String message;
private boolean isseen;
private String chatid;
private boolean isSelected = false;
private boolean isopened;
private String time;
public Chat(String sender, String receiver, String message, boolean isseen, String chatid, boolean isopened, String time) {
this.sender = sender;
this.receiver = receiver;
this.message = message;
this.isseen = isseen;
this.chatid = chatid;
this.isopened = isopened;
this.time = time;
}
public Chat() {
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isIsseen() {
return isseen;
}
public void setIsseen(boolean isseen) {
this.isseen = isseen;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getChatid() {
return chatid;
}
public void setChatid(String chatid) {
this.chatid = chatid;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public boolean isIsopened() {
return isopened;
}
public void setIsopened(boolean isopened) {
this.isopened = isopened;
}
}
This Is My MainActivity.
public class MatchContests extends AppCompatActivity implements ItemClickListener {
RecyclerView recyclerView;
private DatabaseReference myref;
private ArrayList<ZgetsetContests> contestsList;
private AdapterContests adapterContests;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match_contests);
recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapterContests.setClickListener(this);
myref = FirebaseDatabase.getInstance().getReference();
contestsList = new ArrayList<>();
ClearAll();
GetContestDetails();
}
private void GetContestDetails()
{
Query query = myref.child("contestsdetails").child("match1");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ClearAll();
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
ZgetsetContests zgetsetContests = new ZgetsetContests();
zgetsetContests.setEntry(snapshot.child("entry").getValue().toString());
zgetsetContests.setBonususage(snapshot.child("bonususage").getValue().toString());
zgetsetContests.setFirstposition(snapshot.child("firstposition").getValue().toString());
zgetsetContests.setMaintitle(snapshot.child("maintitle").getValue().toString());
zgetsetContests.setTeamsallowed(snapshot.child("teamsallowed").getValue().toString());
zgetsetContests.setTotalspots(snapshot.child("totalspots").getValue().toString());
zgetsetContests.setPrizepool(snapshot.child("prizepool").getValue().toString());
contestsList.add(zgetsetContests);
}
adapterContests = new AdapterContests(getApplicationContext(),contestsList);
recyclerView.setAdapter(adapterContests);
adapterContests.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void ClearAll()
{
if (contestsList != null) {
contestsList.clear();
if (adapterContests != null){adapterContests.notifyDataSetChanged();}
}
contestsList = new ArrayList<>();
}
#Override
public void onClick(View v, int position) {
}
}
My Adapter Class.
public class AdapterContests extends RecyclerView.Adapter<AdapterContests.ViewHolder> {
private static final String Tag = "RecyclerView";
private Context mContext;
private ArrayList<ZgetsetContests> contestsList;
private DatabaseReference dr;
private ItemClickListener clickListener;
public AdapterContests(Context mContext, ArrayList<ZgetsetContests> contestsList) {
this.mContext = mContext;
this.contestsList = contestsList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.design_contests,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
holder.entry.setText(contestsList.get(position).getEntry());
holder.prizepool.setText(contestsList.get(position).getPrizepool());
holder.firstposition.setText(contestsList.get(position).getFirstposition());
holder.totalspots.setText(contestsList.get(position).getTotalspots());
holder.teamsallowed.setText(contestsList.get(position).getTeamsallowed());
holder.bonususage.setText(contestsList.get(position).getBonususage());
holder.maintitle.setText(contestsList.get(position).getMaintitle());
holder.progressBar.setMax(Integer.parseInt(contestsList.get(position).getTotalspots()));
dr = FirebaseDatabase.getInstance().getReference().child("match1joinedteams").child("contest1");
dr.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
Long countjoinedteams1 = dataSnapshot.getChildrenCount();
int a = countjoinedteams1.intValue();
holder.progressBar.setProgress(a);
}else{ }
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public int getItemCount() {
return contestsList.size();
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
TextView maintitle;
TextView entry;
TextView prizepool;
TextView firstposition;
TextView teamsallowed;
TextView bonususage;
TextView totalspots;
ProgressBar progressBar;
public ViewHolder(#NonNull View itemView) {
super(itemView);
maintitle = itemView.findViewById(R.id.maintitle1);
entry = itemView.findViewById(R.id.entry1);
prizepool = itemView.findViewById(R.id.prizepool1);
firstposition = itemView.findViewById(R.id.firstpoisition1);
teamsallowed = itemView.findViewById(R.id.teamsallowed1);
bonususage = itemView.findViewById(R.id.bonususage1);
totalspots = itemView.findViewById(R.id.totalspots1);
progressBar = itemView.findViewById(R.id.progressbar1);
itemView.setTag(itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (clickListener != null) clickListener.onClick(v, getAdapterPosition());
}
}
}
AppCrashes When I Enter The Activity.
Problem is In MainActivity On Line adapterContests.setClickListener(this); Logcat Shows Attempt To Invoke Virtual Method on null Object.
When I Remove This Line App Works Fine But Click Listener Will Not Be Working.
Before When i was only retriving data app was working fine but after implementing onClick App Crashed
Well you call the method on the adapter when it isn't initialized yet.
Do you see this line:
adapterContests.setClickListener(this);
Move it under these:
..............
adapterContests = new AdapterContests(getApplicationContext(),contestsList);
recyclerView.setAdapter(adapterContests);
//here...
adapterContests.notifyDataSetChanged();
..........
UPDATE:
//SHOULD BE LIKE THIS
adapterContests.setClickListener(MatchContests.this);
I working with an app but when I am trying to access firebase data the getter method of the POJO returns null. I can not access data and setup in RecyclerView
Here is what I did:
My Firebase Structure:
My app debugging mode:
My Book Class
public class Book {
private String bookId;
private String bookImage;
private String bookName;
private String writerName;
private String publisherName;
private String shortDesc;
public Book() {
}
public Book(String bookImage, String bookName,
String writerName, String publisherName,String shortDesc) {
this.bookImage = bookImage;
this.bookName = bookName;
this.writerName = writerName;
this.publisherName = publisherName;
this.shortDesc = shortDesc;
}
public Book(String bookId, String bookImage, String bookName,
String writerName, String publisherName, String shortDesc) {
this.bookId = bookId;
this.bookImage = bookImage;
this.bookName = bookName;
this.writerName = writerName;
this.publisherName = publisherName;
this.shortDesc = shortDesc;
}
public String getBookId() {
return bookId;
}
public String getBookImage() {
return bookImage;
}
public String getBookName() {
return bookName;
}
public String getWriterName() {
return writerName;
}
public String getPublisherName() {
return publisherName;
}
public String getShortDesc() {
return shortDesc;
}
public void setBookId(String bookId) {
this.bookId = bookId;
}
My BookListFragment where I'm showing my book list
public class BookListFragment extends Fragment {
private Button button1,button2,button3;
private RecyclerView bookListRv;
private ArrayList<Book> bookList;
private BookAdapter bookAdapter;
private String adminId;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference;
public BookListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_book_list, container, false);
init(view);
adminId = firebaseAuth.getUid();
Book book = new Book();
String bookid =book.getBookId();
configRV();
getBooks();
return view;
}
private void init(View view) {
bookListRv = view.findViewById(R.id.bookRVId);
firebaseAuth = firebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
bookList = new ArrayList<>();
bookAdapter = new BookAdapter(bookList, getContext());
}
private void configRV() {
bookListRv.setLayoutManager(new LinearLayoutManager(getContext()));
bookListRv.setAdapter(bookAdapter);
}
private void getBooks() {
DatabaseReference showBookRef = databaseReference.child("Books").child(adminId);
showBookRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot data:dataSnapshot.getChildren()){
Book book = data.getValue(Book.class);
bookList.add(book);
bookAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
My AddBookActivity
public class AddBookActivity extends AppCompatActivity {
private Button addBookBtn;
private ImageView bookIv;
private EditText bookNameEt,writerNameEt,publisherNameEt,shortDescEt;
private Uri imgUrl = null;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference;
private StorageReference imgReference;
private String adminId,imgUri="";
private FirebaseUser mFirebaseUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_book);
init();
if(mFirebaseUser!=null){
adminId = mFirebaseUser.getUid();
}
bookIv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,1);
}
});
addBookBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addBookData();
}
});
}
private void init() {
firebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = firebaseAuth.getCurrentUser();
imgReference = FirebaseStorage.getInstance().getReference();
databaseReference = FirebaseDatabase.getInstance().getReference();
addBookBtn = findViewById(R.id.addBookBtnId);
bookIv = findViewById(R.id.addBookIvId);
bookNameEt = findViewById(R.id.addBookNameEtId);
writerNameEt = findViewById(R.id.addBookWriterNameEtId);
publisherNameEt = findViewById(R.id.addBookPublisherNameEtId);
shortDescEt = findViewById(R.id.addBookDescripEtId);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1 && resultCode==RESULT_OK){
if(data!=null){
imgUrl = data.getData();
bookIv.setImageURI(imgUrl);
}
}
}
private void addBookData() {
if (imgUrl!=null) {
final StorageReference filePath = imgReference.child("Book_images").child(String.valueOf(System.currentTimeMillis()));
filePath.putFile(imgUrl).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
imgUri=uri.toString();
}
});
}
}
});
}
String bookName = bookNameEt.getText().toString();
String writerName = writerNameEt.getText().toString();
String publisherName = publisherNameEt.getText().toString();
String bookDesc = shortDescEt.getText().toString();
String bookImg = imgUri;
if(TextUtils.isEmpty(bookName) && TextUtils.isEmpty(writerName)
&& TextUtils.isEmpty(publisherName) && TextUtils.isEmpty(bookDesc) && TextUtils.isEmpty(bookImg)){
Toast.makeText(this,"Please Fill The Blank Field",Toast.LENGTH_LONG).show();
}
else if(!TextUtils.isEmpty(bookName) && !TextUtils.isEmpty(writerName)
&& !TextUtils.isEmpty(publisherName) && !TextUtils.isEmpty(bookDesc) && !TextUtils.isEmpty(bookImg)){
saveBook(bookImg,bookName,writerName,publisherName,bookDesc);
}
}
private void saveBook(String url, String bookName, String writerName, String publisherName, String bookDesc) {
DatabaseReference bookRef = databaseReference.child("Books").child(adminId);
String bookId = bookRef.push().getKey();
if(bookId!=null){
Book book = new Book(bookId,url,bookName,writerName,publisherName,bookDesc);
bookRef.child(bookId).child("BookInfo").setValue(book).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
}
}
}
My BookAdapter
public class BookAdapter extends RecyclerView.Adapter {
private List<Book> books;
private Context context;
public BookAdapter(List<Book> books, Context context) {
this.books = books;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_book_layout,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final Book currentBook = books.get(position);
// holder.bookIv.setIm(currentBook.getBookImage());
holder.bookNameTv.setText(currentBook.getBookName());
holder.writerNameTv.setText(currentBook.getWriterName());
holder.publisherNameTv.setText(currentBook.getPublisherName());
holder.shortDescTv.setText(currentBook.getShortDesc());
}
#Override
public int getItemCount() {
return books.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView bookNameTv,writerNameTv,publisherNameTv,shortDescTv;
private ImageView bookIv;
public ViewHolder(#NonNull View itemView) {
super(itemView);
bookIv = itemView.findViewById(R.id.bookListIvId);
bookNameTv = itemView.findViewById(R.id.bookListNameTvId);
writerNameTv = itemView.findViewById(R.id.bookListWriterNameTvId);
publisherNameTv = itemView.findViewById(R.id.bookListPubNameTvId);
shortDescTv = itemView.findViewById(R.id.bookListShortDescTvId);
}
}
}
Now when I am debugging my app the debugger showing me the Book class reference book is all field null.
Any help me for appreciated
It's because you are creating book object in app and book is not fetched from firebase. You need to query for books using adminId
You have to go one more level deep to get BookInfo. Try using below code:
showBookRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()) {
Book book = data.child("BookInfo").getValue(Book.class);
bookList.add(book);
}
bookAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
You have to have your BookInfo directly outside i.e. YourRootId->SubId->YourInfo but this is what you have used as YourRootId->SubId->BookInfo->YourInfo (this is right if you want to retrieve only that particular data)
So First setup a FirebaseRecyclerAdapter
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("yourRootId/");
FirebaseRecyclerOptions<Book> options = FirebaseRecyclerOptions.Builder<Book>()
.setQuery(query, Book.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Book, BookHolder>(options) {
#Override
public BookHolder 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.yourlayout, parent, false);
return new BookHolder(view);
}
#Override
protected void onBindViewHolder(BookHolder holder, int position, Book model) {
// assign all data in here
}
};
then create a viewholder
public class BookHolder extends RecyclerView.ViewHolder {
public LinearLayout root;
public TextView abc;
public TextView xyz;
public ViewHolder(View itemView) {
super(itemView);
abc= itemView.findViewById(R.id.list_title);
xyz= itemView.findViewById(R.id.list_desc);
}
}
I was trying to make a Music Streaming app. I created an Activity called Display Activity. I make a horizontal RecyclerView in Display Activity. In my Firebase I created A node name 'ArtistView' which contains Artist List.
After that i load Artist image and Artist name in my Horizontal recyclerView like same as Spotify. There is another node in my firebase which contain songList of Artist. Now my main question is how to make function like when user click "Guri" artist from My RecyclerView then after clicking it loads list of his Songs in New Activity from Firebase like in Spotify if we click any Artist then it loads songs of Artist in New Activity. Here is the image of my Firebsae Database:-
Firebase Screenshot
If you underStand my question then Here is the Code:-
Display Activity:-
public class DisplayActivity extends AppCompatActivity {
private ArtistRecyclerView artistRecyclerView;
private DatabaseReference databaseReference;
private ValueEventListener eventListener;
private List<ArtistHoler> artistHolerList;
private RecyclerView recyclerView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dispplay);
artistHolerList = new ArrayList<>();
artistRecyclerView = new ArtistRecyclerView(this , artistHolerList);
databaseReference = FirebaseDatabase.getInstance().getReference("ArtistView");
databaseReference.keepSynced(true);
recyclerView = findViewById(R.id.dispay_recycler_view);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this , LinearLayoutManager.HORIZONTAL , false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(artistRecyclerView);
eventListener = databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
ArtistHoler artistHoler = snapshot.getValue(ArtistHoler.class);
artistHolerList.add(artistHoler);
}
artistRecyclerView.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Artist Adapter:-
public class ArtistRecyclerView extends RecyclerView.Adapter<ArtistRecyclerView.HolderOfArtist> {
private List<ArtistHoler> mHolder;
private Context mContext;
public ArtistRecyclerView(Context context, List<ArtistHoler> holder) {
mHolder = holder;
mContext = context;
}
#NonNull
#Override
public HolderOfArtist onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.resource, parent, false);
return new HolderOfArtist(view);
}
#Override
public void onBindViewHolder(#NonNull HolderOfArtist holder, int position) {
ArtistHoler artistHoler = mHolder.get(position);
String text1 = artistHoler.getName();
Glide.with(mContext)
.asBitmap()
.centerCrop()
.load(artistHoler.getImageUri())
.into(holder.image);
holder.image.setOnClickListener(view -> Toast.makeText(mContext, text1, Toast.LENGTH_SHORT).show());
holder.name.setText(text1);
}
#Override
public int getItemCount() {
return mHolder.size();
}
public class HolderOfArtist extends RecyclerView.ViewHolder {
ImageView image;
TextView name;
public HolderOfArtist(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.resource_image);
name = itemView.findViewById(R.id.resource_text);
}
}
}
Artist Holders:-
public class ArtistHoler {
private String mName;
private String mImageUri;
public ArtistHoler() {
}
public ArtistHoler(String name , String imageUri){
mName = name;
mImageUri = imageUri;
}
public String getName() {
return mName;
}
public void setName(String name){
mName = name;
}
public String getImageUri(){
return mImageUri;
}
public void setImageUri(String imageUri) {
mImageUri = imageUri;
}
}
Add click event on holder item and take the corresponding artist name and pass it to next activity.
#Override
public void onBindViewHolder(#NonNull HolderOfArtist holder, int position) {
...
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String artistName = mHolder.get(position).getName();
Intent detailIntent = new Intent(mContext, SongsActivity.class);
detailIntent.putExtra("ArtistName", artistName);
startActivity(detailIntent);
}
});
}
Then in next activity's onCreate get the artist name like below and call the firebase to get the songs list of that particular artist and do whatever you want inside onDataChange
String artistName = getIntent().getStringExtra("ArtistName");
FirebaseDatabase.getInstance().getReference("ArtistSongs").orderByKey().equalTo(artistName).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot song: dataSnapshot.child(artistName).getChildren()) {
//here song indicates "Song" with SongName and SongUrl
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
DATABASE
I wanted to retrieve all the value from my firebase, but it retrieved the last one only which is "hjh" , what did i do wrong?
This is my code
public class MainActivity extends AppCompatActivity {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("content");
ArrayList<String> postList = new ArrayList<>();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference contentRef = rootRef.child("Post");
ValueEventListener value_l;
TextView content_view;
ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
//setContentView(R.layout.post_info);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content_view = (TextView) findViewById(R.id.contentTextview);
listview = (ListView) findViewById(R.id.listview);
value_l = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
String contentText = ds.child("content").getValue(String.class);
postList.add(contentText);
//FOR ARRAYLIST TESTING content_view.setText(postList.get(postList.size()-1));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
};
Thank you :)
You should try this code it may be help you.
1) MainActivity
public class MainActivity extends AppCompatActivity {
private RecyclerView rvData;
private RetriveDataAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rvData = findViewById(R.id.rvData);
rvData.setHasFixedSize(true);
rvData.setLayoutManager(new LinearLayoutManager(MainActivity.this));
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
database.child("Post").addValueEventListener(new ValueEventListener() {
#SuppressLint("LongLogTag")
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<MyBean> arrayList = new ArrayList<MyBean>();
for (DataSnapshot noteDataSnapshot : dataSnapshot.getChildren()) {
MyBean bean = noteDataSnapshot.getValue(MyBean.class);
arrayList.add(bean);
}
Log.e("MainActivity.this", "Data list ::>>>>>" + arrayList.size());
adapter = new RetriveDataAdapter(MainActivity.this, arrayList);
rvData.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
2) MyBean
public class MyBean {
public String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
3) RetriveDataAdapter
public class RetriveDataAdapter extends RecyclerView.Adapter<RetriveDataAdapter.MyViewHolder> {
private static final String TAG = "RetriveDataAdapter.class";
private Context ctx;
private ArrayList<MyBean> dataList;
#SuppressLint("LongLogTag")
public RetriveDataAdapter(Context context, ArrayList<MyBean> dataList) {
this.ctx = context;
this.dataList = dataList;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView tvContent;
public MyViewHolder(View view) {
super(view);
tvContent = view.findViewById(R.id.tvContent);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_form, parent, false);
return new MyViewHolder(itemView);
}
#SuppressLint("LongLogTag")
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final MyBean bean = dataList.get(position);
holder.tvContent.setText("Content: " + bean.getContent());
}
#Override
public int getItemCount() {
return dataList.size();
}
}
I can't see your whole Database's structure and didn't see where you call addValueEventListener(value_l) , so that I can only guess it's because of the wrong level Reference.
You should add value_l to the correct reference, maybe all the post's parent, and iterate through all of it's child using snapshot.forEach()
Google for firebase database iterate may provides more detailed information.