0

I have an app which obtains the users location and sends it to my Firebase Database which has a list of locations closest to the user. The location radius has been set to less than 50km(50000m). if there are no locations within that radius, I want an alert dialog to appear saying that there are no locations available. The locations will be updated as the app runs. The alert dialog should be shown every time the user tries to access the locations within the set radius. Can someone help me out on how to go about doing it? Any help will be greatly appreciated.

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) {

        }
    });
}

}

Daniel
  • 1
  • 7
  • It depends if you want this to be checked only once, perhaps on startup, or over the lifetime of the app. You should also define what "near" means. –  Oct 18 '18 at 16:10
  • I want it to appear all the time the user tries to look for locations near them. and the locations shown are less than 50000m. if there are no locations within the 50000m, the alert dialog should show @jdv – Daniel Oct 18 '18 at 16:19
  • Make sure you put details pertinent to the question in the body of the question with an [edit]. And is this location being updated as the app runs? –  Oct 18 '18 at 16:19
  • thanks. I edited the question already to include the pertinent details. and yes the location is updated as the app runs @jdv – Daniel Oct 18 '18 at 16:26

1 Answers1

0

Assuming you have figured out how to tell that some resource is within some distance from the app, the next question is do you want this to update the app over its entire lifecycle or just at startup or resume.

For the former, as part of your app initialization you start up a timed task of some sort. You want this code to be off the UI thread, and it probably needs to use the network to do its job. The idea is that this task wakes up periodically and does whatever it needs to do to check for external resources.

As long as it finds some valid resource(s) it just goes back to sleep. If it finds no valid resources it then either invokes a callback method or raises an intent that your client code listens for to display a dialog, ring a bell, etc. Make sure you shut down this task when cleaning up your app, and make sure you can cancel the running state and/or it handles and uses timeouts.

If only once on startup just fire off an AsyncTask that gets some results, and then reports via its UI thread handler (or communicates back to the caller) so a dialog can be shown and perhaps the app closed (if these resources are critical to the app lifecycle).

Related Q&A: Timertask or Handler, AsyncTask Android example (But there are many others resources out there.)