The probelm occurs when i use the swipeRefreshLayout to load all messages from database. When i refresh the recycler view it will duplicate my first key as many times as i refresh. Data is only viewed differently on recycler view, it wont affect database.
How can i stop it from displaying the first key multiple times in recycler view? Any help would be great i don't know what condition i should use to fix this.
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
public class MessageActivity extends AppCompatActivity {
// Initialise
private String userID;
private DatabaseReference databaseReference;
private TextView messageTitle;
private TextView lastActive;
private CircleImageView profileImg;
private Toolbar messageToolbar;
private FirebaseAuth firebaseAuth;
private String currentUser;
private EditText messageText;
private ImageButton sendMessage;
// Initialise Array list
private final List<Messages> messages_list = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
// Messages to load to and current page
private MessageAdapter messageAdapter;
private int current_page = 1;
private static final int messages_to_load = 10;
// Messages RecylerView
private RecyclerView messageView;
private SwipeRefreshLayout swipeRefreshLayout;
private int position = 0;
private String last_message ="";
private String first_message = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
// Setup Toolbar
messageToolbar = findViewById(R.id.message_bar);
setSupportActionBar(messageToolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
// Get Database Reference
databaseReference = FirebaseDatabase.getInstance().getReference();
firebaseAuth = FirebaseAuth.getInstance();
currentUser = firebaseAuth.getCurrentUser().getUid();
// Get user ID from Intent
userID = getIntent().getStringExtra("user_ID");
String UserName = getIntent().getStringExtra("user_Name");
// getSupportActionBar().setTitle(UserName);
// Inflater Service
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View message_actionbar_view = inflater.inflate(R.layout.message_custom_imagebar,null);
actionBar.setCustomView(message_actionbar_view);
// Action bar
messageTitle = findViewById(R.id.message_bar_title);
lastActive = findViewById(R.id.message_bar_lastseen);
profileImg = findViewById(R.id.message_image);
messageText = findViewById(R.id.send_message_text);
sendMessage = findViewById(R.id.message_send_btn);
messageAdapter = new MessageAdapter(messages_list);
messageView = findViewById(R.id.Messages_recycler);
// set swipe layout
swipeRefreshLayout = findViewById(R.id.swipe_layout_message);
linearLayoutManager = new LinearLayoutManager(this);
messageView.setHasFixedSize(true);
messageView.setLayoutManager(linearLayoutManager);
messageView.setAdapter(messageAdapter);
// Call get messages method
getMessages();
// Set values
messageTitle.setText(UserName);
databaseReference.child("Users").child(userID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String onlineUser = dataSnapshot.child("online").getValue().toString();
String userImg = dataSnapshot.child("image").toString();
Timestamp timestamp = new Timestamp();
long lastSeen = Long.parseLong(onlineUser);
String lastActives = timestamp.getTimeAgo(lastSeen, getApplicationContext());
// lastActive.setText(lastActives);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
// click event on image button
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageText();
}
});
// What happens when you swipe to refresh
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
current_page++;
position = 0;
getAllMessages();
}
});
}
// Load a number of messages
private void getAllMessages() {
DatabaseReference message_reference = databaseReference.child("Messages").child(currentUser).child(userID);
Query message_Query = message_reference.orderByKey().endAt(last_message).limitToLast(10);
message_Query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Messages message = dataSnapshot.getValue(Messages.class);
String last_message_key = dataSnapshot.getKey();
messages_list.add(position++, message);
// Checks if position is 1
if(position == 1){
last_message = last_message_key;
}
messageAdapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
linearLayoutManager.scrollToPositionWithOffset(10,0);
}
#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) {
}
});
}
private void getMessages() {
DatabaseReference message_reference = databaseReference.child("Messages").child(currentUser).child(userID);
Query message_Query = message_reference.limitToLast(current_page * messages_to_load);
message_Query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
position++;
if(position == 1){
String last_message_key = dataSnapshot.getKey();
last_message = last_message_key;
first_message = last_message_key;
}
messages_list.add(messages);
messageAdapter.notifyDataSetChanged();
messageView.scrollToPosition(messages_list.size() - 1);
swipeRefreshLayout.setRefreshing(false);
}
#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) {
}
});
}
private void sendMessageText() {
String message = messageText.getText().toString();
if(!TextUtils.isEmpty(message)){
String current_User = "Messages/" + currentUser + "/" + userID;
String chat_User = "Messages/" + userID + "/" + currentUser;
DatabaseReference message_push = databaseReference.child("Messages").child(currentUser).child(userID).push();
String pushID = message_push.getKey();
Map sendMessageMap = new HashMap();
sendMessageMap.put("message", message);
sendMessageMap.put("seen", false);
sendMessageMap.put("type", "text");
sendMessageMap.put("time", ServerValue.TIMESTAMP);
sendMessageMap.put("from", currentUser);
Map sendUserMap = new HashMap();
sendUserMap.put(current_User + "/" + pushID, sendMessageMap);
sendUserMap.put(chat_User + "/" + pushID, sendMessageMap);
messageText.setText("");
databaseReference.updateChildren(sendUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(#Nullable DatabaseError databaseError, #NonNull DatabaseReference databaseReference) {
if(databaseError != null){
Log.d("CHAT_LOG", databaseError.getMessage());
}
}
});
}
}
}
It should Print Only once to recycler view, not 2 or 3 times.
Related
I encountered this error and tried to find some solutions but no clue yet. The problem is I am trying to search the item on my phone, once find it, I will click on the item and then update it.
However I got "com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.projects.inputData" error.
BEFORE I click update, my firebase looks like:
AFTER I updated item, it looks like this and all the old data has been automatically removed:
Can someone help me out? Please.
package com.example.projects;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.transition.AutoTransition;
import android.transition.TransitionManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.GenericTypeIndicator;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.concurrent.TimeUnit;
public class mainActivity extends AppCompatActivity implements View.OnClickListener {
FirebaseDatabase firebaseDatabase;
DatabaseReference myRef;
private FloatingActionButton main_fab;
private TextView total_amount, total_buy_price;
private RecyclerView mainRecyclerView;
private String post_key = "";
private String staff_name ="";
private String size = "";
private String material = "";
private String colour = "";
private String notes = "";
private String type = "";
private int money = 0;
private int number = 0;
public int soldNumber = 0;
public int soldPrice = 0;
ArrayList<inputData> dataList;
SearchView searchView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
firebaseDatabase = FirebaseDatabase.getInstance("https://stuff-management-app-default-rtdb.asia-southeast1.firebasedatabase.app");
mainRecyclerView = findViewById(R.id.main_recyclerview);
searchView = findViewById(R.id.searchView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
linearLayoutManager.setReverseLayout(true);
mainRecyclerView.setHasFixedSize(true);
mainRecyclerView.setLayoutManager(linearLayoutManager);
total_buy_price = findViewById(R.id.totalBuyPrice);
total_amount = findViewById(R.id.main_total_records);
myRef = firebaseDatabase.getReference("stuff records");
myRef.addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
int totalRecord = 0;
int totalBuyPrice = 0;
dataList = new ArrayList<>();
for(DataSnapshot snap: snapshot.getChildren()){
inputData data = snap.getValue(inputData.class);
totalRecord += data.getNumber();
total_amount.setText( totalRecord);
totalBuyPrice += data.getMoney();
total_buy_price.setText( totalBuyPrice);
dataList.add(snap.getValue(inputData.class));
}
AdapterClass adapterClass = new AdapterClass(dataList);
mainRecyclerView.setAdapter(adapterClass);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
if (searchView != null) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(newText);
return true;
}
});
}
}
private void search(String str) {
ArrayList<inputData> myList = new ArrayList<>();
for(inputData object : dataList){
if (object.getStaff_name().toLowerCase().contains(str.toLowerCase())){
myList.add(object);
}
}
AdapterClass adapterClass = new AdapterClass(myList);
mainRecyclerView.setAdapter(adapterClass);
adapterClass.notifyDataSetChanged();
}
private int getIndex(Spinner spinner, String myString){
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(myString)){
return i;
}
}
return 0;
}
private void updateInfo() {
AlertDialog.Builder myDialog = new AlertDialog.Builder(this);
LayoutInflater inflater = LayoutInflater.from(this);
View mView = inflater.inflate(R.layout.update_page, null);
myDialog.setView(mView);
final AlertDialog dialog = myDialog.create();
final Spinner itemSpinner = mView.findViewById(R.id.input_size_spinner);
final TextView input_name = mView.findViewById(R.id.input_record);
final EditText input_price = mView.findViewById(R.id.input_price);
final EditText input_number = mView.findViewById(R.id.input_number);
final EditText input_description = mView.findViewById(R.id.input_description);
final EditText input_material = mView.findViewById(R.id.input_material);
final Spinner colourSpinner = mView.findViewById(R.id.input_colour_spinner);
final EditText input_types = mView.findViewById(R.id.input_type);
final Button delBtn = mView.findViewById(R.id.input_cancel);
final Button updateBtn = mView.findViewById(R.id.input_save);
final Button sellBtn = mView.findViewById(R.id.button2);
input_price.setText(String.valueOf(money));
input_description.setText(notes);
input_name.setText(staff_name);
input_material.setText(material);
colourSpinner.setSelection(getIndex(colourSpinner, colour));
input_types.setText(type);
input_number.setText(String.valueOf(number));
itemSpinner.setSelection(getIndex(itemSpinner, size));
//sold
final EditText sellNum = mView.findViewById(R.id.sellAmount);
final EditText sellPrice = mView.findViewById(R.id.sellMoney);
sellNum.setText(String.valueOf(number - 1));
sellPrice.setText(String.valueOf(soldPrice));
String sellNumber = sellNum.getText().toString();
String sellPri = sellPrice.getText().toString();
String[] colourr = new String[]{};
final List<String> colourList = new ArrayList<String>(Arrays.asList(colourr));
// Initializing an ArrayAdapter
final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
this, R.layout.spinner_item, colourList);
myRef = firebaseDatabase.getReference("user_define_colour");
// Attach a listener to read the data at our posts reference
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
colourList.clear();
for (DataSnapshot child : dataSnapshot.getChildren()) {
GenericTypeIndicator<ArrayList<String>> t = new GenericTypeIndicator<ArrayList<String>>() {
};
ArrayList<String> value = child.getValue(t);
colourList.addAll(value);
spinnerArrayAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item);
colourSpinner.setAdapter(spinnerArrayAdapter);
// ----- retrieve colour from firebase
myRef = firebaseDatabase.getReference("stuff records");
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
number = Integer.parseInt(input_number.getText().toString());
notes = input_description.getText().toString();
money = Integer.parseInt(input_price.getText().toString());
staff_name = input_name.getText().toString();
material = input_material.getText().toString();
colour = colourSpinner.getSelectedItem().toString();
type = input_types.getText().toString();
size = itemSpinner.getSelectedItem().toString();
if ( number == 0) {
Toast.makeText(mainActivity.this, "Finished", Toast.LENGTH_SHORT).show();
return;
}
inputData data = new inputData(staff_name, size, material, colour, notes, Integer.parseInt(String.valueOf(money)), Integer.parseInt(String.valueOf(number)), post_key, type);
myRef.child(post_key).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(mainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(mainActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
dialog.dismiss();
}
});
}
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.myViewHolder> {
ArrayList<inputData> dataList;
public AdapterClass(ArrayList<inputData> dataList) {
this.dataList = dataList;
}
#NonNull
#Override
public AdapterClass.myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.main_retrieve, parent, false);
return new AdapterClass.myViewHolder(view);
}
FirebaseRecyclerOptions<inputData> options = new FirebaseRecyclerOptions.Builder<inputData>()
.setQuery(myRef,inputData.class)
.build();
#Override
public void onBindViewHolder(#NonNull AdapterClass.myViewHolder holder, int position) {
holder.description.setText(dataList.get(position).getNotes());
holder.name.setText(dataList.get(position).getStaff_name());
holder.money.setText(String.valueOf(dataList.get(position).getMoney()));
holder.material.setText(dataList.get(position).getMaterial());
holder.size.setText(dataList.get(position).getSize());
holder.colour.setText(dataList.get(position).getColour());
holder.type.setText(dataList.get(position).getTypes());
holder.number.setText(String.valueOf(dataList.get(position).getNumber()));
holder.main_mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateInfo();
}
});
}
#Override
public int getItemCount() {
return dataList.size();
}
public class myViewHolder extends RecyclerView.ViewHolder {
View main_mView;
TextView name, number, money, material, size, colour, description, type;
public myViewHolder(#NonNull View itemView) {
super(itemView);
main_mView = itemView;
description = itemView.findViewById(R.id.notes);
name = itemView.findViewById(R.id.staff_name);
money = itemView.findViewById(R.id.money);
number = itemView.findViewById(R.id.number);
colour = itemView.findViewById(R.id.colour);
material = itemView.findViewById(R.id.material);
size = itemView.findViewById(R.id.size);
type = itemView.findViewById(R.id.types);
}
}
}
}
The problem is shown
inputData data = snap.getValue(inputData.class);
whenever new expense data comes in add it to main expense data list and notify adapter.
expenseArrayList.add(new Data(new_item, new_notes, new_amount, new_date));
if (adapter == null) {
expense_recyclerView.setAdapter(adapter);
} else{
adapter.notifyItemInserted(expense_data_list.size()+1)
}
I got a big problem that I can't fix by myself, I need to put in Firebase the Likes of my social network app with the id POSTID + USERID, but actually, I don't know how to bring the postid and paste it in the likes id (post key).
The main problem is about the post_key: it gives me a random id instead of the post id but honestly, I have no idea how to bring it, so the result is LIKESID = RANDOMID + USERID, instead of LIKESID = POSTID + USERID
I think is very simple to fix it for an expert programmer but as a beginner, this blows my mind
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
ArrayList<Model> mList;
Context context;
public MyAdapter(Context context, ArrayList<Model> mList){
this.mList = mList;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item , parent , false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Model model = mList.get(position);
holder.nickname.setText(model.getNickname());
holder.date.setText(model.getDate());
holder.time.setText(model.getTime());
holder.post.setText(model.getPost());
}
#Override
public int getItemCount() {
return mList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
ImageButton like;
Boolean likechecker = false;
String currentUserID;
FirebaseAuth mAuth;
TextView date, time, nickname, post, liketextview;
DatabaseReference LikesRef;
DatabaseReference Database = FirebaseDatabase.getInstance().getReference();
final String post_key = Database.push().getKey();
Integer countlikes;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
date = itemView.findViewById(R.id.date_text);
time = itemView.findViewById(R.id.time_text);
post = itemView.findViewById(R.id.post_text);
nickname = itemView.findViewById(R.id.nickname_text);
like = itemView.findViewById(R.id.like_btn);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
LikesRef = (FirebaseDatabase.getInstance().getReference().child("Likes"));
setlikebuttonstatus(post_key);
like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
likechecker = true;
LikesRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(likechecker.equals(true)){
if (snapshot.child(post_key).hasChild(currentUserID)){
LikesRef.child(post_key).child(currentUserID).removeValue();
likechecker = false;
}
else {
LikesRef.child(post_key).child(currentUserID).setValue(true);
likechecker = false;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
public void setlikebuttonstatus(final String post_key) {
post = itemView.findViewById(R.id.post_text);
liketextview = itemView.findViewById(R.id.like_textview);
LikesRef = (FirebaseDatabase.getInstance().getReference().child("Likes"));
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
LikesRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.child(post_key).hasChild(currentUserID)){
countlikes = (int) snapshot.child(post_key).getChildrenCount();
like.setImageResource(R.drawable.like);
liketextview.setText(Integer.toString(countlikes) + " Likes");}
else {
countlikes = (int) snapshot.child(post_key).getChildrenCount();
like.setImageResource(R.drawable.notlike);
liketextview.setText(Integer.toString(countlikes) + " Likes");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
}
Homepage.Activity
package com.example.scrapbase11;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerAdapter_LifecycleAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import java.awt.font.TextAttribute;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.EventListener;
import java.util.HashMap;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class HomepageActivity extends AppCompatActivity {
String currentUserID;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef, PostsRef, LikesRef;
private TextView nicknamedisplayed, displaynumblikes;
private EditText posttext;
private CircleImageView circleImageView;
private Button pubblicabtn;
private String saveCurrentdate, saveCurrenttime, tsaveCurrentdate, tsaveCurrenttime, postRandomName, nickname;
private RecyclerView recyclerView;
private FirebaseDatabase db = FirebaseDatabase.getInstance();
private DatabaseReference root = db.getReference().child("Posts");
private DatabaseReference Database = FirebaseDatabase.getInstance().getReference();
private MyAdapter adapter;
private ArrayList<Model> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
displaynumblikes = (TextView) findViewById(R.id.like_textview);
nicknamedisplayed = (TextView) findViewById(R.id.nickname_textview);
posttext = (EditText) findViewById(R.id.postedittext);
pubblicabtn = (Button) findViewById(R.id.pubblica_btn);
circleImageView = (CircleImageView) findViewById(R.id.home_profileimage);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
adapter = new MyAdapter(this, list);
recyclerView.setAdapter(adapter);
Calendar calFordDate = Calendar.getInstance();
Calendar calFordTime = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd/MM/yyyy");
saveCurrentdate = currentDate.format(calFordDate.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm");
saveCurrenttime = currentTime.format(calFordTime.getTime());
final String post_key = Database.push().getKey();
circleImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Sendtomyprofile();
}
});
nicknamedisplayed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Sendtomyprofile();
}
});
root.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
Model model = dataSnapshot.getValue(Model.class);
list.add(model);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
UsersRef = (FirebaseDatabase.getInstance().getReference().child("Users"));
PostsRef = (FirebaseDatabase.getInstance().getReference().child("Posts"));
LikesRef = (FirebaseDatabase.getInstance().getReference().child("Likes"));
pubblicabtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Savepostmethod();
}
});
// codice per far visualizzare il proprio nickname
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
nickname = snapshot.child("nickname").getValue().toString();
nicknamedisplayed.setText("Welcome back " + nickname);
}
}
// fine del codice per visualizzare il proprio nickname
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(HomepageActivity.this, "Database error :)", Toast.LENGTH_SHORT).show();
}
});
}
private void Sendtomyprofile() {
Intent Gotomyprofileintent =new Intent(HomepageActivity.this, ProfileActivity.class);
startActivity(Gotomyprofileintent);
}
private void Savepostmethod() {
String post = posttext.getText().toString();
if (TextUtils.isEmpty(post)) {
Toast.makeText(this, "Please write something...", Toast.LENGTH_SHORT).show();
} else {
Calendar tcalFordDate = Calendar.getInstance();
Calendar tcalFordTime = Calendar.getInstance();
SimpleDateFormat tcurrentDate = new SimpleDateFormat("ddMMyyyy");
tsaveCurrentdate = tcurrentDate.format(tcalFordDate.getTime());
SimpleDateFormat tcurrentTime = new SimpleDateFormat("HHmm");
tsaveCurrenttime = tcurrentTime.format(tcalFordTime.getTime());
postRandomName = tsaveCurrentdate + tsaveCurrenttime;
HashMap postMap = new HashMap();
postMap.put("userid", currentUserID);
postMap.put("nickname", nickname);
postMap.put("post", post);
postMap.put("time", saveCurrenttime);
postMap.put("date", saveCurrentdate);
PostsRef.child(currentUserID + postRandomName).updateChildren(postMap).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()) {
Toast.makeText(HomepageActivity.this, "Pubblicazione riuscita", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(HomepageActivity.this, "Pubblicazione non riuscita, controlla la tua connessione internet", Toast.LENGTH_SHORT).show();
}
}
});
}
}}
The issue is obvious. You create here:
final String post_key = Database.push().getKey();
Always a random Uid. And by using it here:
setlikebuttonstatus(post_key);
You always end up with LIKESID = RANDOMID + USERID as explained in the question. You also wrote the solution: Write the postUid instead the random one.
What is the model here giving you back? Is it just a string?:
holder.post.setText(model.getPost());
Can you share with us how you get the list of posts and we can find a solution. We basicaly need only the key from each post snapshot instead of the data. You probably have it but it's not mapped for your other code to get it.
With the code from the edit you can get the post uid like this and maybe add to the Model class a property id and add it afterdwards like this:
Model model = dataSnapshot.getValue(Model.class);
String key=dataSnapshot.getKey();
model.id=key;
list.add(model);
I am developing an android app which shows the user with the latest jobs from various fields. I want to display the jobs that the user has applied so far in "Your Applications" section.
But the values are not getting retrieved. It displays a blank activity. I have attached the code.
Applications.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Application;
import android.app.ProgressDialog;
import android.os.Bundle;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Applications extends AppCompatActivity {
DatabaseReference databaseReference;
FirebaseDatabase firebaseDatabase;
RecyclerView recyclerView;
FirebaseUser user;
FirebaseAuth mAuth;
ArrayList<Post> posts;
MyAdap adap;
ProgressDialog pd;
long maxid=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_applications);
recyclerView = findViewById(R.id.work);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
posts = new ArrayList<>();
pd= new ProgressDialog(Applications.this);
pd.setMessage("Loading...");
pd.show();
getSupportActionBar().setTitle("Your Applications");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Job Applications");
Query query = databaseReference.orderByChild(String.valueOf(maxid+1)).equalTo(user.getUid());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
Post p = ds.getValue(Post.class);
posts.add(p);
}
pd.dismiss();
adap = new MyAdap(Applications.this, posts);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
pd.dismiss();
}
});
}
}
Posts.java
public class Post {
private String jobtitle, jobtype, company, location;
public Post() {
}
public Post(String jobtitle, String jobtype, String company, String location) {
this.jobtitle = jobtitle;
this.jobtype = jobtype;
this.company = company;
this.location = location;
}
public String getJobtitle() {
return jobtitle;
}
public void setJobtitle(String jobtitle) {
this.jobtitle = jobtitle;
}
public String getJobtype() {
return jobtype;
}
public void setJobtype(String jobtype) {
this.jobtype = jobtype;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
MyAdap.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MyAdap extends RecyclerView.Adapter<MyAdap.ViewHolder> {
Context cb;
ArrayList<Post> posts;
public MyAdap(Context c, ArrayList<Post> applications){
cb=c;
posts=applications;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(cb).inflate(R.layout.post, parent,false));
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.jobTitle.setText(posts.get(position).getJobtitle());
holder.jobType.setText(posts.get(position).getJobtype());
holder.location.setText(posts.get(position).getLocation());
holder.companyName.setText(posts.get(position).getCompany());
}
#Override
public int getItemCount() {
return posts.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView jobTitle, jobType,companyName,location;
public ViewHolder(#NonNull View itemView) {
super(itemView);
jobTitle = itemView.findViewById(R.id.jobTitle);
jobType = itemView.findViewById(R.id.jobType);
companyName = itemView.findViewById(R.id.companyName);
location = itemView.findViewById(R.id.location);
}
}
}
Here is the image of the database.
I think you have a problem with your orderByChild and equalTo method in the Query section. Please try without the Query and if you want to add sorting read details here.
And one more thing you don't have any jobtype in your database but in your POJO class you have this field in your Constructor.
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
Post p = ds.getValue(Post.class);
posts.add(p);
}
pd.dismiss();
adap = new MyAdap(Applications.this, posts);
recyclerView.setAdapter(adap);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
pd.dismiss();
}
});
You are not attaching adapter to recycle view
adap = new MyAdap(Applications.this, posts);
recyclerView.setAdapter(adap)
you need to set adpater to recycle view
As said by abdul add the adapter to the recycler view and also add the android lifecycle method onStart(); method and in the add adapter.startlisteneing();
I was trying to develop a music app ,so I have two activities like ArtistActivity and FavoriteActivity. My ArtistActivity contains a RecyclerView which loads SongName, SongUrl, SongArtist in a ListView and it loads data from Firebase, and for each item there is a heart bang icon in the end of the item. My main question is when I click item, then I want to send clicked item in other activity which was my FavoriteActivity and I want to play the song when item is clicked on FavoriteActivity. So for this I need to manage SongUrl in FavoriteActivity and I am confused on this topic.
For example :
When we click Add to favorite in some apps and you can take example of Spotify in my app. I want to build same function and i provided my code below. So please if you have any answer regarding my question please answer me.
Here is my code :
My Adapter Class :
package com.geetmp3.GeetMp3.ArtistPanel;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.geetmp3.GeetMp3.R;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import xyz.hanks.library.bang.SmallBangView;
public class PanelAdapter extends RecyclerView.Adapter<PanelAdapter.PanelViewHolder> {
private Context mContext;
private List<PanelList> mUploads;
public PanelAdapter(Context context, List<PanelList> panelList) {
mContext = context;
mUploads = panelList;
}
#NonNull
#Override
public PanelViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.artist_recycler_layout, parent, false);
return new PanelViewHolder(v);
// Toast.makeText(mContext, "" + ge, Toast.LENGTH_SHORT).show();
}
#Override
public void onBindViewHolder(#NonNull PanelViewHolder holder, int position) {
PanelList panelList = mUploads.get(position);
holder.textViewName.setText(panelList.getSongName());
Glide.with(mContext)
.load(panelList.getSongImageUri())
.centerCrop()
.into(holder.circleImageView);
//
holder.bangView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.bangView.isSelected()) {
holder.bangView.setSelected(false);
// What can i do here
} else {
holder.bangView.setSelected(true);
holder.bangView.likeAnimation(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
Toast.makeText(mContext, mUploads.get(position).getSongName() + "Added to playlist", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class PanelViewHolder extends RecyclerView.ViewHolder {
private TextView textViewName;
private CircleImageView circleImageView;
private LinearLayout thisLayout;
private SmallBangView bangView;
public PanelViewHolder(#NonNull View itemView) {
super(itemView);
thisLayout = itemView.findViewById(R.id.artist_linear);
textViewName = itemView.findViewById(R.id.artist_song_name);
circleImageView = itemView.findViewById(R.id.artist_songs_image);
bangView = itemView.findViewById(R.id.bang_like_heart);
}
}
}
My getter and setter class:
public class PanelList {
private String SongName;
private String SongUrl;
private String SongImageUri;
private String SongLyrics;
private String SongMusicDirector;
private String SongProducer;
private String SongArtist;
public PanelList() {
}
public PanelList(String SongName, String SongUrl, String SongImageUri, String SongArtist, String SongLyrics, String SongMusicDirector, String SongProducer) {
this.SongName = SongName;
this.SongUrl = SongUrl;
this.SongImageUri = SongImageUri;
this.SongArtist = SongArtist;
this.SongLyrics = SongLyrics;
this.SongMusicDirector = SongMusicDirector;
this.SongProducer = SongProducer;
}
public String getSongArtist() {
return SongArtist;
}
public String getSongLyrics() {
return SongLyrics;
}
public String getSongMusicDirector() {
return SongMusicDirector;
}
public String getSongProducer() {
return SongProducer;
}
public String getSongName() {
return SongName;
}
public String getSongUrl() {
return SongUrl;
}
public String getSongImageUri() {
return SongImageUri;
}
}
My artist Activity :
public class ArtistActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ValueEventListener eventListener;
private DatabaseReference mDataRef, artist_ref;
private List<PanelList> mList;
private PanelAdapter panelAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.artist1layout);
mRecyclerView = findViewById(R.id.artist_song_recyclerview);
mDataRef = FirebaseDatabase.getInstance().getReference("ArtistView").child(getIntent().getStringExtra("Artist"))
.child("Songs");
mRecyclerView.setHasFixedSize(true);
mDataRef.keepSynced(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mList = new ArrayList<>();
panelAdapter = new PanelAdapter(ArtistActivity.this, mList);
mRecyclerView.setAdapter(panelAdapter);
eventListener = mDataRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mList.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
PanelList list = postSnapshot.getValue(PanelList.class);
mList.add(list);
}
panelAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
There is nothing in my FavoriteActivity except onCreate.
Don't pass the list in adapter if it is dynamic.
Add this function in your adapter
public void setPanelList(List<PanelList> panelList){
panelList = mList;
notifyDataSetChanged();
}
Modify your mDataRef.addValueEventListener
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mList.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
PanelList list = postSnapshot.getValue(PanelList.class);
mList.add(list);
}
panelAdapter.setPanelList(mList);
}
Hope this helps.
I currently have implemented RecyclerView, but my CarView does not show the data.
These are my current data in Firebase:
But the RecyclerView shows all three CardViews, but without the records:
These are the files I'm using:
DomiciliarySearchFragment.java
import android.os.Bundle;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.didierzuniga.domix.R;
import com.didierzuniga.domix.adapter.OrderAdapterRecyclerView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* A simple {#link Fragment} subclass.
*/
public class DomiciliarySearchFragment extends Fragment {
#Bind(R.id.recycler_order) RecyclerView recyclerView;
public DomiciliarySearchFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_domiciliary_search, container, false);
showToolbar(getResources().getString(R.string.tab_search), true, view);
ButterKnife.bind(this, view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
new GetDataFromFirebase().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// Read from the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("order");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
HashMap<String, String> values = (HashMap<String, String>) dataSnapshot.getValue();
recyclerView.setAdapter(new OrderAdapterRecyclerView(values));
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
System.out.println("Failed to read value." + error.toException());
}
});
return view;
}
private class GetDataFromFirebase extends AsyncTask<Void,Void,Boolean>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... voids) {
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
public void showToolbar(String tittle, boolean upButton, View view){
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(tittle);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(upButton);
}
}
OrderAdapterRecyclerView.java
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.didierzuniga.domix.R;
import java.util.HashMap;
import java.util.Map;
public class OrderAdapterRecyclerView extends RecyclerView.Adapter<OrderAdapterRecyclerView.ViewHolder>{
private HashMap<String, String> values;
public OrderAdapterRecyclerView(HashMap<String, String> values) {
this.values = values;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_order,parent,false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.fromm.setText(values.get(position));
holder.too.setText(values.get(position));
holder.moneyToPayy.setText(values.get(position));
}
#Override
public int getItemCount() {
return values.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView fromm;
private TextView too;
private TextView moneyToPayy;
ViewHolder(View itemView) {
super(itemView);
fromm = (TextView) itemView.findViewById(R.id.from);
too = (TextView) itemView.findViewById(R.id.to);
moneyToPayy = (TextView) itemView.findViewById(R.id.moneyToPay);
}
}
}
Model: Order.java
public class Order {
public String uid;
public String oFrom;
public String oTo;
public String oHeader;
public String oDescription;
public String oMoneyToPay;
public String oAuthor;
public boolean completed;
public Order(){
}
public Order(String oFrom, String oTo, String oHeader, String oDescription, String oMoneyToPay, String oAuthor) {
this.oFrom = oFrom;
this.oTo = oTo;
this.oHeader = oHeader;
this.oDescription = oDescription;
this.oMoneyToPay = oMoneyToPay;
this.oAuthor = oAuthor;
this.completed = false;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getoFrom() {
return oFrom;
}
public void setoFrom(String oFrom) {
this.oFrom = oFrom;
}
public String getoTo() {
return oTo;
}
public void setoTo(String oTo) {
this.oTo = oTo;
}
public String getoHeader() {
return oHeader;
}
public void setoHeader(String oHeader) {
this.oHeader = oHeader;
}
public String getoDescription() {
return oDescription;
}
public void setoDescription(String oDescription) {
this.oDescription = oDescription;
}
public String getoMoneyToPay() {
return oMoneyToPay;
}
public void setoMoneyToPay(String oMoneyToPay) {
this.oMoneyToPay = oMoneyToPay;
}
public String getoAuthor() {
return oAuthor;
}
public void setoAuthor(String oAuthor) {
this.oAuthor = oAuthor;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
}
¿What I need to do to be able to display the registers in each CardView?
Thank you!
In DomiciliarySearchFragment.java /onDataChange,
Can you confirm that hashmap has been correctly populated?
I had a similar problem, but the reason was that the data was not stored correctly in the collection
Thanks uguboz, I should have use dataSnapshot.getChildren(), and get all the records one by one in a loop
rv = (RecyclerView) view.findViewById(R.id.recycler_order);
rv.setLayoutManager(new LinearLayoutManager(getContext()));
orders = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
adapter = new OrderAdapter(orders);
rv.setAdapter(adapter);
database.getReference().child("order").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
orders.removeAll(orders);
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Order order = snapshot.getValue(Order.class);
orders.add(order);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Thank you everyone.