Not getting Firebase database data - java

I am developing app to display user score that store in firebase database but after running application it won't display data in listview
below is my code:-
listViewLeaderBoard = (ListView) findViewById(R.id.listView_leader_board);
reference = FirebaseDatabase.getInstance().getReference("score");
leaderBoards = new ArrayList<>();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
LeaderBoard leaderBoard = postSnapshot.getValue(LeaderBoard.class);
leaderBoards.add(0,leaderBoard);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Collections.sort(leaderBoards);
CustomLeaderBoardAdapter adapter = new CustomLeaderBoardAdapter(getApplicationContext(),R.layout.leader_board_list_layout,leaderBoards);
listViewLeaderBoard.setAdapter(adapter);
adapter.notifyDataSetChanged();
Database snapshot:-
Output:-

try this:
listViewLeaderBoard = (ListView) findViewById(R.id.listView_leader_board);
reference = FirebaseDatabase.getInstance().getReference("score");
leaderBoards = new ArrayList<>();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
LeaderBoard leaderBoard = postSnapshot.getValue(LeaderBoard.class);
leaderBoards.add(leaderBoard);
CustomLeaderBoardAdapter adapter = new CustomLeaderBoardAdapter(getApplicationContext(),R.layout.leader_board_list_layout,leaderBoards);
listViewLeaderBoard.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

To solve this, move this line of code:
List<LeaderBoard> leaderBoards = new ArrayList<>();
inside onDataChange() method, otherwise it will always be, due the asynchronous behaviour of this method which is called even before you are trying to add those objects of LeaderBoard class to the list.
Also, leaderBoards.clear(); is no needed anymore. Your code should look something like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference scoreRef = rootRef.child("score");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String imageUrl = ds.child("imageUrl").getValue(String.class);
String name = ds.child("name").getValue(String.class);
long score = ds.child("score").getValue(Long.class);
Log.d("TAG", image + " / " + Urlname + " / " + score);
list.add(image + " / " + Urlname + " / " + score);
}
Log.d("TAG", list);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
scoreRef.addListenerForSingleValueEvent(eventListener);

You can find and change the rules for your database in the Firebase console.Simply choose your project, click on the Database section on the left, and then select the Rules tab.I don't know you have done this or not try this hope this will help you.
{
"rules": {
".read": true,
".write": true
}
}

Related

Retrieve specific value from Firebase database into string variable

