Retriving multiple entries from Firebase - java

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

Related

Firebase Realtime Database not displayed when retriving to textviews in Android

onCreate() method is never executed. I just want to take the below data to 4 TextViews. "Detail" is the model class.
No errors are shown when running the app.
view_temp is an activity.
this is firebase realtime db
this is the java class
`public class view_temp extends AppCompatActivity {
private view_temp viewTemp;
public Detail detail;
private TextView roomtemp, roomhuminity, bodypulse, bodytemp;
private DatabaseReference mDatabase;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_temp);
mDatabase = FirebaseDatabase.getInstance().getReference("heat-stroke-device");
roomtemp = (TextView) findViewById(R.id.txt_room_temp);
roomhuminity = (TextView) findViewById(R.id.txt_huminity_temp);
bodypulse = (TextView) findViewById(R.id.txt_body_pulse);
bodytemp = (TextView) findViewById(R.id.txt_body_temp);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
detail = postSnapshot.getValue(Detail.class);
String rtemp = detail.getRoomtemp();
String rhumidity = detail.getRoomhumidity();
String bpulse = detail.getBodypulse();
String btemp = detail.getBodytemp();
roomtemp.setText(rtemp);
roomhuminity.setText(rhumidity);
bodypulse.setText(bpulse);
bodytemp.setText(btemp);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getMessage());
}
});
}
}`
There is no need to add the name of the project in the getReference() method. To get those names and the corresponding values correctly, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.getKey();
double value = ds.getValue(Double.class);
Log.d("TAG", name "/" + value);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
rootRef.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be:
RoomHumi/86.0
RoomTemp/30.8
bodyPulse/126.0
bodyTemp/29.0
If the keys are always fixed, then simply use:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double roomHumi = dataSnapshot.child("RoomHumi").getValue(Double.class);
Log.d("TAG", "RoomHumi" "/" + valueroomHumi);
double roomTemp = dataSnapshot.child("RoomTemp").getValue(Double.class);
Log.d("TAG", "RoomTemp" "/" + roomTemp);
double bodyPulse = dataSnapshot.child("bodyPulse").getValue(Double.class);
Log.d("TAG", "bodyPulse" "/" + bodyPulse);
double bodyTemp = dataSnapshot.child("bodyTemp").getValue(Double.class);
Log.d("TAG", "bodyTemp" "/" + bodyTemp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
rootRef.addListenerForSingleValueEvent(valueEventListener);
And you'll have the same result in the logcat.
Just change your line
mDatabase = FirebaseDatabase.getInstance().getReference("heat-stroke-device");
to
mDatabase = FirebaseDatabase.getInstance().getReference();
Note: You do not need to put your database name into reference.

Firebase - Unable to read data on application interface - Android Studio

I am developing a task management application on Android Studio with Firebase. I have created a class to add data to the database but I have tried multiple approaches to integrate and read the data on the application with no progress.
Main Activity.java
database = FirebaseDatabase.getInstance();
ref = database.getReference().child("Task List");
final ArrayList<String> mTaskName = new ArrayList<>();
taskListView = (ListView) findViewById(R.id.taskListView);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.task_info, mTaskName);
taskListView.setAdapter(arrayAdapter);
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String value = dataSnapshot.getValue(String.class);
mTaskName.add(value);
arrayAdapter.notifyDataSetChanged();
}
add_task.java
mDatabase = FirebaseDatabase.getInstance().getReference().child("Task List"); // Reference database
addTaskbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String taskName = newTask.getText().toString().trim();
String date = dateField.getText().toString().trim();
String assignee = spinnerAssign.getSelectedItem().toString();
String descrip = description.getText().toString();
if (!TextUtils.isEmpty(taskName) && !TextUtils.isEmpty(date)) {
HashMap<String, String> taskData = new HashMap<>();
taskData.put("Name", taskName);
taskData.put("Date", date);
taskData.put("Assigned to", assignee);
taskData.put("Description", descrip);
mDatabase.push().setValue(taskData).addOnCompleteListener(new OnCompleteListener<Void>() {
The database is structured like this:
task-list-for-managers
-Task List
-PushID
-Assigned to: "Name"
-Date: "Date"
-Description: "Description"
-Name: "Task Name"
ValueEventListener eventListener = new ValueEventListener() {
//Searching the database and adding each to list
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
//adding the key to an arraylist to be referenced when deleting records or passing intents from specific button
mTaskName.add(ds.getKey());
String name = ds.child("Name").getValue(String.class);
String date = ds.child("Date").getValue(String.class);
id.add(name + "\n" + date);
Log.d("TAG", name);
}
taskListView.setAdapter(arrayAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
database.addListenerForSingleValueEvent(eventListener);

How do I get the id of an element from firebase

//database
database = FirebaseDatabase.getInstance();
foods = database.getReference("Food/" + categoryID);
I need categoryID. How can I retrieve it?
To get the id, try the following:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Food");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The snapshot is at child Food then you can iterate inside the direct child and get the id which is 01
I have found a solution. like this;
categoryID = getIntent().getStringExtra("CategoryID");
foodId = getIntent().getStringExtra("FoodId");
database = FirebaseDataBase.getInstance();
foods = database.getReference("Food/" + categoryID + "/" + foodId);
with this method I could reach both food and category ID.

Not getting Firebase database data

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
}
}

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