Java 我正在编写一个位置共享应用程序,实时显示用户的位置,但我';我应该使用firebase与其他用户共享

Java 我正在编写一个位置共享应用程序,实时显示用户的位置,但我';我应该使用firebase与其他用户共享,java,android,firebase,real-time,Java,Android,Firebase,Real Time,我能够获得用户的位置,但我不知道如何将其上传到firebase,然后与其他用户实时共享 public class MapsActivityy extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; LocationManager locationManager; @Override protected void onCreate(Bundle savedInstanceState) {

我能够获得用户的位置,但我不知道如何将其上传到firebase,然后与其他用户实时共享

public class MapsActivityy extends FragmentActivity implements  OnMapReadyCallback {

private GoogleMap mMap;
LocationManager locationManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps_activityy);
    // 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);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    //Permission to view el location
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                 int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    //check lw el network provider enabled
    //example vodafone or wi-fi
    if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                //bngeeb el actual location
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                // latlng el location 3la el map
                LatLng latLng = new LatLng(latitude,longitude);
                //initalize class geocoder te3ml convert mn el lat wl lng to an address
                Geocoder geocoder = new Geocoder(getApplicationContext());
                try {
                    // 3shan n7ot el address fe list w max el results 1
                    List<Address> addressList= geocoder.getFromLocation(latitude,longitude,1);
                    String string  = addressList.get(0).getCountryName()+" , ";
                    string +=addressList.get(0).getLocality()+" , ";
                    string +=addressList.get(0).getSubLocality();
                    //Hy7ot marker 3l location
                    mMap.addMarker(new MarkerOptions().position(latLng).title(string));
                    //3shan n3ml zoom 3l location
                    // el second val hwa amount of zoom
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,15.2f));

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {
            }
            @Override
            public void onProviderEnabled(String s) {
            }
            @Override
            public void onProviderDisabled(String s) {
            }
        });
    }
    //Satellite
    else if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                    //bngeeb el actual location
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    // latlng el location 3la el map
                    LatLng latLng = new LatLng(latitude,longitude);
                    //initalize class geocoder te3ml convert mn el lat wl lng to an address
                    Geocoder geocoder = new Geocoder(getApplicationContext());
                    try {
                        // 3shan n7ot el address fe list w max el results 1
                        List<Address> addressList= geocoder.getFromLocation(latitude,longitude,1);
                        String string  = addressList.get(0).getCountryName()+" , ";
                        string +=addressList.get(0).getLocality()+" , ";
                        //if available hygeeb subLoc if not hyb3t null
                       string +=addressList.get(0).getSubLocality();
                        //Hy7ot marker 3l location
                        mMap.addMarker(new MarkerOptions().position(latLng).title(string));
                        //3shan n3ml zoom 3l location
                        // el second val hwa amount of zoom
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,15.2f));

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }


            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

            }
        });

    }
}


