Lat / Lng值分别存储在firebase中,分配给变量

时间:2018-05-23 11:06:12

标签: java android firebase arraylist firebase-realtime-database

This is my firebase data使用Split方法我尝试分离存储在Firebase中的lat/lan值,但只显示第一个值,但第二个值无法get.error发生并停止run.String lat = gpsVal [0]可以assign但String lang = gpsVal 1无法assign.app关闭。 但是当我将手动值lat / lng :( 7.714195099999999,81.6947587)添加到示例变量时,则可以将值(String lat = gpsVal [0],lang = gpsVal 1)分配给变量

这是我的代码:

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];

2 个答案:

答案 0 :(得分:2)

这种情况正在发生,因为您尝试使用locationnew之外的onDataChange()列表,由于此方法的异步行为,该列表始终为empty

换句话说,您现在还无法返回尚未加载的内容。您不能简单地在onDataChange()方法之外使用该结果,因为当您尝试在方法之外使用list时,数据尚未从数据库中完成加载,这就是无法访问的原因。快速解决此问题的方法是仅在onDataChange()方法中移动所有逻辑,如下所示:

    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();
        }
    });

或者如果您想在方法之外使用它,我建议您从 post 中查看我的anwser的最后一部分,其中我已经解释了如何使用自定义回调。您还可以查看此 video ,以便更好地理解。

答案 1 :(得分:1)

单独添加

 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));
}

并在地图上像这样接收