Home > Back-end >  firebase to listview android studio
firebase to listview android studio

Time:11-04

This is my database and I wanna retrieve a data (which is underline in red color) from firebase to Listview .

This is the picture of my XML code

This is the my java code:

public class TimeTableActivity extends AppCompatActivity {

    ListView table01;
    DatabaseReference Trainline;
    ArrayList<String> arrayList= new ArrayList<>();
    ArrayAdapter<String> arrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_table);
        Trainline= FirebaseDatabase.getInstance().getReference("Time_table");
        table01 = findViewById(R.id.table01);
        arrayAdapter = new ArrayAdapter<String>( TimeTableActivity.this, android.R.layout.simple_list_item_1);
        table01.setAdapter(arrayAdapter);

        Trainline.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {    
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {    
            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot snapshot) {    
            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {    
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {    
            }
        });    
    }    
}

CodePudding user response:

In the onChildAdded you can:

  1. Read the value from the snapshot
  2. Add it to the list that the adapter is based on
  3. Tell the adapter to refresh itself

In code:

arrayAdapter = new ArrayAdapter<String>(TimeTableActivity.this, 
                                        android.R.layout.simple_list_item_1, arrayList);
                                                                          //            
  • Related