我想在用户点击按钮时向Firebase发送位置更新

时间:2017-07-03 17:38:35

标签: android firebase firebase-realtime-database firebase-authentication

我想在用户点击按钮时向Firebase发送位置更新。更新设置为每3秒发送一次位置更改。但问题是它无法发送错误

Process: com.example.parthtiwari.trace, PID: 7423
                                                                         java.lang.NullPointerException: Attempt to invoke virtual method 'void android.location.LocationManager.requestLocationUpdates(java.lang.String, long, float, android.location.LocationListener)' on a null object reference

这是我的代码

 import android.Manifest;
 import android.content.Context;
import android.content.Intent;

 public class gpdfuel extends AppCompatActivity {

private Button btn;
private Button start;
private FirebaseAuth fb;
private FirebaseAuth.AuthStateListener fbListener;
private DatabaseReference databaseReference;
private String userID;
LocationManager loc;
LocationListener lic;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gpdfuel);
    start = (Button) findViewById(R.id.start);

    fb = FirebaseAuth.getInstance();
    databaseReference = FirebaseDatabase.getInstance().getReference();
    FirebaseUser user = fb.getCurrentUser();

    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //noinspection MissingPermission
            loc.requestLocationUpdates("gps", 5000, 0, lic);
        }
    });

    lic = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            FirebaseUser user = fb.getCurrentUser();
            databaseReference.child(user.getUid()).push().setValue(location.getLatitude() + ",   " + location.getLongitude());
        }

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

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {
            Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(i);
        }
    };

}

1 个答案:

答案 0 :(得分:1)

初始化LocationManager loc;的位置?它永远不会根据你的代码进行初始化,这就是为什么你得到空指针异常。