I'm trying to retrieve a specific value from a Firebase realtime Database.
The data looks like this:
I want to get the URL value from any of them and then put it into a string variable to use later. This is so that the program does not need to be changed if the download link is changed. The code I have so far is;
DatabaseReference fdb = FirebaseDatabase.getInstance().getReference();
//Query query = fdb.child("URLDOWNLOADS").child("WSSeasons")
fdb.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot url : dataSnapshot.getChildren())
{
LoginInfoFirebasedb DownURL = url.getValue(LoginInfoFirebasedb.class);
String temp = DownURL.dwldURL;
URL1 = temp;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
Some help would be seriously appreciated. I understand this may be a simple problem but I am stumped.
To get each url as a String, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("URLDOWNLOADS");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
String url = ds.child("URL").getValue(String.class);
Log.d(TAG, key + " / " + url);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
ref.addListenerForSingleValueEvent(valueEventListener);

Retriving multiple entries from Firebase

Hi everyone. i am trying to retrieve the ids under 01-Nov-2018 and 02-Nov-2018 but I am unable to do so. I have tried this question but unable to get the data. My Code is:
ListView listView;
ArrayList<String> list = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReferenceFromUrl("https://myapplication-340c0.firebaseio.com/").child("Teacher").child("batch 1").child("C7-Advanced Java");//.child("02-Nov-2018");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_data);
listView = findViewById(R.id.list);
myRef.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
collectPhoneNumbers((Map<String, Object>) dataSnapshot.getValue());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void collectPhoneNumbers(Map<String,Object> users) {
ArrayList phoneNumbers = new ArrayList<>();
//iterate through each user, ignoring their UID
for (Map.Entry<String, Object> entry : users.entrySet()){
//Get user map
Map singleUser = (Map) entry.getValue();
//Get phone field and append to list
phoneNumbers.add( singleUser.get("02-Nov-2018").toString());
}
Log.d("data from db",phoneNumbers.toString());
//listView.setAdapter(adapter);
System.out.println(phoneNumbers.toString());
}
there is an error at Log.d
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.example.root.connieapp.ViewData.collectPhoneNumbers(ViewData.java:57)
at com.example.root.connieapp.ViewData.access$000(ViewData.java:19)
at com.example.root.connieapp.ViewData$1.onDataChange(ViewData.java:33)
i have to add more values in firebase and there would be many of them. how can i get many values ??
Please help me to overcome this issue.
I have reused the code but didn't rename variables. please don't mind that.. thanks
To solve this, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("Teacher").child("batch 1").child("C7-Advanced Java");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String date = ds.getKey();
String code = ds.child("Code").getValue(String.class);
String fams = ds.child("fams").getValue(String.class);
String jams = ds.child("jams").getValue(String.class);
Log.d(TAG, date + " / " + code + " / " + fams + " / " + jams);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
ref.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be:
01-Nov-2018 / jam /p / p
02-Nov-2018 / sam /p / p

How to show datas on a ListView when it has multiple child in Firebase database as shownin picture

So please look at the problem iam facing.
Assuming that the SuccessfulOrders node is a direct child of your Firebase database root, to get that data and add it into a list, please use the following code:
String phoneNo = FirebaseAuth.getInstance().getCurrentUser().getPhoneNumber();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference phoneNoRef = rootRef.child("SuccessfulOrders").child(phoneNo);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ListView<String> list = new ArrayList<>();
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
String productName = ds.child("productName").getValue(String.class);
list.add(productName);
Log.d("TAG", productName);
}
//Do what you need to do with your list.
Log.d("TAG", list.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
phoneNoRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logat wil be:
1000 Website Visit
SOCIAL MEDIA PACK
//and so on

How can I read the two value down a child?

Here is my database reference:
I want to read the two key's value(reminddate and title) and show on the listview.How can I do it?
Metodolist.java
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference hom = database.getReference("Student").child(student_id).child("event");
listview = findViewById(R.id.listview);
final ArrayAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,android.R.id.text1);
listview.setAdapter(adapter);
hom.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot event : dataSnapshot.getChildren() ) {
Event = event.getValue().toString();
Log.e("Metodolist",Event);
adapter.add(Event);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.e("MeTo list","Pass1");
This is how can be done:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference eventRef = rootRef.child("Student").child(student_id).child("event");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String reminddate = ds.child("reminddate").getValue(String.class);
String title = ds.child("title").getValue(String.class);
Log.d("TAG", reminddate + " / " + title);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
eventRef.addListenerForSingleValueEvent(eventListener);
The output will be:
22-02-18 / A
23-02-18 / B

How to retrieve full List Of Objects from Firebase that contains another List of String in it?

I have stored some List of person objects on Firebase.I want to retrieve this full List into newList of person from database.The class perosn contains another List batch
My class person look like:
public class person {
public String name,sid;
public HashMap<String,String> batch;
public int cls;
}
The code I have used is:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference fDatabaseRoot = database.getReference("studentsList");
fDatabaseRoot.orderByChild("name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot areaSnapshot : dataSnapshot.getChildren()) {
Map<String,person> td =
(HashMap<String,person>)areaSnapshot.getValue();
// arrayListStudent= (List<person>) td.values();
// Log.d("aaa1",arrayListStudent.toString());
}
//Log.d("aaa",arrayListStudent.toString());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Where am i getting wrong.Please give some hint and suggestions....
Here is the screenshot of my database structure:
Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference studentsListRef = rootRef.child("studentsList");
Query query = studentsListRef.orderByChild("name");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
String key1 = ds.child("batch").child("0").getValue(String.class);
String key2 = ds.child("batch").child("1").getValue(String.class);
Log.d("TAG", name + " / " + key1 + " / " + key2);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(eventListener);
In this way, you'll get the value of name and of both fields under batch.

Categories

Resources