要将GPS位置存储在Firebase实时数据库中

时间:2018-11-03 02:47:12

标签: java android firebase firebase-realtime-database

我需要将自己的位置存储到Firebase实时数据库中。以下代码有效,并且仅在Android应用中显示位置。如何将此位置发送到Firebase?

public class MainActivity extends AppCompatActivity {

    Button button;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        textView = (TextView) findViewById(R.id.textView);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {              //check for sdk version
           if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {
               if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
                       != PackageManager.PERMISSION_GRANTED && checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)
                       != PackageManager.PERMISSION_GRANTED) {

                   requestPermissions(new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, 1000);
               }else{
                   LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                   Location location = locationManager  .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                   try{
                       String city = hereLocation(location.getLatitude(), location.getLongitude());
                       textView.setText(city);

                   }catch (Exception e)
                   { e.printStackTrace();
                       Toast.makeText(MainActivity.this,"Not found!",Toast.LENGTH_LONG).show();
                   }
               }
           }

            }
        });


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        switch (requestCode){  //set the text value
            case 1000:{
                if(grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    String city = hereLocation(location.getLatitude(),location.getLongitude());
                    textView.setText(city);
                }else{
                    Toast.makeText(this,"permission is granted!",Toast.LENGTH_LONG).show();
                }
                break;
            }
        }
    }

    private String hereLocation(double lat, double lon){  //access geo location
       String cityName = "";

        Geocoder geocoder= new Geocoder(this ,Locale.getDefault());
        List<Address> addresses;
        try{
            addresses = geocoder.getFromLocation(lat,lon, 10);
            if(addresses.size()> 0){
                for(Address adr:addresses) {

                    if (adr.getLocality() != null && adr.getLocality() .length()> 0) {

                        cityName = adr.getLocality();
                        break;

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

       return cityName;
    }
}

城市名称使用文本视图进行存储。它将提供设备所在的当前城市。我需要将此位置发送到Firebase实时数据库。

1 个答案:

答案 0 :(得分:0)

您可以使用Firebase数据库和DatabaseReference类将位置发送到Firebase。首先,您必须确保在build.gradle中具有以下SDK:

implementation 'com.google.firebase:firebase-storage:16.0.4'
implementation 'com.google.firebase:firebase-database:16.0.4'

此外,请确保已在Firebase控制台中设置了实时数据库。最好选择“测试”选项,以便任何人都可以写入数据库。如果您以前从未使用过Firebase,请check out this documentation by Firebase to setup Firebase in your Android app.

在依赖中添加代码后,请执行以下操作:

FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = firebaseDatabase.getReference("Locations"); 
//Instead of "Locations" you can say something else. Locations will be the name of your path where the location is stored.
//Create a Hashmap to store the information with a key and a value:
Hashmap<String, String> values = new Hashmap<>();
values.put("Location", city);
databaseReference.push().setValue(values);

您可以添加onSuccessListener或onFailureListener来查看其是否有效。 如果不起作用,请查看此doc by Firebase

相关问题