I'm trying to return the key and value from my Firebase Database and insert it into a RecycleView adapter but the values won't show up in the app.
I can't wrap my head around this whatsoever.
I tried to show the values in a Toast and it worked but why won't the values be inserted into the RecycleView adapter?
This is the code.
public class test extends AppCompatActivity {
TextView textView;
Button button;
String phone;
String n;
String a;
FirebaseAuth mAuth;
MyRecyclerViewAdapter adapter;
ArrayList<String> info;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Bundle b = new Bundle();
b = getIntent().getExtras();
phone = b.getString("number");
textView = findViewById(R.id.textV);
button = findViewById(R.id.signoutButton);
mAuth = FirebaseAuth.getInstance();
textView.setText(textView.getText().toString() + " as " + phone);
info = new ArrayList<>();
FirebaseDatabase myRef = FirebaseDatabase.getInstance();
DatabaseReference sRef = myRef.getReference("users");
sRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnap : dataSnapshot.getChildren()) {
if (childSnap.getKey().equals(phone)) {
for (DataSnapshot c : childSnap.getChildren()) {
n = c.getKey();
a = c.getValue().toString();
info.add(n);
info.add(a);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
RecyclerView recyclerView = findViewById(R.id.rvInfo);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, info);
adapter.setClickListener(new MyRecyclerViewAdapter.ItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(test.this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
});
recyclerView.setAdapter(adapter);
}
}
You can get this using following code
sRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnap : dataSnapshot.getChildren()) {
if (childSnap.getKey().equals(phone)) {
for (DataSnapshot c : childSnap.getChildren()) {
n = c.getKey();
a = c.getValue().toString();
info.add(n);
info.add(a);
}
}
}
notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
You have to add notifyDataSetChanged(); after you fill ArrayList from firebase. Because it's take time to load data from firebase. And your adapter initialised before fill ArrayList from firebase.
Related
In my firebase I have questions and their answers stored. Each answer has an id, which it got from push(). But I am unable to show the list of all the users who have answered the question. Please help.
Here is the code:
ListView listView;
ArrayList<String> answerers = new ArrayList<>();
ArrayAdapter arrayAdapter;
String askedBy, question, likes;
FirebaseAuth mAuth;
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_answers);
listView = findViewById(R.id.answersListView);
Intent intent = getIntent();
askedBy = intent.getStringExtra("askedBy");
question = intent.getStringExtra("question");
likes = intent.getStringExtra("numberOfLikes");
mAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("questions").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
if (dataSnapshot.child("question").getValue().toString().equals(question) && dataSnapshot.child("askedBy").getValue().toString().equals(askedBy)
&& dataSnapshot.child("likes").getValue().toString().equals(likes)) {
dataSnapshot.child("answers").getRef().addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshots) {
if (snapshots.exists()){
for (DataSnapshot dataSnapshots : snapshots.getChildren()){
String id = dataSnapshot.getRef().push().getKey();
answerers.add(dataSnapshots.child(id).child("answeredBy").getValue().toString());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
arrayAdapter = new ArrayAdapter<>(ViewAnswersActivity.this, android.R.layout.simple_list_item_1, answerers);
listView.setAdapter(arrayAdapter);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent1 = new Intent(ViewAnswersActivity.this, AnswerActivity.class);
intent1.putExtra("askedBy", askedBy);
intent1.putExtra("answeredBy", answerers.get(i));
intent1.putExtra("question", question);
intent1.putExtra("numberOfLikes", likes);
startActivity(intent1);
}
});
}
When I am running the app, the listView is coming empty, indicating value hasn't been stored.
Try to set adapter within onDataChange()
#Override
public void onDataChange(#NonNull DataSnapshot snapshots) {
if (snapshots.exists()){
for (DataSnapshot dataSnapshots : snapshots.getChildren()){
String id = dataSnapshot.getRef().push().getKey();
answerers.add(dataSnapshots.child(id).child("answeredBy").getValue().toString());
}
arrayAdapter = new ArrayAdapter<> (ViewAnswersActivity.this, android.R.layout.simple_list_item_1, answerers);
listView.setAdapter(arrayAdapter);
}
}
I have a problem clearing list in fragments. I need to clear the list when happening update in fragment. I already put it in different places but it does not help me.
When an update happens in fragment it shows the same list but that list also add elements from the previous list. If I put list.clear(); in the moment when it rakes arguments from firebase it did not give me needed effect, when I put it in onCreate() method then app gives me error.
public class Favourite extends Fragment {
private RecyclerView recyclerView;
private ArrayList<TourReader1> artistList;
private ToursAdapter1 adapter1;
private DatabaseReference reference,reference2;
String uid;
public Favourite() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
//Get current user id
uid = user.getUid();
//Connect to specific point in database Tours
reference = FirebaseDatabase.getInstance().getReference("Tours");
//Create add to method valuelistener or reference which is specific point in database
reference2 = FirebaseDatabase.getInstance().getReference("user").child(uid);
reference.addValueEventListener(valueEventListener);
reference.keepSynced(true);
}
ValueEventListener valueEventListener = (new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot1) {
//get all information from specific point of database
for (DataSnapshot datasnapshot : snapshot1.getChildren()) {
//get current name of starting point from where we recive information from database
String firstname = datasnapshot.getKey();
//valuelistener for another point from database
reference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dSnapshot2:snapshot.getChildren()){
String seconame = dSnapshot2.getKey();
Boolean control = dSnapshot2.child("like").getValue(Boolean.class);
if(control != null&&firstname.equals(seconame) &&control.equals(true)) {
TourReader1 artist = datasnapshot.getValue(TourReader1.class);
artistList.add(artist);
}
}
adapter1.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
artistList = new ArrayList<>();
View rootview = inflater.inflate(R.layout.favourite, container, false);
recyclerView = rootview.findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
adapter1 = new ToursAdapter1(getContext(), artistList);
recyclerView.setAdapter(adapter1);
GridLayoutManager mGridLayoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(mGridLayoutManager);
return rootview;
}
}
You should clear the artistList using artistList.clear() before your for loop in onDataChangeas this list is having the data from the last callback triggered.
Ok, I found the answer myself, I clear my list in the adapter by tourlist.clear() and remove userpoints.keepSynced(true); when like icon is false.
holder.sparkButton.setEventListener(new SparkEventListener() {
#Override
public void onEvent(ImageView button, boolean buttonState) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
DatabaseReference userpoints = FirebaseDatabase.getInstance().getReference("user").child(uid);
ToursLike registerDatabase = new ToursLike(true);
if(buttonState){
userpoints.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(tour.Name)) {
userpoints.child(tour.Name).setValue(registerDatabase);
userpoints.keepSynced(true);
tourList.clear();
}
else{
userpoints.child(tour.Name).child("like").setValue(true);
userpoints.keepSynced(true);
tourList.clear();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
else{
userpoints.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userpoints.child(tour.Name).child("like").setValue(false);
tourList.clear();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onEventAnimationEnd(ImageView button, boolean buttonState) {
}
#Override
public void onEventAnimationStart(ImageView button, boolean buttonState) {
}
});
}
Here is the image of my Firebase database setup:
I'm trying to program a simple notes application, I'm able to save everything to Firebase but struggling to retrieve the information.
A child of the user IDis randomly generated which is causing me issues when trying to retrieve the data. The below code is how im saving all the data to the Firebase database.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress_reports);
findViewById(R.id.saveNoteButton).setOnClickListener(saveReport);
progressReportTitle = findViewById(R.id.progressReportTitle);
progressReportContent = findViewById(R.id.progressReportContent);
fAuth = FirebaseAuth.getInstance();
fProgressReportsDatabase = FirebaseDatabase.getInstance().getReference().child("ProgressReports").child(fAuth.getCurrentUser().getUid());
findViewById(R.id.loadNoteButton).setOnClickListener(loadReports);
}
View.OnClickListener saveReport = new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = progressReportTitle.getText().toString().trim();
String content = progressReportContent.getText().toString().trim();
if (title.isEmpty()) {
progressReportTitle.setError("Please Enter a title for this report");
progressReportTitle.requestFocus();
} else if (content.isEmpty()) {
progressReportContent.setError("No content within report");
progressReportContent.requestFocus();
} else {
saveReportToDB(title, content);
}
}
};
private void saveReportToDB(String title, String content) {
if (fAuth.getCurrentUser() != null) {
final DatabaseReference newProgressReportRef = fProgressReportsDatabase.push();
final Map progressReportMap = new HashMap();
progressReportMap.put("title", title);
progressReportMap.put("content", content);
progressReportMap.put("timestamp", ServerValue.TIMESTAMP);
And below is how im attempting to load this data into a listview on a separate activity, with no luck,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
mListView = (findViewById(R.id.progressList));
fAuth = FirebaseAuth.getInstance();
fFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = FirebaseDatabase.getInstance().getReference().child("ProgressReports").child(fAuth.getCurrentUser().getUid());;
FirebaseUser user = fAuth.getCurrentUser();
userID = user.getUid();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showData(DataSnapshot dataSnapshot){
for(DataSnapshot ds : dataSnapshot.getChildren()){
ReportInformation rInfo = new ReportInformation();
rInfo.setTitle(ds.child(userID).child("title").getValue(ReportInformation.class).getTitle());
rInfo.setContent(ds.child(userID).child("content").getValue(ReportInformation.class).getContent());
//rInfo.setTimestamp(ds.child(userID).child("timestamp").getValue().toString());
ArrayList<String> array = new ArrayList<>();
array.add(rInfo.getTitle());
array.add(rInfo.getContent());
//array.add(rInfo.getTimestamp());
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array);
mListView.setAdapter(adapter);
}
}
What am I doing wrong, and how can I query the database for the HashMap which is randomly generated?
Thanks guys
To display all titles of all those objects in a ListView, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("ProgressReports").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String title = ds.child("title").getValue(String.class);
list.add(title);
Log.d("TAG", title);
}
ListView listView = (ListView) findViewById(R.id.list_view);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
Your list will contain two titles:
Test
Test
More information here if you want to use a model class.
I'm building a simple chat application. In user fragment, if we click on user it get crashed and go to previous activity if there is previous chat. While there is no chat with that user fragment works fine, but when we type message and click send message store on Firebase and app crashes, similarly if there is chat, chat fragment get crashed.
I think problem is in mReference.addValueEventListener(new ValueEventListener()) method. Code and error is given below. I saw other answers but didn't understand with my code.
MessageActivity.java
public class MessageActivity extends AppCompatActivity {
CircleImageView profile_image;
TextView username;
FirebaseUser mFirebaseUser;
DatabaseReference mDatabaseReference;
ImageView btn_send;
EditText send_msg;
Intent mIntent;
MessageAdapter mMessageAdapter;
List<Chat> mChats;
RecyclerView mRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
profile_image = findViewById(R.id.profile_image);
username = findViewById(R.id.username);
btn_send = findViewById(R.id.img_btn_send);
send_msg = findViewById(R.id.text_send);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
mIntent = getIntent();
final String userid = mIntent.getStringExtra("userid");
mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
btn_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = send_msg.getText().toString();
if (!msg.equals("")){
sendMessage(mFirebaseUser.getUid(), userid, msg);
}
send_msg.setText("");
}
});
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
assert user != null;
username.setText(user.getUsername());
if ( user.getImageURL().equals("default")){
profile_image.setImageResource(R.mipmap.ic_launcher_round);
}else {
Glide.with(MessageActivity.this).load(user.getImageURL()).into(profile_image);
}
readMessage(mFirebaseUser.getUid(), userid, user.getImageURL());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendMessage(String sender, String receiver, String message){
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("message", message);
mDatabaseReference.child("Chats").setValue(hashMap);
}
private void readMessage(final String myId, final String userID, final String imageURL){
mChats = new ArrayList<>();
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Chats");
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mChats.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
Chat chat = dataSnapshot1.getValue(Chat.class);
assert chat != null;
if (chat.getReceiver().equals(myId) && chat.getSender().equals(userID) || chat.getReceiver().equals(userID) && chat.getSender().equals(myId)){
mChats.add(chat);
}
mMessageAdapter = new MessageAdapter(MessageActivity.this, mChats, imageURL);
mRecyclerView.setAdapter(mMessageAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
ChatsFragment.java
public class ChatsFragment extends Fragment {
private RecyclerView mRecyclerView;
private UserAdapter mUserAdapter;
private List<User> mUsers;
FirebaseUser fUser;
DatabaseReference mReference;
private List<String> userList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chats, container, false);
mRecyclerView = view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
fUser = FirebaseAuth.getInstance().getCurrentUser();
userList = new ArrayList<>();
mReference = FirebaseDatabase.getInstance().getReference("Chats");
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userList.clear();
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (chat.getSender().equals(fUser.getUid())){
userList.add(chat.getReceiver());
}
if (chat.getReceiver().equals(fUser.getUid())){
userList.add(chat.getSender());
}
}
readChats();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
private void readChats() {
mUsers = new ArrayList<>();
mReference = FirebaseDatabase.getInstance().getReference("Users");
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUsers.clear();
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
for (String id : userList){
if (user.getId().equals(id)){
if (mUsers.size() != 0){
for ( User user1 : mUsers){
if ( !user.getId().equals(user1.getId()));
mUsers.add(user);
}
}
else{
mUsers.add(user);
}
}
}
}
mUserAdapter = new UserAdapter(getContext(), mUsers);
mRecyclerView.setAdapter(mUserAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Error is :
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database##16.0.4:423)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database##16.0.4:214)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database##16.0.4:79)
at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database##16.0.4:212)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##16.0.4:55)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6228)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
Ok so I have made a CardView hold one database item(in this case a football player) and adapted it in a RecyclerView.
My Firebase Database looks like this:
Players:
|---Goalkeepers:
|--GoalkeeperName
|--(And some other data fields)
|---Defenders:
|---Midfielders:
|---Attackers
My database reference looks like this:
playersDatabase = FirebaseDatabase.getInstance().getReference("Players").child("Goalkeepers");
If I leave the reference as ("Players"), it will give me 4 empty fields representing the Goalkeeper, Defenders, Midfielders and Attackers branch.
How do I display all data from all Position branches such as Goalkeeper, Defenders, Midfielders and Attackers?
Also is there any way of displaying all the players in an organised way with headings in my layout so it looks like this?
Goalkeepers(heading)
Goalkeeper1
Goalkeeper2
Defenders (heading)
Defender1
Defender2
This is the code from the actual app:
public class PlayerList extends AppCompatActivity {
private RecyclerView mPlayerList;
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference playersRef = rootRef.child("Players");
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_squad_list);
//playersDatabase = FirebaseDatabase.getInstance().getReference("Players").child("Goalkeepers");
playersRef.keepSynced(true);
//new code
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String typeOfPlayer = ds.getKey();
Log.d("TAG", typeOfPlayer);
for(DataSnapshot dSnapshot : dataSnapshot.child(typeOfPlayer).getChildren()) {
String player = dSnapshot.getKey();
Log.d("TAG", " " + player);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
playersRef.addListenerForSingleValueEvent(valueEventListener);
mPlayerList = (RecyclerView) findViewById(R.id.my_recycle_view);
mPlayerList.setHasFixedSize(true);
mPlayerList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Player, PlayerViewHolder>firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Player, PlayerViewHolder>(Player.class, R.layout.player_row, PlayerViewHolder.class, playersRef) {
#Override
protected void populateViewHolder(PlayerViewHolder viewHolder, Player model, int position) {
viewHolder.setPlayerName(model.getPlayerName());
viewHolder.setPlayerSurname(model.getPlayerSurname());
viewHolder.setPlayerPosition(model.getPlayerPosition());
}
};
mPlayerList.setAdapter(firebaseRecyclerAdapter);
}
public static class PlayerViewHolder extends RecyclerView.ViewHolder{
View mView;
public PlayerViewHolder(View itemView){
super(itemView);
mView = itemView;
}
public void setPlayerName (String playerName){
TextView textViewName = (TextView) mView.findViewById(R.id.textViewName);
textViewName.setText(playerName);
}
public void setPlayerSurname (String playerSurname){
TextView textViewName = (TextView) mView.findViewById(R.id.textViewSurname);
textViewName.setText(playerSurname);
}
public void setPlayerPosition (String playerPosition){
TextView textViewName = (TextView) mView.findViewById(R.id.textViewPosition);
textViewName.setText(playerPosition);
}
}
}
Any help is appreciated. Thanks
To display those players accordingly to the following database structure:
Goalkeepers
Goalkeeper1
Goalkeeper2
Defenders
Defender1
Defender2
Please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference playersRef = rootRef.child("Players");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String typeOfPlayer = ds.getKey();
Log.d("TAG", typeOfPlayer);
DatabaseReference playerRef = playersRef.child(typeOfPlayer);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
String player = dSnapshot.getKey();
Log.d("TAG", " " + player);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
playerRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
playersRef.addListenerForSingleValueEvent(valueEventListener);
Edit:
According to your edited post, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference playersRef = rootRef.child("Players");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String typeOfPlayer = ds.getKey();
Log.d("TAG", typeOfPlayer);
for(DataSnapshot dSnapshot : dataSnapshot.child(typeOfPlayer).getChildren()) {
String player = dSnapshot.getKey();
Log.d("TAG", " " + player);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
playersRef.addListenerForSingleValueEvent(valueEventListener);
Your result must be:
Attackers
Defenders
Goalkeepers
Goalkeeper1
Midfielders
Try this code ..
private void readData(){
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("Players").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String typeOfPlayer = ds.getKey();
Log.d("TAG", typeOfPlayer);
for(DataSnapshot dSnapshot : dataSnapshot.child(typeOfPlayer).getChildren()) {
String player = dSnapshot.getKey();
Log.d("TAG", " " + player);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
and i hope add internet permission into manifest file..
more information refer this link
https://www.simplifiedcoding.net/firebase-realtime-database-crud/