我一直在尝试将状态系统添加到我的Android项目中。我在网上找到了一个完全符合该想法的教程,并使系统的一部分正常工作。
我已经完成了本教程:https://youtu.be/17HqLBkuX-E
第2部分:https://youtu.be/eYk-gokOyA8
第3部分:https://youtu.be/mbDcdul_fdk
用户身份验证与用户加入和退出“状态”页面的功能一起起作用。
我的代码存在的问题是我在以下行收到错误:
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
mLastLocation = locations;
displayLocation();
}
我收到以下错误:
不兼容的类型。必需:android.location.Location找到: com.google.firebase.database.DatabaseReference
在将字段“位置”更改为android.location.Location之后。我在另一行收到错误:
locations = FirebaseDatabase.getInstance().getReference("Presence Location");
说明如下:
不兼容的类型。必需:android.location.Location找到: com.google.firebase.database.DatabaseReference
点击Alt + Enter此处时,系统会提示我将字段位置更改为com.google.firebase.database.DatabaseReference。但是,这使我回到了前面提到的错误。
我将在下面显示页面代码的完整内容。我希望我提供的上下文可能对选择帮助我解决此错误的人有用。
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
//import android.location.LocationListener;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.aladdin.FitHub2019Project.R;
import com.aladdin.FitHub2019Project.models.User;
import com.aladdin.FitHub2019Project.services.LocationService;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.internal.bind.MapTypeAdapterFactory;
import com.google.android.gms.location.LocationListener;
public class OnlineList extends AppCompatActivity implements GoogleApiClient
.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener {
//firebase
DatabaseReference onlineRef;
DatabaseReference currentUserRef;
DatabaseReference counterRef;
Location locations;
FirebaseRecyclerAdapter<UserRace,OnlineListViewHolder> adapter;
//RecyclerView
RecyclerView onlineList;
RecyclerView.LayoutManager layoutManager;
//Location
private static final int MY_PERMISSION_REQUEST_CODE = 7171;
private static final int PLAY_SERVICES_RES_REQUEST = 7172;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private static int UPDATE_INTERVAL = 5000;
private static int FASTEST_INTERVAL = 3000;
private static int DISTANCE = 10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_online_list);
//Init view
onlineList = (RecyclerView)findViewById(R.id.onlineList);
onlineList.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
onlineList.setLayoutManager(layoutManager);
// set toolbar and logout functionality / allowing ability to join via menu
// Toolbar toolbar = (Toolbar)findViewById(R.id.toolBar);
// toolbar.setTitle("Race Presence System");
// setSupportActionBar(toolbar);
//Firebase Connect
locations = FirebaseDatabase.getInstance().getReference("Presence Location");
onlineRef = FirebaseDatabase.getInstance().getReference().child(".info/connected");
counterRef = FirebaseDatabase.getInstance().getReference("lastOnline");//creating a new child name lastOnline
currentUserRef = FirebaseDatabase.getInstance().getReference("lastOnline")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()); //Creating a new child in lastOnline with the key Uid
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
}, MY_PERMISSION_REQUEST_CODE);
}
else
{
if(checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
displayLocation();
}
}
setupSystem();
//After setting up the system, users are added from counterRef and display on the RecyclerView
//online list
updateList();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch(requestCode)
{
case MY_PERMISSION_REQUEST_CODE:
{
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if(checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
displayLocation();
}
}
}
break;
}
}
private void displayLocation() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
{
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null)
{
//Update to firebase
locations.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(new Tracking(FirebaseAuth.getInstance().getCurrentUser().getEmail(),
FirebaseAuth.getInstance().getCurrentUser().getUid(),
String.valueOf(mLastLocation.getLatitude()),
String.valueOf(mLastLocation.getLongitude())));
}
else
{
// Toast.makeText(this, "Couldn't get the location ", Toast.LENGTH_SHORT).show();
Log.d("TEST", "Couldn't load location");
}
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setSmallestDisplacement(DISTANCE);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resultCode != ConnectionResult.SUCCESS)
{
if(GooglePlayServicesUtil.isUserRecoverableError(resultCode))
{
GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERVICES_RES_REQUEST).show();
}
else
{
Toast.makeText(this, "This device is not supported", Toast.LENGTH_SHORT).show();
finish();
}
return false;
}
return true;
}
//*ALADDIN*Update FirebaseUI to newest version <-- older version of firebase ui code
private void updateList() {
FirebaseRecyclerOptions<UserRace> userOptions = new FirebaseRecyclerOptions.Builder<UserRace>()
.setQuery(counterRef,UserRace.class)
.build();
adapter = new FirebaseRecyclerAdapter<UserRace, OnlineListViewHolder>(userOptions) {
@Override
protected void onBindViewHolder(@NonNull OnlineListViewHolder viewHolder, int position, @NonNull final UserRace model) {
if(model.getEmail().equals(FirebaseAuth.getInstance().getCurrentUser().getEmail()))
viewHolder.txtEmail.setText(model.getEmail()+ " (me)");
else
viewHolder.txtEmail.setText(model.getEmail());
//implement item click recycler view
viewHolder.itemClickListener = new ItemClickListener() {
@Override
public void onClick(View view, int position) {
if(!model.getEmail().equals(FirebaseAuth.getInstance().getCurrentUser().getEmail()))
{
Intent map = new Intent(OnlineList.this, MapsTracking.class);
map.putExtra("email",model.getEmail());
map.putExtra("lat",mLastLocation.getLatitude());
map.putExtra("lng",mLastLocation.getLongitude());
startActivity(map);
}
}
};
}
@NonNull
@Override
public OnlineListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
View itemView = LayoutInflater.from(getBaseContext())
.inflate(R.layout.user_layout, parent, false);
return new OnlineListViewHolder(itemView);
}
};
adapter.startListening();
onlineList.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
//setting up system
private void setupSystem() {
onlineRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue(Boolean.class))
{
currentUserRef.onDisconnect().removeValue(); //delete older value
//setting online user in list
counterRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(new UserRace(FirebaseAuth.getInstance().getCurrentUser().getEmail(),
"Online"));
adapter.notifyDataSetChanged();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
counterRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
UserRace userRace = postSnapshot.getValue(UserRace.class); //*ALADDIN* - Check For error on this line if issue
Log.d("LOG", ""+userRace.getEmail()+" is "+userRace.getStatus());
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu_race,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.action_join:
counterRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(new UserRace(FirebaseAuth.getInstance().getCurrentUser()
.getEmail(),"Online"));
break;
case R.id.action_logout:
currentUserRef.removeValue();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
displayLocation();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
displayLocation();
startLocationUpdates();
}
private void startLocationUpdates() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
{
return;
}
// LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
}
@Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
@Override
protected void onStart() {
super.onStart();
if(mGoogleApiClient != null)
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
if(mGoogleApiClient != null)
mGoogleApiClient.disconnect();
if(adapter != null)
adapter.stopListening();
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
checkPlayServices();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
mLastLocation = locations;
displayLocation();
}
}
如果需要我提供任何其他信息,我会提供。
所有帮助将不胜感激。