Search code examples
javaandroidfirebasefirebase-realtime-databaseandroid-listview

In array it is storing NULL instead of PDF file name


public class cp extends AppCompatActivity {

    ListView ListPdf;
    DatabaseReference databaseReference;
    List<upload> uploadPdf;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cp);

        ListPdf = (ListView) findViewById(R.id.List);
        uploadPdf = new ArrayList<>();
        ViewAllPdf();
    }

    private void ViewAllPdf() {
        databaseReference = FirebaseDatabase.getInstance().getReference("year_1");
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for(DataSnapshot PostSnapShot: dataSnapshot.getChildren()){

                    upload Pdf = PostSnapShot.getValue(upload.class);
                    uploadPdf.add(Pdf);

                }

                String[] uploads = new String[uploadPdf.size()];
                for(int i=0;i<uploads.length;i++){
                    uploads[i] = uploadPdf.get(i).getName();
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,uploads);
                ListPdf.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }


}

upload class

public class upload {

    public String name;

    public upload() {

        this.name = name;
    }



    public String getName() {
        return name;
    }
}

In uploads[ ] it is storing null instead of file name,i cannot figure out what's the problem. I tried logcat for debuging but it shows Pdf object has three files but in uploads[ ] it stores NULL. Please look into it

Firebase database screenshot

enter image description here


Solution

  • The problem with your code is your POJO class Upload. See an example from Firebase Documentation

    
    public class User {
    
        public String username;
        public String email;
    
        public User() {
            // Default constructor required for calls to DataSnapshot.getValue(User.class)
        }
    
        public User(String username, String email) {
            this.username = username;
            this.email = email;
        }
    
    }
    
    

    Also the fields name in your Realtime Database doesn't match with your POJO class.