I want to read the data from firebasedatabase and show that into recyclerview retrieve data form FirebaseDatabase by orderbychild method. I want to read data of that child who's email match with my useremail who is currently login from app .
This is my Firebase:
I have successfully completed the first part, but I am facing problems with second part how can I pass the retrieved data to recyclerview adapter.
For example whenever user login from mobeen#gmail.com I read his location and ticket_no and show that data into recyclerview. I am facing problem with this line
programinglist.setAdapter(new myadapter(this, modl1));
where should I pass my modl1 (ArrayList<model> modl1) to recyclerview.setadapter
public class recyclierview extends AppCompatActivity {
public RecyclerView programinglist;
DatabaseReference b1, b2;
public ArrayList<model> modl1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recyclierview);
programinglist = findViewById(R.id.my_recycler_view);
programinglist.setLayoutManager(new LinearLayoutManager(this));
modl1 =new ArrayList<model>();
readdata(new firebasecallback() {
#Override
public void oncallback(ArrayList<model> list) {
Log.v("aliraza" , "value oncalback" + list.get(0).getTicket_no());
}
});
}
private void readdata(final firebasecallback firebasecallback)
{
b1= FirebaseDatabase.getInstance().getReference();
b2=b1.child("tasks");
b2.orderByChild("email").equalTo(MainActivity.email).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
model m = new model();
String location = dataSnapshot.child("location").getValue().toString();
String tickeno = dataSnapshot.child("ticket_no").getValue().toString();
Log.v("ALI", "family value " +location);
Log.v("ALI", "family value " + tickeno);
m.setLocation(location);
Log.v("ALI", "location " +m.getLocation());
m.setTicket_no(tickeno);
modl1.add(m);
Log.v("ALI", "family value " +modl1.get(0).getTicket_no());
firebasecallback.oncallback(modl1);
}
#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) {
}
});
programinglist.setAdapter(new myadapter(this, modl1));// where should i call this setadapter function of recyclierview.enter code here
}
private interface firebasecallback
{
void oncallback( ArrayList<model> list);
}
}
Initialise your arraylist and adapter;
public ArrayList<model> modl1=new ArrayList();
private myadapter adapter;
In onCreate() method initialize your adapter with blank list and set adapter to recyclerview.
adapter=new myadapter(this, modl1);
programinglist.setAdapter(adapter);
then create a method addItem() in your adapter.
public void addItem(model item){
list.add(item); // add item to your adapter list
notifyItemInserted(list.size());
}
changes in onChildAdded() method
modl1.add(m); //remove this line
firebasecallback.oncallback(m);
readdata(new firebasecallback() {
#Override
public void oncallback(model m) {
modl1.add(m);
adapter.add(m);
Log.v("aliraza" , "value oncalback" + list.get(0).getTicket_no());
}
});
You can remove firebasecallback method,as there is no need of it, and directly add item to adapter in onChildAdded() method. Simply call readdata() method from onCreate()
private void readdata()
{
b1= FirebaseDatabase.getInstance().getReference();
b2=b1.child("tasks");
b2.orderByChild("email").equalTo(MainActivity.email).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
model m = new model();
String location = dataSnapshot.child("location").getValue().toString();
String tickeno = dataSnapshot.child("ticket_no").getValue().toString();
Log.v("ALI", "family value " +location);
Log.v("ALI", "family value " + tickeno);
m.setLocation(location);
Log.v("ALI", "location " +m.getLocation());
m.setTicket_no(tickeno);
modl1.add(m);
Log.v("ALI", "family value " +modl1.get(0).getTicket_no());
adapter.add(m);
}
#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) {
}
});
}
Hope this will help!!
Related
As I know the ChildEventListener is the only way to detect that data in Firebase Realtime Database was deleted. That's why I extend LiveData to handle the events of ChildEventListener.
public class UserRatingsLiveData extends LiveData<DataSnapshot> {
private static final String LOG_TAG = "UserRatingsLiveData";
private final Query query;
private final UserRatingsChildEventListener listener = new UserRatingsChildEventListener();
public UserRatingsLiveData(DatabaseReference ref) {
this.query = ref;
}
#Override
protected void onActive() {
Log.d(LOG_TAG, "onActive");
query.addChildEventListener(listener);
}
#Override
protected void onInactive() {
Log.d(LOG_TAG, "onInactive");
query.removeEventListener(listener);
}
private class UserRatingsChildEventListener implements ChildEventListener {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
setValue(dataSnapshot);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
setValue(dataSnapshot);
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
// What to do here to signale that the element was removed?
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(LOG_TAG, "entering onCancelled(...)");
}
}
}
Delegating newly created elements in onChildAdded(...) with setValue(dataSnapshot) is straight forward. But what's with signaling that an element was removed?
Should I use a special LiveData object only for the remove event?
Any other idea?
I need help. Here i have load the hospital name from firebase to spinner how i want to getItemAtposition because when i click on hospital name it has to seleceted and clicked on getDirection button in my application so it will reload to the google map and mark on particular hospital which is selected so now how can do in my java code, but i know missing something but cant find me please help me out
Thanks in advance
Java code
//init Db
hospitalRef = FirebaseDatabase.getInstance().getReference("hospital");
//init interface
iFirebaseLoaddone = this;
hospitalRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Hospital> hospital = new ArrayList<>();
for (DataSnapshot hospitalsnapshot : dataSnapshot.getChildren()) {
hospital.add(hospitalsnapshot.getValue(Hospital.class));
}
iFirebaseLoaddone.onFirebaseLoadSuccess(hospital);
}
#Override
public void onCancelled(DatabaseError databaseError) {
iFirebaseLoaddone.onFirebaseLoadFailed(databaseError.getMessage());
}
});
searchableSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String seleceted =parent.getItemAtPosition(position).toString();
Log.e("clicked",""+ seleceted);
hospitalRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
setMarker(dataSnapshot);
// Comment comment = dataSnapshot.getValue(Comment.class);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
setMarker(dataSnapshot);
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
#Override
public void onFirebaseLoadSuccess(List<Hospital> hospitalList) {
hospitals = hospitalList;
//get all data
List<String> id = new ArrayList<>();
List<String> name_list = new ArrayList<>();
List<Double> latitude = new ArrayList<>();
List<Double> longitude = new ArrayList<>();
for (Hospital hospital : hospitalList)
// id.add(hospital.getId());
name_list.add(hospital.getName());
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, name_list);
searchableSpinner.setAdapter(adapter);
}
You can get selected value from spinner as below,
String seleceted =parent.getItemAtPosition(position).toString(); //your code
String selected = name_list.get(position); //another way to get selected name
You can get latitude and longitude from spinner - hospital name from firebase DB.
Query query = reference.orderByChild("name").equalTo(seleceted);
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
double latitude = dataSnapshot.child("latitude").getValue();
double longitude = dataSnapshot.child("longitude").getValue();
setMarker(latitude,longitude);
}
#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) {
}
});
public void readUniversity(){
ChildEventListener uniListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//Log.d(LOG_TAG, dataSnapshot.getKey());
University uni = dataSnapshot.getValue(University.class);
universitieslist.add(uni); //Adding to an ArrayList of type University
//Log.d(LOG_TAG, universitieslist.size()+"is the size");
arrayofUniversities.add(uni.getName()); //Adding name of University to list
//Log.d(LOG_TAG, adapter.getCount() + " items");
//Log.d(LOG_TAG, arrayofUniversities.size()+" is the size");
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
DatabaseReference uniReference = database.getReference("note-retrieve/Universities");
uniReference.addChildEventListener(uniListener);
}
The code is pretty much self explanatory. I am using arrayofUniversities a list to populate a spinner so I need an adapter. I am populating the spinner with the names of the Universities
I am storing the University Objects in universitieslist
The problem I have is when I leave the readUniversity() method I lose every element in universitieslist and arrayofUniversities even though my spinner is populated with these.
Its very strange as the list should have the objects stored.
Also, I have my adapter at the very top of the code in onCreate().
Try this way. Hope it will work .. :)
private Arrylist<University > universityList = new ArryList<>();
private Arrylist<String> universitysName = new ArryList<>();
mDatabase.getReference().child("path")
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null) {
University mUniversity = dataSnapshot.getValue(University
.class);
universityList.add(mUniversity);
universitysName.add(mUniversity.getName);
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The problem seems to be with the adapter, if you can see the logs but the adapter is not updating, then is because the adapter is not being notified the data set has changed
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null) {
University mUniversity = dataSnapshot.getValue(University
.class);
universityList.add(mUniversity);
universitysName.add(mUniversity.getName);
//UPDATE YOUR ADAPTER HERE
//spinnerAdapter.notifyDataSetChanged();
}
}
But I think the real problem is the origin of your current problem: You are getting each child. This is a way to do it, but for this case where you need all the data first and when that is ready show the spinner with the elements to the user, you should better get all the list elements in one query.
database.getReference("note-retrieve/Universities")..addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
University mUniversity = dataSnapshot.getValue(University
.class);
universityList.add(mUniversity);
universitysName.add(mUniversity.getName);
//ONCE THIS IS DONE, THEN PASS THE ARRAY TO THE ADAPTER
}
//The loop here is over, so you can set the adapter with the full list of data/universities
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
i need to get all data in Childs and show it in ListView
Every Values in Childs!,The main Child is "XXX-Users" and other Childs is about "Model Phones",, i want get All Date of This Childs on ListView
this is my Activity:
public class xxxxxxx extends AppCompatActivity {ListView listView;
ArrayList<String> usernames = new ArrayList<>() ;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("xxx-Users");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xxxxxxxxxxxxx);
listView = (ListView) findViewById(R.id.listview00);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,usernames);
listView.setAdapter(arrayAdapter);
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.getValue(String.class);
usernames.add(value);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}`**
My Layout
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:id="#+id/listview00" />
As cricket_007 said, your code doesn't match your data structure. Your listener will fire for the nodes immediately under xxx-Users. But your actual URL values are one level deeper.
One simple way to handler this is to loop over those nested children in onChildAdded():
DatabaseReference myRef = database.getReference("xxx-Users");
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String value = childSnapshot.getValue(String.class);
usernames.add(value);
}
arrayAdapter.notifyDataSetChanged();
}
...
In android I am simply add some values in listview from firebase now I data pair like:
I am using array list for adding this items on my adapter by the help of ChildEventListener, Here is my class :
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView listView;
ArrayList<String> arr = new ArrayList<>(10);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
final Firebase myFirebaseRef = new Firebase("https://f.......firebaseio.com/");
myFirebaseRef.child("Donors").child("Baldia Town").child("Ittehad Town").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
System.out.println(dataSnapshot.getKey() + " was " + dataSnapshot.getValue());
Log.d("obj", dataSnapshot.getKey() + " , " + dataSnapshot.getValue());
arr.add(dataSnapshot.getKey());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
listView = (ListView) findViewById(R.id.lvDonnors);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,arr);
arrayAdapter.notifyDataSetChanged();
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView text = (TextView) view;
Toast.makeText(this, text.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
Note: by this I simply get the Log :
Faizan: 2341
Hussain: 1345
Khezar: 2233
Zeeshan: 1122
but I want to add the name only in "arr" (list) . and when user press "zeeshan" I simply get its id (datasnapshot.getValue)like 1122 in any variable.
Can anyone help me to do this??