-2

This is my firebase data using Split method i try to separate lat/lan value stored in Firebase, but only first value show but second value cannot get.error occured and stop run.String lat=gpsVal[0] can assign but String lang=gpsVal1 cannot assign.app close. but when i add manual value lat/lng: (7.714195099999999,81.6947587)" to example variable then can assign both value(String lat=gpsVal[0],lang=gpsVal1) to variable

This my code:

final ArrayList <String> locationnew = new ArrayList <String>();
    database.orderByChild("ItemName").equalTo(name).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot){
                    for(DataSnapshot suggestionSnapshot : dataSnapshot.getChildren())
                    {
                         itcat=suggestionSnapshot.getKey();
                         String loc=suggestionSnapshot.child("ShopLocation").getValue().toString();
                         names1.add(itcat);
                         locationnew.add(loc);

                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                   // Toast.makeText(getApplicationContext(), "AWW SNAP... Something is Wrong.", Toast.LENGTH_LONG).show();
                }
            });

        String[] loca=new String[1000];

        for(int i=0; i < locationnew.size(); i++)
        {
            loca[i]=locationnew.get(i);
        }

        String find_lat_lan = "";
        serch2.setText(String.valueOf(loca[0]));
        String example = serch2.getText().toString();
        Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(example);
        while(m.find()) {
            find_lat_lan = m.group(1) ;
        }

        String[] gpsVal = find_lat_lan.split(",");
        String lat=gpsVal[0];
        String lang=gpsVal[1];
Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

2

This is happening because you are trying to use the locationnew list outside the onDataChange() which will always be empty due the asynchronous behaviour of this method.

With other words, you cannot return something now that hasn't been loaded yet. You cannot simply use that result outside the onDataChange() method because by the time you are trying to use that list outside the method, the data hasn't finished loading yet from the database and that's why is not accessible. A quick solve for this problem would be to move all your logic only inside the onDataChange() method like this:

    final ArrayList <String> locationnew = new ArrayList <String>();
    database.orderByChild("ItemName").equalTo(name).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot){
            for(DataSnapshot suggestionSnapshot : dataSnapshot.getChildren())
            {
                itcat=suggestionSnapshot.getKey();
                String loc=suggestionSnapshot.child("ShopLocation").getValue().toString();
                names1.add(itcat);
                locationnew.add(loc);

            }
            String[] loca=new String[1000];

            for(int i=0; i < locationnew.size(); i++)
            {
                loca[i]=locationnew.get(i);
            }

            String find_lat_lan = "";
            serch2.setText(String.valueOf(loca[0]));
            String example = serch2.getText().toString();
            Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(example);
            while(m.find()) {
                find_lat_lan = m.group(1) ;
            }

            String[] gpsVal = find_lat_lan.split(",");
            String lat=gpsVal[0];
            String lang=gpsVal[1];
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

            // Toast.makeText(getApplicationContext(), "AWW SNAP... Something is Wrong.", Toast.LENGTH_LONG).show();
        }
    });

Or if you want to use it outside the method, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
1

add it seperatly

 private void subscribeToUpdates() {
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference(getString(R.string.firebase_path));

    ref.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
            setMarker(dataSnapshot);
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
            setMarker(dataSnapshot);
            Log.d("markerKey", "hello: " + dataSnapshot.getKey());
            String key = dataSnapshot.getKey();
//                subscribeUpdates(key);
        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
        }

        @Override
        public void onCancelled(DatabaseError error) {
            Log.d(TAG, "Failed to read value.", error.toException());
        }
    });
}

private void setMarker(DataSnapshot dataSnapshot) {
    // When a location update is received, put or update
    // its value in mMarkers, which contains all the markers
    // for locations received, so that we can build the
    // boundaries required to show them all on the map at once
    String key = dataSnapshot.getKey();
// not important
    newName = key.replace(" ", ".");
    HashMap<String, Object> value = (HashMap<String, Object>) dataSnapshot.getValue();
    double lat = Double.parseDouble(value.get("latitude").toString());
    double lng = Double.parseDouble(value.get("longitude").toString());
    LatLng location = new LatLng(lat, lng);
    if (!mMarkers.containsKey(key)) {
        mMarkers.put(key, mMap.addMarker(new MarkerOptions().title(newName).position(location)
                .icon(BitmapDescriptorFactory.defaultMarker(colours[new Random().nextInt(colours.length)]))));
    } else {
        mMarkers.get(key).setPosition(location);
    }

    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    for (Marker marker : mMarkers.values()) {
        builder.include(marker.getPosition());
    }
    mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 300));
}

and receive it like this on map

  • using google api auto complete method i add location to database.in my code if i print (find_lat_lan) it show 7.714195099999999,81.6947587 but error occurred separate this from comma – S.B.S.Kaushalya May 23 '18 at 11:31
  • find_lat_lan = m.group(1) ; giving you string ??? without error ? because if this is null of course you will get error –  May 23 '18 at 11:38