简体   繁体   中英

Why does my ArrayList show size of zero when logged from main method but shows a size of a certain number when called from internal method?

I am creating a Vending Machine program using firebase where everytime a value is updated in the firebase it gets extracted to class "NewUt" and gets added to the ArrayList "allLocations".I have Log.d() in the onCreate method that prints the size of the array and another Log.d() in the onDataChange method when the data is updated. The Log.d() in the onCreate shows that the Array has a size of 0 but the Log.d() in the onDataChange method shows a size more than zero. What could be the problem?

I have tried to put the onDataChange inside a different method but still same results.

package com.xeon.vendingmachine;

import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Camera;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MapsActivity extends FragmentActivity implements 
OnMapReadyCallback {

private GoogleMap mMap;
DatabaseReference myRef;
private static ArrayList<Utilities> allLocations = new ArrayList<>();




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    FirebaseApp.initializeApp(this);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    myRef = FirebaseDatabase.getInstance().getReference("Vending Machines");
    Random r = new Random();
    Double randLat = r.nextDouble()*100;
    Double randLon = r.nextDouble()*100;
   Utilities utilitiesForDatabase = new Utilities(randLat,randLon,"Carol Machifne","Carfol","Layfs","Ffull");
     String uid = myRef.push().getKey();
     myRef.child(uid).setValue(utilitiesForDatabase);
    String TAG  = "RefFromMain";
   myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            allLocations.clear();

            for (DataSnapshot allLocs : dataSnapshot.getChildren()) {
                Utilities newUt = allLocs.getValue(Utilities.class);
                allLocations.add(newUt);
            }


            Log.d("ArraySize" , "Size is " + allLocations.size());
            Log.d("LatLng" , " New Lattitude : " + allLocations.get(allLocations.size()-1).getLattitude() + " Longitude : " + allLocations.get(allLocations.size()-1).getLongitude());
             NotificationCompat.Builder mBuilderArray =
                    new NotificationCompat.Builder(getApplicationContext())
                            .setContentTitle("New location added")
                            .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
                            .setContentText("Size is " + allLocations.size());

            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(1,mBuilderArray.build());

        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.e("Database Error", "The data could not be extracted");
        }
    });
    Log.d(TAG , "Size is " + this.allLocations.size());

}


@Override
public void onMapReady(GoogleMap googleMap) {

    mMap = googleMap;



}


}

Log.d() in the onCreate method.

D/RefFromMain: Size is 0
D/RefFromMain: Size is 0
D/RefFromMain: Size is 0
D/RefFromMain: Size is 0

Log.d() in the onDataChange method.

D/ArraySize: Size is 4
D/ArraySize: Size is 5
D/ArraySize: Size is 6
D/ArraySize: Size is 10
 allLocations = new ArrayList<>();
 Log.d(TAG , "Size is " + allLocations.size());

There's nothing in it yet. Its size is therefore zero.

Later you put something in it:

          allLocations.add(newUt);
        }
        Log.d("ArraySize" , "Size is " + allLocations.size());

Now its size has increased (by some number of elements depending on the immediately-preceding for-loop)

You logged the array size in main after allocation. So it is 0. But in onDataChange you have put data in that array with allLocations.add(newUt); . So it is showing the size equal to the number of data inserted in it.

At first you are initialling your Arraylist. here

 allLocations = new ArrayList<>();
    Log.d(TAG , "Size is " + allLocations.size());

So it initialling with empty data . there's nothing in it . After that in addValueEventListener you are adding data to your allLocations ArrayList.

 myRef.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            allLocations.clear();
            for (DataSnapshot allLocs : dataSnapshot.getChildren()) {
                Utilities newUt = allLocs.getValue(Utilities.class);
              allLocations.add(newUt);
            }

So now it has values in it .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM