I'm having some trouble obtaining a new message.
So my algorithm works like this. I receive the last message from the chat(in Firebase), and if the last message UserId is not equal to mine than it sets a Boolean(newMessage) to true to make it a new message.
When i click on it, the variable sets to false. However when i re-run the application the Boolean does not stay the same, it just resets itself.
What should i do, to fix this?
Here is the code :
MessengerMessagesFragment.java
public class MessengerMessagesFragment extends Fragment{
private static final String TAG = "MessengerMessagesFragme";
private List<User> mUserList;
private static final int SIGN_IN_REQUEST_CODE = 111;
private ListView mListView;
private ArrayList<String> mUsersInM;
private MessagesListAdapter mAdapter;
User user;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_messenger_messages, container, false);
mListView = (ListView) view.findViewById(R.id.lvMessages);
mUserList = new ArrayList<>();
mUsersInM = new ArrayList<>();
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
// Start sign in/sign up activity
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.build(), SIGN_IN_REQUEST_CODE);
} else {
// User is already signed in, show list of messages
getUsersInM();
}
return view;
}
private void updateUserslist(){
Log.d(TAG, "updateUsersList: updating users list");
mAdapter = new MessagesListAdapter(getActivity(), R.layout.layout_message_listitem, mUserList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "onItemClick: selected user: " + mUserList.get(position).toString());
mAdapter.setNewMessage(false);
Log.e(TAG, "onItemClick: Set new message bool " + mAdapter.isNewMessage());
Intent intent = new Intent(getActivity(), ChatActivity.class);
intent.putExtra(getString(R.string.intent_user), mUserList.get(position));
startActivity(intent);
}
});
}
private void getMessages(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
for(int i = 0; i < mUsersInM.size(); i++){
final int count = i;
Query query = reference
.child(getString(R.string.dbname_users))
.orderByChild(getString(R.string.field_user_id))
.equalTo(mUsersInM.get(i));
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
mUserList.add(singleSnapshot.getValue(User.class));
}
if(count >= mUsersInM.size() - 1){
updateUserslist();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
private void getUsersInM(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_messages))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
mUsersInM.add(singleSnapshot.getKey().toString());
Log.d(TAG, "onDataChange: Message user id: " + mUsersInM.toString() );
}
getMessages();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
MessagesListAdapter.java
public class MessagesListAdapter extends ArrayAdapter<User> {
private static final String TAG = "MessageListAdapter";
private LayoutInflater mInflater;
private List<User> mUsers = null;
private int layoutResource;
private Context mContext;
private int messagesCount = 0;
DatabaseReference myRef;
public boolean newMessage;
public boolean isNewMessage() {
return newMessage;
}
public void setNewMessage(boolean newMessage) {
this.newMessage = newMessage;
}
//private int msgC;
private String userID;
public MessagesListAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull List<User> objects) {
super(context, resource, objects);
mContext = context;
myRef = FirebaseDatabase.getInstance().getReference();
//getMessagesCount();
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutResource = resource;
this.mUsers = objects;
}
private static class ViewHolder{
TextView username, message, timeStamp;
ImageView profileImage, statusOnline, statusOffline;
RelativeLayout messageBackground;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.username = (TextView) convertView.findViewById(R.id.f_username);
holder.message = (TextView) convertView.findViewById(R.id.m_message);
holder.profileImage = (ImageView) convertView.findViewById(R.id.f_profile_image);
holder.timeStamp = (TextView) convertView.findViewById(R.id.m_timestamp);
holder.statusOnline = (ImageView) convertView.findViewById(R.id.iv_Online);
holder.statusOffline = (ImageView) convertView.findViewById(R.id.iv_Offline);
holder.messageBackground = (RelativeLayout) convertView.findViewById(R.id.RelLayoutMessage);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.username.setText(getItem(position).getUsername());
//holder.email.setText(getItem(position).getEmail());
//DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = myRef.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()){
//Log.d(TAG, "onDataChange: found user: " + singleSnapshot.getValue(UserAccountSettings.class).toString());
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(singleSnapshot.getValue(UserAccountSettings.class).getProfile_photo(),
holder.profileImage);
userID = singleSnapshot.getValue(User.class).getUser_id();
boolean is_Online = singleSnapshot.getValue(User.class).isOnline();
if(is_Online == true){
holder.statusOnline.setVisibility(View.VISIBLE);
holder.statusOffline.setVisibility(View.GONE);
}else if(is_Online == false){
holder.statusOnline.setVisibility(View.GONE);
holder.statusOffline.setVisibility(View.VISIBLE);
}
}
setMessageItemSettings(holder, userID);
getNewMessage(holder, userID);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return convertView;
}
private void getNewMessage(final ViewHolder holder, final String user_id){
Query lastMessageQuery = myRef.child(mContext.getString(R.string.dbname_messages))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(user_id).orderByKey().limitToLast(1);
lastMessageQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
String messageUid = data.child(mContext.getString(R.string.field_messageUserId)).getValue().toString();
Log.e(TAG, "onDataChange: *************** MESSAGE FROM USER *************** : " + messageUid + " ====== " + newMessage);
if(messageUid.equals(user_id)){
newMessage = true;
Log.e(TAG, "onDataChange: *************** NEW MESSAGE FROM USER *************** : " + messageUid + " ====== " + newMessage);
if(newMessage){
holder.messageBackground.setBackgroundColor(Color.parseColor("#b7b7b7"));
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setMessageItemSettings(final ViewHolder holder, final String user_id){
Log.e(TAG, "getView: USER ID************************************" + userID);
Log.e(TAG, "getView: USER ID************************************" + messagesCount);
//msgC = messagesCount;
//DatabaseReference databaseReference2 = FirebaseDatabase.getInstance().getReference();
Query lastMessageQuery = myRef.child(mContext.getString(R.string.dbname_messages))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(user_id).orderByKey().limitToLast(1);
lastMessageQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: THINGS--------------+++ ---" + dataSnapshot.toString());
Log.e(TAG, "getView: USER ID************************************" + userID);
Log.e(TAG, "getView: USER ID************************************" + messagesCount);
//String lastItem = dataSnapshot.getValue().toString();
for (DataSnapshot data : dataSnapshot.getChildren()) {
try{
String mMessage = data.child(mContext.getString(R.string.field_messageText)).getValue().toString();
holder.message.setText(mMessage);
String mTime = data.child(mContext.getString(R.string.field_messageTime)).getValue().toString();
holder.timeStamp.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", Long.valueOf(mTime)));
}catch(NullPointerException e){
Log.e(TAG, "onDataChange: *************** GETTING MESSAGES FROM USER ARE NULL *************** : " + e.getMessage());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Handle possible errors.
}
});
//Log.d(TAG, "getView: USER ID****************" + userID);
}
Firebase Message Structure :
Are you saving the newMessage = true; statement in somewhere?
i have fixed it buy putting a new_message variable in user_id node 2(WI8yTLA...) on firebase and that solved my problem.
Related
I am trying to show random users from Firebase Realtime Database .I am currently able to show one random user from my Firebase Realtime database but what i want to do is show 6 random users on to my recyclerview at once .But i am unable to figure out how to add query for same without getting an error at runtime.
Mycode
public class UsersFragment extends Fragment {
private RecyclerView recyclerView;
private UserAdapter mUserAdapter;
private List<User> mUsers;
String TAG = "MyTag";
ValueEventListener mValueEventListener;
List<String> UserIdsList = new ArrayList<>();
public UsersFragment() {
// 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_users, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mUsers = new ArrayList<>();
//readUser();
RandomUsers();
return view;
}
private void RandomUsers() {
//mUsers.add((User) UserIdsList);
mUserAdapter = new UserAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(mUserAdapter);
mUserAdapter.notifyDataSetChanged();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference UserIdsRef = rootRef.child("UserIds");
ValueEventListener mValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String userIDS = ds.getKey();
UserIdsList.add(userIDS);
}
int UserListSize = UserIdsList.size();
Log.d(TAG, String.valueOf(UserListSize));
Random random=new Random();
int random1=random.nextInt(UserListSize);
// int Rdm= UserIdsList.get(new Random().nextInt(UserListSize));
DatabaseReference UserRef = rootRef.child("Users").child(UserIdsList.get(random1));
Log.d(TAG,"UserRef "+ String.valueOf(UserRef));
//new Random().nextInt(UserListSize)
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
mUsers.add(user);
mUserAdapter.notifyDataSetChanged();
String name = dataSnapshot.child("First").getValue(String.class);
Log.d(TAG, "Name called "+name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "Error: " + databaseError.toException()); //Don't ignore errors!
}
};
UserRef.addListenerForSingleValueEvent(eventListener);
//UserRef.addValueEventListener(eventListener);
Query query2 = UserRef.limitToFirst(2);
query2.addListenerForSingleValueEvent(eventListener);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "Error: " + databaseError.getMessage()); //Don't ignore errors!
}
};
UserIdsRef.addListenerForSingleValueEvent(mValueEventListener);
//UserIdsRef.addValueEventListener(mValueEventListener);
}
}
UserAdapter.java
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private Context mContext;
private List<User> mUsers;
private List<String> UserIdsList;
private boolean ischat;
String theLastMessage;
public UserAdapter(Context mContext, List<User> mUsers,boolean ischat) {
this.mContext = mContext;
this.mUsers = mUsers;
this.ischat=ischat;
}
#NonNull
#Override
public UserAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(mContext).inflate(R.layout.user_item,parent,false);
return new UserAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserAdapter.ViewHolder holder, int position) {
final User user=mUsers.get(position);
holder.username.setText(user.getFirst());
if (user.getImageURL().equals("default")){
holder.profile_image.setImageResource(R.mipmap.ic_launcher);
} else {
Glide.with(mContext).load(user.getImageURL()).into(holder.profile_image);
}
if (ischat){
lastMessage(user.getId(), holder.last_msg);
} 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.VISIBLE);
}
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mContext, MessageActivity.class);
intent.putExtra("UserName",user.getFirst());
intent.putExtra("userid", user.getId());
intent.putExtra("ImageURL",user.getImageURL());
mContext.startActivity(intent);
}
});
}
#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;
public ViewHolder(#NonNull 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);
}
}
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) {
}
});
}
}
Data Snapshot
DataSnapshot { key = KRhmaWXCctMHbU1Z6NAWRGGw2ag2, value = {EmailId=abc#gmail.com, First=shivam} }
You can try this:
DatabaseReference UserRef = rootRef.child("Users").orderByKey().startAt(UserIdsList.get(random1)).limitToFirst(6);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
mUsers.add(user);
mUserAdapter.notifyDataSetChanged();
String name = dataSnapshot.child("First").getValue(String.class);
Log.d(TAG, "Name called "+name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "Error: " + databaseError.toException());
}
};
UserRef.addListenerForSingleValueEvent(eventListener);
I have built a chat application and I am adding the message sent to the recyclerview before it's delivered. I want to add a status like whatsApp(tick for sent, error if an error has occurred). Here is my code of the send message:
In send message I am doing this:
public void sendMessage(final String myUId, String chatterUId, final String messageType, final String messageText) {
if (messageText != null && !messageText.trim().equals("")) {
//String messageType = "text"; // it is text by default
//To update the conversation entry with latest message
if (convId == null || convId.equals("")) {
//generate push key as the conv Id
convId = myConvRef.push().getKey();
}
final FirebaseDatabase rootDB = FirebaseDatabase.getInstance();
final DatabaseReference messagesReference = rootDB.getReference()
.child(FirebaseValues.MESSAGES_TABLE)
.child(convId);
sentMessagePushKey = messagesReference.push().getKey();
sentMessage = new Message(messageText, messageType, myUId);
messages.add(sentMessage);
messagesKey.add(sentMessagePushKey);
messageET.setText("");
messagesAdapter.notifyDataSetChanged();
messageRv.scrollToPosition(messages.size() - 1);
//Not posting full code due to stackoverflow word restriction
}
loadMessages function is:
private void loadMessages() {
Log.d(TAG, "Inside loadMessages()");
messagesRef = FirebaseDatabase.getInstance().getReference().child(FirebaseValues.MESSAGES_TABLE).child(convId);
Query messagesQuery = messagesRef.limitToLast(TOTAL_ITEM_EACH_LOAD).orderByKey();
messagesQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot ds, #Nullable String s) {
Log.d(TAG, "Current Message Key: " + ds.getKey());
if (itemPos++ == 0) {
lastKey = ds.getKey();
}
Log.d(TAG, "last item key is: " + lastKey);
Message message = ds.getValue(Message.class);
if(!sentMessagePushKey.equals(ds.getKey())){
messages.add(message);
messagesKey.add(ds.getKey());
}
else{
//The message has been updated in db successfully
messagesAdapter.updateSent(true);
}
//messages.add(message);
/*if(topicKey!=null){
messagesKey.add(0,null);
messages.add(0,null);
}*/
messagesAdapter.notifyDataSetChanged();
messageRv.scrollToPosition(messages.size() - 1);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
messagesAdapter.updateSent(false);
}
});
}
when child is added I want to update show the sent tick on the recylerview Item.
MessagesAdapter:
public class MessagesAdapter extends RecyclerView.Adapter<MessagesAdapter.MessageViewHolder> {
//Other content i.e message
private static final int CONTENT = 0;
//Topic content
private static final int TOPIC_TYPE = 1;
//My message
private static final int MY_MESSAGE = 2;
//My Image message
private static final int MY_IMAGE_MESSAGE = 3;
//My Voice note
private static final int MY_VOICE_NOTE = 4;
//Other person's messages
private static final int OTHER_IMAGE_MESSAGE = 5;
private static final int OTHER_VOICE_TYPE = 6;
private static final String TAG = "MessageAdapterTAG" ;
static final int PERMISSION_STORAGE = 99;
private ArrayList<Message> messages;
private Context mContext;
private FirebaseDatabase mDb;
private ArrayList<String> messagesKey;
private String topicKey;
private String convId;
private String myUId;
private boolean tag = false;
float ratingVal = -1;
int noOfRates=0;
public MessagesAdapter(Context context, ArrayList<Message> messages, ArrayList<String> messagesKey,String myUId, String convId, String topicKey) {
mContext = context;
this.messages = messages;
mDb = FirebaseDatabase.getInstance();
this.messagesKey = messagesKey;
this.myUId = myUId;
this.convId = convId;
this.topicKey = topicKey;
}
View view = null;
#Override
public MessagesAdapter.MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType==TOPIC_TYPE){
//User came through topic
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.topic_chat_layout, parent, false);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
AbsListView.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(params);
}
else if(viewType==MY_MESSAGE){
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_bubble_layout, parent, false);
}
else if(viewType==MY_IMAGE_MESSAGE){
//Image message
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_image_message_layout, parent, false);
}
else if(viewType==MY_VOICE_NOTE){
//Voice message
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_voice_message_layout, parent, false);
}
else if(viewType == OTHER_IMAGE_MESSAGE){
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chatter_image_message_layout, parent, false);
}
else if(viewType==OTHER_VOICE_TYPE){
//Voice message
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chatter_voice_message_layout, parent, false);
}
else{
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chatter_chat_bubble_layout, parent, false);
}
return new MessageViewHolder(view, mContext);
}
public void updateSent(boolean sent){
if(sent){
//Message is sent
}
else{
//error occured
}
}
#Override
public void onBindViewHolder(#NonNull final MessageViewHolder holder, int position) {
Message model = messages.get(position);
if(getItemViewType(position)==TOPIC_TYPE){
Log.d(TAG, "Topic Key:"+topicKey);
//Log.d(TAG, "message below topic: " + model.getText());
DatabaseReference topicRef = FirebaseDatabase.getInstance().getReference()
.child(FirebaseValues.TOPICS_TABLE).child(topicKey);
topicRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final Topics topic = dataSnapshot.getValue(Topics.class);
TextView topicTv = holder.mView.findViewById(R.id.topicTextTv);
TextView usernameTv = holder.mView.findViewById(R.id.usernameTv);
TextView timeTv = holder.mView.findViewById(R.id.timestampTv);
CircleImageView userImage = holder.mView.findViewById(R.id.userImg);
if(topic!=null){
final TextView rateTv;
rateTv = holder.mView.findViewById(R.id.ratingTv);
final DatabaseReference ratingRef = FirebaseDatabase.getInstance().getReference()
.child(FirebaseValues.RATING_TABLE)
.child(topic.getUid());
ratingRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Rating rating = dataSnapshot.getValue(Rating.class);
if(rating!=null){
ratingVal = rating.getTotal_rating();
noOfRates = rating.getNo_of_rates();
}
else{
ratingVal = 0;
}
rateTv.setText(String.format("%.1f", ratingVal/noOfRates)+"/5");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
rateTv.setTooltipText(String.format("%.1f", ratingVal/noOfRates)+" average rating from "+ noOfRates + "ratings");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e(TAG, "Database Error: "+ databaseError.getMessage());
}
});
TextView rateUserTv;
rateUserTv = holder.mView.findViewById(R.id.rateUserTv);
rateUserTv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//open rate user Dialog
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext);
// ...Irrelevant code for customizing the buttons and title
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.rating_layout, null);
final SmileRating smileRating = dialogView.findViewById(R.id.smile_rating);
dialogBuilder.setView(dialogView);
final AlertDialog alertDialog = dialogBuilder.create();
Button submitBtn = dialogView.findViewById(R.id.submitRatingBtn);
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final int rating = smileRating.getRating();
if(ratingVal>=0){
noOfRates+=1;
float newRate = (ratingVal+rating);
Log.d(TAG, "New Rating: "+newRate);
Rating tempRate = new Rating(newRate, noOfRates);
ratingRef.setValue(tempRate).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
DatabaseReference userRatingRef = FirebaseDatabase.getInstance().getReference()
.child(FirebaseValues.USER_TABLE)
.child(topic.getUid())
.child(FirebaseValues.RATING_TABLE)
.child(myUId);
userRatingRef.setValue(rating).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(mContext, "Thanks for rating the conversation", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
}
});
}
}
});
alertDialog.show();
}
});
topicTv.setText(topic.getText());
String time = GetTimeAgo.getTimeAgo(topic.getTimestampCreatedLong(), mContext);
timeTv.setText(time);
if(!topic.isSecret()){
holder.setUserImage(topic.getUid(), userImage);
holder.setUsername(topic.getUid(), usernameTv);
}
else{
usernameTv.setText("Anonymous");
}
}
else{
topicTv.setText("Topic not found");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
else if(getItemViewType(position)==MY_IMAGE_MESSAGE){
holder.setImageMessage(convId,messagesKey.get(position), model.getText());
}
else if(getItemViewType((position))==MY_VOICE_NOTE){
holder.setVoiceMessage(convId, messagesKey.get(position), model.getText());
}
else if( getItemViewType(position)==OTHER_IMAGE_MESSAGE){
//to replace sent to received
holder.setImageMessage(convId,messagesKey.get(position), model.getText().replace("Sent","Received"));
}
else if(getItemViewType(position)==OTHER_VOICE_TYPE){
holder.setVoiceMessage(convId, messagesKey.get(position), model.getText().replace("Sent","Received"));
}
else{
holder.setMessage(model.getText(), model.getFrom());
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
PrettyDialog pd = new PrettyDialog(mContext);
pd.setTitle("Message Options");
pd.addButton(
"Delete Message", // button text
R.color.pdlg_color_white, // button text color
R.color.pdlg_color_red, // button background color
new PrettyDialogCallback() { // button OnClick listener
#Override
public void onClick() {
// Do what you gotta do
}
}
).addButton(
"Retract Message",
R.color.pdlg_color_white,
R.color.pdlg_color_red,
new PrettyDialogCallback() {
#Override
public void onClick() {
// Dismiss
}
}
).addButton(
"Copy", // button text
R.color.pdlg_color_white, // button text color
R.color.pdlg_color_green, // button background color
new PrettyDialogCallback() { // button OnClick listener
#Override
public void onClick() {
// Do what you gotta do
}
}
);
pd.show();
return true;
}
});
Log.d(TAG, "message: " + model.getText());
}
}
#Override
public int getItemCount() {
return messages.size();
}
#Override
public int getItemViewType(int position) {
if(position==0 && topicKey!=null){
//Insert the topic as first element
return TOPIC_TYPE;
}
Message message = messages.get(position);
if(message.getFrom().equals(myUId)){
//Message is mine
if(message.getType().equals(FirebaseValues.IMAGE_TYPE)){
return MY_IMAGE_MESSAGE;
}
else if(message.getType().equals(FirebaseValues.VOICE_NOTE_TYPE)){
return MY_VOICE_NOTE;
}
return MY_MESSAGE;
}
else{
//The message is from other user
if(message.getType().equals((FirebaseValues.IMAGE_TYPE))){
return OTHER_IMAGE_MESSAGE;
}
else if(message.getType().equals(FirebaseValues.VOICE_NOTE_TYPE)){
return OTHER_VOICE_TYPE;
}
}
return CONTENT;
}
I am unable to post holder class code due to the stackoverflow's word limit.
EDIT:
I have solved this problem myself by removing the object from the recycler view and adding it again and them call notifyItemInserted() on recyclerview. If anyone has better solution please do answer
I got a source code of a food delivery app from git. he is parsing a website and displaying the menu items, I guess to see the
instead of this I have created a fire-base database and stored one food item for testing
I want to display my item from the fire-base to the app menu I will show the code of all food item fragment,
package com.example.guanzhuli.foody.HomePage.fragment;
public class AllTabFragment extends Fragment {
private String baseUrl = "http://rjtmobile.com/ansari/fos/fosapp/fos_food_loc.php?city=";
private String TAG = "ALLFOOD";
private StorageReference mStorageRef;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("menu");
ArrayList<Food> foods = new ArrayList<>();
private RecyclerView mRecyclerView;
private AllFoodAdapter adapter;
private RecyclerView.LayoutManager layoutManager;
String foodName;
public AllTabFragment() {
// 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_all_tab, container, false);
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
foodName = snapshot.child("name").getValue().toString();
String foodPrice = snapshot.child("prize").getValue().toString();
Toast.makeText(getActivity(), foodName, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// Request Data From Web Service
if (foods.size() == 0) {
objRequestMethod();
}
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview_all);
mRecyclerView.setHasFixedSize(false);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
adapter = new AllFoodAdapter(getActivity(), foods);
adapter.setOnItemClickListener(new AllFoodAdapter.OnRecyclerViewItemClickListener() {
#Override
public void onItemClick(View view, String data) {
Bundle itemInfo = new Bundle();
for (int i = 0; i < foods.size(); i++) {
if (foods.get(i).getId() == Integer.valueOf(data)) {
itemInfo.putInt("foodId", foods.get(i).getId());
itemInfo.putString("foodName", foods.get(i).getName());
// itemInfo.putString("foodName", foodName);
itemInfo.putString("foodCat", foods.get(i).getCategory());
itemInfo.putString("foodRec", foods.get(i).getRecepiee());
itemInfo.putDouble("foodPrice", foods.get(i).getPrice());
itemInfo.putString("foodImage", foods.get(i).getImageUrl());
break;
}
}
FoodDetailFragment foodDetailFragment = new FoodDetailFragment();
foodDetailFragment.setArguments(itemInfo);
getActivity().getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out)
.replace(R.id.main_fragment_container, foodDetailFragment)
.addToBackStack(AllTabFragment.class.getName())
.commit();
}
});
mRecyclerView.setAdapter(adapter);
return view;
}
private void objRequestMethod() {
HomePageActivity.showPDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, buildUrl(), null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.d(TAG, jsonObject.toString());
try {
JSONArray foodsJsonArr = jsonObject.getJSONArray("Food");
for (int i = 0; i < foodsJsonArr.length(); i++) {
JSONObject c = foodsJsonArr.getJSONObject(i);
String id = c.getString("FoodId");
String name = c.getString("FoodName");
String recepiee = c.getString("FoodRecepiee");
String price = c.getString("FoodPrice");
String category = c.getString("FoodCategory");
String thumb = c.getString("FoodThumb");
final Food curFood = new Food();
curFood.setCategory(category);
curFood.setName(name);
curFood.setRecepiee(recepiee);
curFood.setPrice(Double.valueOf(price));
curFood.setId(Integer.valueOf(id));
curFood.setImageUrl(thumb);
foods.add(curFood);
// Log.e("Current Food", curFood.getName());
ImageLoader imageLoader = VolleyController.getInstance().getImageLoader();
imageLoader.get(thumb, new ImageLoader.ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Image Load Error: " + error.getMessage());
}
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean arg1) {
if (response.getBitmap() != null) {
curFood.setImage(response.getBitmap());
// Log.e("SET IMAGE", curFood.getName());
adapter.notifyData(foods);
}
}
});
foods.get(i).setImage(curFood.getImage());
}
} catch (Exception e) {
System.out.println(e);
}
HomePageActivity.disPDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
VolleyLog.d(TAG, "ERROR" + volleyError.getMessage());
Toast.makeText(getActivity(), volleyError.getMessage(),
Toast.LENGTH_SHORT).show();
HomePageActivity.disPDialog();
}
});
VolleyController.getInstance().addToRequestQueue(jsonObjReq);
}
private String buildUrl() {
return baseUrl + HomePageActivity.City;
}
}
I got food name from fire-base and stored in the string called "foodname" Now I want to display it in the menu, how can I do it?
if my question is wrong please forgive me, please help me
package com.example.guanzhuli.foody.HomePage.adapter;
public class AllFoodAdapter extends RecyclerView.Adapter<AllHolder> implements
View.OnClickListener {
private Context mContext;
ArrayList<Food> foods;
public String TAG = "ALLFOOD";
//
// public AllFoodAdapter(Context context) {
// mContext = context;
// }
public AllFoodAdapter(Context context, ArrayList<Food> foods) {
mContext = context;
this.foods = foods;
}
#Override
public AllHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.cardview_food, parent, false);
AllHolder allHolder = new AllHolder(v);
v.setOnClickListener(this);
return allHolder;
}
#Override
public void onBindViewHolder(AllHolder holder, int position) {
holder.mTextId.setText(String.valueOf(foods.get(position).getId()));
holder.mTextName.setText(foods.get(position).getName());
holder.mTextPrice.setText(String.valueOf(foods.get(position).getPrice()));
holder.mTextCategory.setText(foods.get(position).getCategory());
holder.mImageView.setImageBitmap(foods.get(position).getImage());
holder.itemView.setTag(foods.get(position).getId());
}
#Override
public int getItemCount() {
return foods.size();
}
public void notifyData(ArrayList<Food> foods) {
// Log.d("notifyData ", foods.size() + "");
this.foods = foods;
notifyDataSetChanged();
}
public static interface OnRecyclerViewItemClickListener {
void onItemClick(View view, String data);
}
private OnRecyclerViewItemClickListener mOnItemClickListener = null;
public void setOnItemClickListener(OnRecyclerViewItemClickListener listener) {
this.mOnItemClickListener = listener;
}
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, String.valueOf(view.getTag()));
} else {
Log.e("CLICK", "ERROR");
}
}
}
class AllHolder extends RecyclerView.ViewHolder {
NetworkImageView mImage;
ImageView mImageView;
TextView mTextId, mTextName, mTextCategory, mTextPrice;
public AllHolder(View itemView) {
super(itemView);
// mImage = (NetworkImageView) itemView.findViewById(R.id.food_img);
mImageView = (ImageView) itemView.findViewById(R.id.food_img);
mTextId = (TextView) itemView.findViewById(R.id.food_id);
mTextName = (TextView) itemView.findViewById(R.id.food_name);
mTextPrice = (TextView) itemView.findViewById(R.id.food_price);
mTextId = (TextView) itemView.findViewById(R.id.food_id);
mTextCategory = (TextView) itemView.findViewById(R.id.food_category);
}
}
Please help me, because it is an important project for me
If you want to display the strings you have received from firebase in a new activity as a list, you can declare an ArrayList and then add those strings to it and then with an adapter set it to display.
In code it looks something like this:
private ArrayList array;
private ListView listView;
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
private String curName;
//set them
listView = findViewById(R.id.list1);
array = new ArrayList<String>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("menu");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
array.add(ds.child("name").getValue(String.class));
}
ArrayAdapter adapter = new ArrayAdapter(Main6Activity.this, android.R.layout.simple_list_item_1, array);
listView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
stackoverflow was not conceived to get complete code solutions. We can only help you on some point. Other than that, you need to think to use the Food class for read and write values on your db. When you retrive the values, get it as a Food object casting it by method dataSnapshot.getValue("object class");...
In your case you need a code like this:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Food food = snapshot.getValue(Food.class);
//here you need to add the food object to a list and after the for diplay it with adapter.
//for example foodsList.add(food);
}
foodsList.setAdapter(myAdepter); //ecc
}
If you need help, please tell us more
You seem to be loading the food items from the database, and reading the values from them. All that's left to do, is add each item to the foods array, and tell the adapter that its data has changed:
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String foodName = snapshot.child("name").getValue(String.class);
String foodPrice = snapshot.child("prize").getValue(String.class);
Food food = new Food();
food.setName(name);
food.setPrice(Double.valueOf(price));
foods.add(food);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
My database structure
I am trying to create an activity where I can display all the logs. Just timestamp and the log message. I have tried with firebaseUI and adapter but I can't get the data to show. Best I have done was to post same last log in all positions. This is what I have so far but no success. I am new to firebase and all I need is to display the logs in a list. It can be lisView or recyclerView. If anyone can help me with code or example. Thank you.
Database structure is | "logs" node / userId / logId / fields |
public class LogActivity extends AppCompatActivity {
private static final String TAG = "LogActivity";
private static final int ACTIVITY_NUM = 3;
//widgets
private Context mContext = LogActivity.this;
private RecyclerView mLogRecycleView;
private TextView timeStamp, log;
//firebase
private DatabaseReference mLogDatabase;
private FirebaseAuth mAuth;
//adapter
private FirebaseRecyclerAdapter adapter;
//vars
private String mCurrentUserID, logID;
List<AppLogs> logsList = new ArrayList<>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log);
Log.d(TAG, "onCreate: Started");
mCurrentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
mLogRecycleView = findViewById(R.id.recyclerList);
mLogDatabase = FirebaseDatabase.getInstance().getReference().child("logs").child(mCurrentUserID);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mLogRecycleView.setHasFixedSize(true);
mLogRecycleView.setLayoutManager(linearLayoutManager);
firebaseListAdapter();
mLogRecycleView.setAdapter(adapter);
setupBottomNavigationView();
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
private void firebaseListAdapter() {
Log.d(TAG, "firebaseListAdapter: started");
Query logQuery = mLogDatabase.orderByChild("time");
FirebaseRecyclerOptions<AppLogs> options =
new FirebaseRecyclerOptions.Builder<AppLogs>()
.setQuery(logQuery, AppLogs.class).build();
adapter = new FirebaseRecyclerAdapter<AppLogs, LogViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final LogViewHolder holder, int position, #NonNull AppLogs model) {
Log.d(TAG, "onBindViewHolder: started");
//get the ID of the messages
//final String logID = getRef(position).getKey();
//Log.d(TAG, "onBindViewHolder: logID : " + logID);
Query logQuery = mLogDatabase;
logQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot singData : dataSnapshot.getChildren()) {
//AppLogs logs = dataSnapshot.getValue(AppLogs.class);
Log.d(TAG, "onChildAdded: log:==== " + singData.child("log").getValue());
//Log.d(TAG, "onChildAdded: log_ID:==== " + logs.getLog_id());
String log = singData.child("log").getValue().toString();
// String timeStamp = Long.toString(logs.getTime());
//
holder.setLog(log);
// holder.setTimeStamp(timeStamp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public LogViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Log.d(TAG, "onCreateViewHolder: create users view holder: ");
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_log_list_view, parent, false);
return new LogViewHolder(view);
}
};
}
public static class LogViewHolder extends RecyclerView.ViewHolder {
View mView;
public LogViewHolder(View itemView) {
super(itemView);
this.mView = itemView;
}
public void setLog(String log) {
TextView tvLog = mView.findViewById(R.id.tvLog);
tvLog.setText(log);
}
public void setTimeStamp(String timeStamp) {
TextView tvTimeStamp = mView.findViewById(R.id.tvTimeStamp);
tvTimeStamp.setText(timeStamp);
}
}
/*
*BottomNavigationView Setup
*/
private void setupBottomNavigationView() {
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavViewBar);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(mContext, this, bottomNavigationViewEx);
Menu menu = bottomNavigationViewEx.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(true);
}
}
and my log model class
package com.logistics.alucard.socialnetwork.Models;
public class AppLogs {
private String log, log_id;
private long time;
public AppLogs(String log, String log_id, long time) {
this.log = log;
this.log_id = log_id;
this.time = time;
}
public AppLogs() {
}
public String getLog() {
return log;
}
public void setLog(String log) {
this.log = log;
}
public String getLog_id() {
return log_id;
}
public void setLog_id(String log_id) {
this.log_id = log_id;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
}
I manage to figure it out! Thank you for your help. Still a bit confusing how to
build queries but I'll try to get better :)
This is my solution to the firebase retrieve data:
protected void onBindViewHolder(#NonNull final LogViewHolder holder, int position, #NonNull AppLogs model) {
Log.d(TAG, "onBindViewHolder: started");
//get the ID of the messages
final String logID = getRef(position).getKey();
//Log.d(TAG, "onBindViewHolder: logID : " + logID);
Query logQuery = mLogDatabase;
logQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//AppLogs appLogs = dataSnapshot.getValue(AppLogs.class);
//Log.d(TAG, "onDataChange: logs:---------" + dataSnapshot.child(logID).child("log").getValue());
String log = dataSnapshot.child(logID).child("log").getValue().toString();
String timeStamp = dataSnapshot.child(logID).child("time").getValue().toString();
Log.d(TAG, "onDataChange: logs:--------------" + log);
holder.setLog(log);
holder.setTimeStamp(timeStamp);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
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);