如果Firebase中没有内容,则显示警报对话框

时间:2018-10-18 15:51:08

标签: android firebase firebase-realtime-database

我有一个应用程序,该应用程序获取用户位置并将其发送到我的Firebase数据库,该数据库具有最接近用户的位置列表。位置半径已设置为小于50km(50000m)。如果在该半径范围内没有位置,我希望显示一个警告对话框,提示没有可用位置。位置将随着应用程序的运行而更新。每次用户尝试访问设置半径内的位置时,都应显示警报对话框。有人可以帮我解决这个问题吗?任何帮助将不胜感激。

LActivity

public class LActivity extends AppCompatActivity implements
    LocationListener,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

private static final String TAG = "Location1";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;

public Location mCurrentLocation;
String mLastUpdateTime;
ViewPager viewPager;

ProgressDialog progressdialog;

protected void createLocationRequest() {
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setInterval(INTERVAL);
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    progressdialog = new ProgressDialog(this);
    progressdialog.setMessage("Pending");

    Runnable progressRunnable = new Runnable() {
        @Override
        public void run() {
            progressdialog.cancel();
        }
    };

    Handler pdcanceller = new Handler();
    pdcanceller.postDelayed(progressRunnable,1500);
    progressdialog.show();



    createLocationRequest();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    setContentView(R.layout.activity_rape_location);

    viewPager = (ViewPager) findViewById(R.id.viewpagerL);
    viewPager.setAdapter(new RapeLocationPageAdapter(getSupportFragmentManager(),
            LActivity.this));


}

public void getLocation(View view) {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 501);
    } else {
        mGoogleApiClient.connect();
    }

    progressdialog.show();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 501) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            mGoogleApiClient.connect();
        } else {
            Toast.makeText(this, "Location permission denied. Please grant location permission to the app.", Toast.LENGTH_SHORT).show();
        }
    }
}

@Override
public void onStart() {
    super.onStart();
    Log.d(TAG, "onStart fired ..............");
    mGoogleApiClient.connect();
    progressdialog.show();

}

@Override
public void onStop() {
    super.onStop();
    Log.d(TAG, "onStop fired ..............");
    mGoogleApiClient.disconnect();
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    startLocationUpdates();
}

protected void startLocationUpdates() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED)
    {
        final AlertDialog builder = new AlertDialog.Builder(this).create();
        builder.setMessage("Location has not been granted");
        builder.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                builder.dismiss();
            }
        });

        builder.show();
        return;
    }


    PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, mLocationRequest, this);
    Log.d(TAG, "Location update started ..............: ");
    progressdialog.show();


}



@Override
public void onConnectionSuspended(int i) {


}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    final AlertDialog builder = new AlertDialog.Builder(this).create();
    builder.setMessage("If there are no locations near you, please contact the local police for immediate attention");
    builder.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            builder.dismiss();
        }
    });

    builder.show();

}

@Override
public void onLocationChanged(Location location) {
    mCurrentLocation = location;


     RapeLocation rapeLocation = (RapeLocation) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewpagerRape + ":" + viewPager.getCurrentItem());
     rapeLocation.update(mCurrentLocation);



        }
}

LActivityMain

public class LActivityMain extends Fragment {

RecyclerView recyclerView;
LocationsAdapter locationsAdapter;
ArrayList<LocationModel> locationModelArrayList = new ArrayList<LocationModel>();
ArrayList<LocationModel> filteredlocationModelArrayList = new ArrayList<LocationModel>();
protected DatabaseReference mDatabase;
LActivityMain locationActivityfin;
Button bnt1;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.activity_locationmain, container, false);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    locationActivityfin = (LActivityMain) getActivity();
    mDatabase = FirebaseDatabase.getInstance().getReference();
    recyclerView = view.findViewById(R.id.rvLocations);
    bnt1 = view.findViewById(R.id.locdone);
    bnt1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getActivity().onBackPressed();




        }
    });




    locationsAdapter = new LocationsAdapter(getActivity(), new OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            LatLng latLng = new LatLng(filteredlocationModelArrayList.get(position).getLatitude(),
                    filteredlocationModelArrayList.get(position).getLongitude());
            String url = "http://maps.google.com/maps?saddr=" + locationActivityfin.mCurrentLocation.getLatitude() + "," + locationActivityfin.mCurrentLocation.getLongitude() + "&daddr=" + latLng.latitude + "," + latLng.longitude + "&mode=driving";
            Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                    Uri.parse(url));
            PackageManager packageManager = getActivity().getPackageManager();
            if (intent.resolveActivity(packageManager) != null) {
                startActivity(intent);
            } else {
                if (getView() != null)
                    Snackbar.make(getView(), "Make sure Google Maps is installed to use this feature", Snackbar.LENGTH_LONG).show();
            }

        }
    }, filteredlocationModelArrayList);
    getDataFromServer();

   //textView.setText(getArguments().getDouble("latitude") + ", " + getArguments().getDouble("longitude"));
}
public void update(Location location) {
    //  Toast.makeText(getActivity(), "updated", Toast.LENGTH_SHORT).show();
    filteredlocationModelArrayList.clear();
    for (LocationModel locationModel : locationModelArrayList) {
        Location location1 = new Location("Loc");
        location1.setLatitude(locationModel.getLatitude());
        location1.setLongitude(locationModel.getLongitude());
        if (location1.distanceTo(location) <= 50000 && filteredlocationModelArrayList.size() < 30) {
            double distance = (double) (location1.distanceTo(location) / 1000);
            try {
                distance = round(distance, 2);
            } catch (Exception e) {


            }



            locationModel.setDistance(distance);
            filteredlocationModelArrayList.add(locationModel);
        }



        locationsAdapter.update(filteredlocationModelArrayList);

    }
}

public double round(double value, int places) {
    if (places <= 0) throw new IllegalArgumentException();

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.doubleValue();
}

void getDataFromServer() {
    mDatabase.child("ali").child("location221").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot dataChild : dataSnapshot.getChildren()) {

                LocationModel locationModel = dataChild.getValue(LocationModel.class);
                locationModelArrayList.add(locationModel);
            }
            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            recyclerView.setAdapter(locationsAdapter);
            if (locationActivityRape.mCurrentLocation != null) {
                update(locationActivityRape.mCurrentLocation);
            }




        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

}

1 个答案:

答案 0 :(得分:0)

假设您已经弄清楚了方法可以告诉某些资源距应用程序一定距离,那么下一个问题是您是否希望它在整个生命周期中或仅在启动时更新应用程序,或者恢复。

对于前者,作为应用程序初始化的一部分,您将启动某种定时任务。您希望此代码脱离UI线程,并且可能需要使用网络来完成其工作。想法是,此任务会定期唤醒,并执行检查外部资源所需的所有工作。

只要找到一些有效资源,它就会重新进入睡眠状态。如果找不到有效资源,则它会调用一个回调方法或引发一个意图,即您的客户端代码会监听以显示对话框,敲响铃声等。请确保在清理应用程序时关闭此任务,并确保您可以取消运行状态和/或处理并使用超时。

如果仅在启动时启动一个AsyncTask即可获得一些结果,然后通过其UI线程处理程序进行报告(或与调用方进行通信),从而可以显示对话框,并可能关闭了应用程序(如果这些资源对应用程序生命周期至关重要)。

相关问答:Timertask or HandlerAsyncTask Android example(但是还有很多其他资源。)