/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
 /*  LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/

}
}
公共类MapsActivityy在MapReadyCallback上扩展了FragmentActivity实现{
私有谷歌地图;
地点经理地点经理;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u maps\u activityy);
//获取SupportMapFragment,并在地图准备好使用时收到通知。
SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
getMapAsync(这个);
locationManager=(locationManager)getSystemService(位置服务);
//查看el位置的权限
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予和&ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u LOCATION)!=PackageManager.permission\u已授予){
考虑到呼叫
//ActivityCompat#请求权限
//在此处请求缺少的权限,然后覆盖
//public void onRequestPermissionsResult(int-requestCode,字符串[]权限,
//int[]格兰特结果)
//处理用户授予权限的情况。请参阅文档
//对于ActivityCompat,请请求权限以获取更多详细信息。
回来
}
//检查lw el网络提供程序是否已启用
//沃达丰或wi-fi示例
if(locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER)){
locationManager.RequestLocationUpdate(locationManager.NETWORK_提供程序,0,0,新LocationListener(){
@凌驾
已更改位置上的公共无效(位置){
//实际位置
双纬度=location.getLatitude();
double longitude=location.getLongitude();
//latlng el位置3la el地图
LatLng LatLng=新LatLng(纬度、经度);
//初始化类地理编码器te3ml将mn el lat wl lng转换为地址
Geocoder Geocoder=新的Geocoder(getApplicationContext());
试一试{
//3山n7ot el地址fe列表w最大el结果1
List addressList=geocoder.getFromLocation(纬度、经度,1);
String String=addressList.get(0).getCountryName()+“,”;
字符串+=addressList.get(0.GetLocation()+”,”;
string+=addressList.get(0.getSubLocality();
//Hy7ot标记3l位置
mMap.addMarker(新的MarkerOptions().position(latLng.title)(字符串));
//3shan n3ml缩放3l位置
//el second val hwa缩放量
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,15.2f));
}捕获(IOE异常){
e、 printStackTrace();
}
}
@凌驾
状态已更改的公共void(字符串s、int i、Bundle){
}
@凌驾
已提供已启用的公共void(字符串s){
}
@凌驾
公共无效onProviderDisabled(字符串s){
}
});
}
//卫星
else if(locationManager.isProviderEnabled(locationManager.GPS\U提供程序)){
locationManager.RequestLocationUpdate(locationManager.GPS_提供程序,0,0,新LocationListener(){
@凌驾
已更改位置上的公共无效(位置){
//实际位置
双纬度=location.getLatitude();
double longitude=location.getLongitude();
//latlng el位置3la el地图
LatLng LatLng=新LatLng(纬度、经度);
//初始化类地理编码器te3ml将mn el lat wl lng转换为地址
Geocoder Geocoder=新的Geocoder(getApplicationContext());
试一试{
//3山n7ot el地址fe列表w最大el结果1
List addressList=geocoder.getFromLocation(纬度、经度,1);
String String=addressList.get(0).getCountryName()+“,”;
字符串+=addressList.get(0.GetLocation()+”,”;
//如果可用,hygeeb subLoc如果不是hyb3t null
string+=addressList.get(0.getSubLocality();
//Hy7ot标记3l位置
mMap.addMarker(新的MarkerOptions().position(latLng.title)(字符串));
//3shan n3ml缩放3l位置
//el second val hwa缩放量
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,15.2f));
}捕获(IOE异常){
e、 printStackTrace();
}
}
@凌驾
状态已更改的公共void(字符串s、int i、Bundle){
}
@凌驾
已提供已启用的公共void(字符串s){
}
@凌驾
公共无效onProviderDisabled(字符串s){
}
});
}
}
/**
*一旦可用,就可以操纵贴图。
*当映射准备好使用时,将触发此回调。
*这是我们可以添加标记或线条、添加侦听器或移动摄影机的地方。在这种情况下,
*我们只是在澳大利亚悉尼附近加了一个标记。
*如果设备上未安装Google Play服务,系统将提示用户安装
private DatabaseReference ref;
private FirebaseDatabase minstance;

minstance = FirebaseDatabase.getInstance();
ref = instac.getReference("userData");
Address address = new Address(location, countryname, locality, sublocality);
//as you have a custom arraylist, i hope you already have constructors with the same argument you need to pass data, and getter setter method of all the data variable you need to store in database.

ref.child(String.valueOf(userId)).setValue(address);
//Here the userId works like Primarykey to your database.

ref.child(String.valueOf(userId)).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            Address address = dataSnapshot.getValue(Address.class);
    }
@Override
        public void onCancelled(DatabaseError databaseError) {

            Log.d(TAG, "Failed To Write Data", databaseError.toException());

        }
    });
Arraylist<Long> alllocation; //ARRAY LIST TO STORE RETRIEVED DATA
Arraylist<String> allcountry;
Arraylist<String> alllocality;
Arraylist<String> allsublocality;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("userData");
 ref.addListenerForSingleValueEvent(
        new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                //Get map of users in datasnapshot
                collectUserData((Map<String,Object>) dataSnapshot.getValue());
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                //handle databaseError
            }
        });
private void collectUserData(Map<String,Object> users) {

alllocation = new Arraylist<Long>;
allcountry = new Arraylist<String>;
alllocality = new Arraylist<String>;
allsublocality = new Arraylist<String>;

//iterate through each user, ignoring their UID
for (Map.Entry<String, Object> entry : users.entrySet()){

    //Get user map
    Map singleUser = (Map) entry.getValue();
    //Get data choosing their field and append to list
    alllocation.add((Long) singleUser.get("location"));
    allcountry.add((String) singleUser.get("country"));
    alllocality.add((String) singleUser.get("locality"));
    allsublocality.add((String) singleUser.get("sublocality"));
   }
}