2
    public class Hospitals extends AppCompatActivity {

        private DatabaseReference mDatabase;
        private String []hospitals;
        private String []links;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_hospitals);
            mDatabase= FirebaseDatabase.getInstance().getReference().child("Hospitals");
            mDatabase.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    String total=dataSnapshot.child("total").getValue().toString();
                    hospitals=new String[Integer.parseInt(total)];
                    links=new String[Integer.parseInt(total)];
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
            Toast.makeText(Hospitals.this,String.valueOf(hospitals.length),Toast.LENGTH_LONG).show();
}

This is the database and i want to extract the value 2 stored in key "total":

image

All the dependencies are set up correctly and other database related operations are working fine.

Lee Mac
  • 15,615
  • 6
  • 32
  • 80

1 Answers1

1

To solve this, change this line of code:

String total=dataSnapshot.child("total").getValue().toString();

with

int total=dataSnapshot.child("total").getValue(Integer.class);

The problem in your code is that you are usig to get the data from the database, the String class while the data is stored as an integer.

Edit:

According to your comment, your Toast doesn't work in that place, because onDataChange() method has an asynchronous behaviour which means that by the time you are trying to toast that message, the data is not loaded yet from the database. A quick solve for this problem would be to use that Toast only inside the onDataChange() method or if you want to use it outside, you need to create your own callback and for that, I recommend you see the last part of my answer from this post.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • If you want to use it further as a String, just use: `String.valueOf(total)` – Alex Mamo Feb 17 '18 at 13:18
  • it didn't help,and it was expected because when i put the Toast inside the onDataChange {} body,it works perfectly fine.so,it has something to do with the scope of the variable because if the toast inside function body works,it means that the hospitals variable was initialized but it was a different copy of hospitals which vanished as the method ends. – Aryan Kashyap Feb 17 '18 at 13:54