so, after a year or two i started this project again... by the time it was outdated it worked fine... but since android x came out i wanted to upgrade my application and got stuck on a error i find it funny...
quick brief, i have button that makes me online / offline.. on pressing the button the map should zoom at my curr. location and add a marker.. but here comes the error :
Logcat:
Process: com.app.mk.transport, PID: 22142
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
at com.app.mk.transport.DriverHome$16$1$1.onComplete(DriverHome.java:1110)
at com.firebase.geofire.GeoFire$2.onComplete(GeoFire.java:178)
at com.google.firebase.database.core.Repo$6.run(com.google.firebase:firebase-database##19.2.0:404)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
DriverHome.java ( Not The whole code ):
private void setUpAutocomplete() {
AutocompleteSupportFragment autocompleteFragment = new AutocompleteSupportFragment();
// final AutocompleteSupportFragment autocompleteFragment;
// autocompleteFragment = (AutocompleteSupportFragment) getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
autocompleteFragment.setCountry("MK");
if (!Places.isInitialized()) {
Places.initialize(getApplicationContext(), getResources().getString(R.string.google_open_api));
}
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ADDRESS));
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(#NonNull Place place) {
if (location_switch.isChecked()) {
destination = place.getAddress();
destination = destination.replace(" ", "+");
if (destination.contains("+(FYROM)")) {
destination = destination.replace("+(FYROM)", "");
}
mMap.clear();
getDirection();
}
}
#Override
public void onError(#NonNull Status status) {
Toast.makeText(DriverHome.this, "" + status.toString(), Toast.LENGTH_SHORT).show();
Log.i("MITKASIN", "An error occurred: " + status);
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.driver_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_trip_history) {
// Handle the camera action
} else if (id == R.id.nav_way_bill) {
} else if (id == R.id.nav_help) {
} else if (id == R.id.nav_settings) {
} else if (id == R.id.nav_update_Info) {
showDialogUpdateInfo();
} else if (id == R.id.nav_sign_out) {
signOut();
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void showDialogUpdateInfo() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(DriverHome.this);
alertDialog.setTitle("Update Information");
alertDialog.setMessage("Please fill in the informations");
LayoutInflater inflater = this.getLayoutInflater();
View dialog_change_pwd = inflater.inflate(R.layout.layout_update_information, null);
final TextInputEditText edt_Name = dialog_change_pwd.findViewById(R.id.edtName);
final TextInputEditText edt_Phone = dialog_change_pwd.findViewById(R.id.edtPhone);
final ImageView image_upload = (ImageView) dialog_change_pwd.findViewById(R.id.image_upload);
image_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage();
}
});
alertDialog.setView(dialog_change_pwd);
alertDialog.setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
final android.app.AlertDialog waitingDialog = new SpotsDialog.Builder()
.setContext(DriverHome.this)
.setTheme(R.style.Orange)
.setMessage(R.string.waitingDialog_title)
.setCancelable(false)
.build();
waitingDialog.show();
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
String name = edt_Name.getText().toString();
String phone = edt_Phone.getText().toString();
Map<String, Object> updateInfo = new HashMap<>();
if (!TextUtils.isEmpty(name))
updateInfo.put("name", name);
if (!TextUtils.isEmpty(phone))
updateInfo.put("phone", phone);
DatabaseReference driverInformations = FirebaseDatabase.getInstance().getReference(Common.user_driver_tbl);
driverInformations.child(account.getId())
.updateChildren(updateInfo)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
waitingDialog.dismiss();
if (task.isSuccessful()) {
Toast.makeText(DriverHome.this, "Information updated!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DriverHome.this, "Information update Failed!", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), Common.PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Common.PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri saveUri = data.getData();
if (saveUri != null) {
final ProgressDialog mDialog = new ProgressDialog(this);
mDialog.setMessage("Uploading...");
mDialog.show();
String imageName = UUID.randomUUID().toString();
final StorageReference imageFolder = storageReference.child("images/" + imageName);
imageFolder.putFile(saveUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mDialog.dismiss();
Toast.makeText(DriverHome.this, "Uploaded !", Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(final Uri uri) {
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
Map<String, Object> avatarUpdate = new HashMap<>();
avatarUpdate.put("avatarUrl", uri.toString());
DatabaseReference driverInformations = FirebaseDatabase.getInstance().getReference(Common.user_driver_tbl);
driverInformations.child(account.getId())
.updateChildren(avatarUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(DriverHome.this, "Uploaded!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DriverHome.this, "Upload error !", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
});
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mDialog.setMessage("Upliaded " + progress + "%");
}
});
}
}
}
private void signOut() {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
else
builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to logout?")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Paper.init(this);
AccountKit.logOut();
Intent intent = new Intent(DriverHome.this, MainActivity.class);
startActivity(intent);
finish();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
private float getBearing(LatLng startPosition, LatLng endPosition) {
double lat = Math.abs(startPosition.latitude - endPosition.latitude);
double lng = Math.abs(startPosition.longitude - endPosition.longitude);
if (startPosition.latitude < endPosition.latitude && startPosition.longitude < endPosition.longitude)
return (float) (Math.toDegrees(Math.atan(lng / lat)));
else if (startPosition.latitude >= endPosition.latitude && startPosition.longitude < endPosition.longitude)
return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 90);
else if (startPosition.latitude >= endPosition.latitude && startPosition.longitude >= endPosition.longitude)
return (float) (Math.toDegrees(Math.atan(lng / lat)) + 180);
else if (startPosition.latitude < endPosition.latitude && startPosition.longitude >= endPosition.longitude)
return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 270);
return -1;
}
private void updateFirebaseToken() {
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference tokens = db.getReference(Common.token_tbl);
Token token = new Token(FirebaseInstanceId.getInstance().getToken());
tokens.child(account.getId())
.setValue(token);
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
private void getDirection() {
currentPosition = new LatLng(Common.mLastLocation.getLatitude(), Common.mLastLocation.getLongitude());
String requestApi = null;
try {
requestApi = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&" +
"transit_routing_reference=less_driving&" +
"origin=" + currentPosition.latitude + "," + currentPosition.longitude + "&" +
"destination=" + destination + "&" +
"key=" + getResources().getString(R.string.google_direction_api);
Log.i("MITKASIN", requestApi);
mServices.getPath(requestApi)
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body());
JSONArray jsonArray = jsonObject.getJSONArray("routes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject route = jsonArray.getJSONObject(i);
JSONObject poly = route.getJSONObject("overview_polyline");
String polyline = poly.getString("points");
polyLineList = decodePoly(polyline);
}
if (!polyLineList.isEmpty()) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : polyLineList)
builder.include(latLng);
LatLngBounds bounds = builder.build();
CameraUpdate mCameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 1);
mMap.animateCamera(mCameraUpdate);
// mMap.getUiSettings().setAllGesturesEnabled(true);
}
polylineOptiuons = new PolylineOptions();
polylineOptiuons.color(Color.GRAY);
polylineOptiuons.width(5);
polylineOptiuons.startCap(new SquareCap());
polylineOptiuons.endCap(new SquareCap());
polylineOptiuons.jointType(JointType.ROUND);
polylineOptiuons.addAll(polyLineList);
greyPolyline = mMap.addPolyline(polylineOptiuons);
blackPolylineOptions = new PolylineOptions();
blackPolylineOptions.color(Color.BLACK);
blackPolylineOptions.width(7);
blackPolylineOptions.startCap(new SquareCap());
blackPolylineOptions.endCap(new SquareCap());
blackPolylineOptions.jointType(JointType.ROUND);
blackPolyline = mMap.addPolyline(blackPolylineOptions);
if (!polyLineList.isEmpty()) {
mMap.addMarker(new MarkerOptions()
.position(polyLineList.get(polyLineList.size() - 1))
.title("Pickup Location"));
}
//Animation
ValueAnimator polyLineAnimator = ValueAnimator.ofInt(0, 100);
polyLineAnimator.setDuration(2000);
polyLineAnimator.setInterpolator(new LinearInterpolator());
polyLineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
List<LatLng> points = greyPolyline.getPoints();
int percentValue = (int) valueAnimator.getAnimatedValue();
int size = points.size();
int newPoints = (int) (size * (percentValue / 100.0f));
List<LatLng> p = points.subList(0, newPoints);
blackPolyline.setPoints(p);
}
});
polyLineAnimator.start();
carMarker = mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.flat(true)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));
handler = new Handler();
index = -1;
next = 1;
handler.postDelayed(drawPathRunnable, 2000);
// mMap.getUiSettings().setScrollGesturesEnabled(true);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(DriverHome.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
// mMap.getUiSettings().setScrollGesturesEnabled(true);
}
private List decodePoly(String encoded) {
List poly = new ArrayList();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PEMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
buildLocationCallback();
buildLocationRequest();
if (location_switch.isChecked())
displayLocation();
}
}
}
private void setUpLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//Request runtime permission
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
}, MY_PEMISSION_REQUEST_CODE);
} else {
buildLocationRequest();
buildLocationCallback();
if (location_switch.isChecked())
displayLocation();
}
}
private void buildLocationCallback() {
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
Common.mLastLocation = location;
}
displayLocation();
}
};
}
private void buildLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
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;
}
fusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
Common.mLastLocation = location;
if (Common.mLastLocation != null) {
if (location_switch.isChecked()) {
final double latitude = Common.mLastLocation.getLatitude();
final double longitude = Common.mLastLocation.getLongitude();
//Update to Firebase
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
geoFire.setLocation(account.getId(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
if (mCurrent != null) {
mCurrent.remove();
}
mCurrent = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Your Location"));
// Move camera to this position when set to online!
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 14.5f));
// Draw animation rotate marker
// rotateMarker(mCurrent, 360, mMap);
}
});
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
} else {
Log.d("ERROR", "Cannot get your location");
}
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(false);
mMap.setIndoorEnabled(false);
mMap.setBuildingsEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.style_json));
if (!success) {
Log.e("Mitkasin", "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e("Mitkasin", "Can't find style. Error: ", e);
}
if (ActivityCompat.checkSelfPermission(DriverHome.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(DriverHome.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
buildLocationRequest();
buildLocationCallback();
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, Looper.myLooper());
}
}
excuse me for the nasty code tho :D
and sorry if its a dumb question but idk what im missing here ...
You need to call your displayLocation and getDirection methods only after the map has been initialized (i.e. mMap = googleMap). Check out related Null Pointer Exception and getMapAsync Error
E.g.:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(false);
mMap.setIndoorEnabled(false);
mMap.setBuildingsEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.style_json));
if (!success) {
Log.e("Mitkasin", "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e("Mitkasin", "Can't find style. Error: ", e);
}
displayLocation();
getDirection();
}
Hope this helps!
Related
// Camera activity code
public class CamActivity extends AppCompatActivity implements
ActivityCompat.OnRequestPermissionsResultCallback,
AspectRatioFragment.Listener {
public static boolean activityStatus;
private Handler handler = new Handler();
private FirebaseAnalytics mFirebaseAnalytics;
private static final String TAG = "CamActivity";
private static final int REQUEST_CAMERA_PERMISSION = 1;
private static final String FRAGMENT_DIALOG = "dialog";
private static final int SELECT_PICTURE = 1;
private static final int[] FLASH_OPTIONS = {
CameraView.FLASH_AUTO,
CameraView.FLASH_OFF,
CameraView.FLASH_ON,
};
private static final int[] FLASH_ICONS = {
R.drawable.ic_flash_auto,
R.drawable.ic_flash_off,
R.drawable.ic_flash_on,
};
private static final int[] FLASH_TITLES = {
R.string.flash_auto,
R.string.flash_off,
R.string.flash_on,
};
private int mCurrentFlash;
private CameraView mCameraView;
private Handler mBackgroundHandler;
private FloatingActionButton fab;
private ImageView open_gallery;
private View.OnClickListener mOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.take_picture:
if (mCameraView != null) {
try {
mCameraView.takePicture();
/*handler.postDelayed(() ->
mCameraView.takePicture(),
500);*/
}catch (Exception e){
Log.e(TAG,"mCameraView"+e.toString());
}
}
break;
case R.id.open_gallery:
openGallery();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle bundle1 = new Bundle();
bundle1.putString(TAG, TAG);
bundle1.putString(TAG, TAG);
mFirebaseAnalytics.logEvent(TAG, bundle1);
setContentView(R.layout.activity_camera_renderer);
mCameraView = findViewById(R.id.camera);
open_gallery = findViewById(R.id.open_gallery);
if (open_gallery!=null)
open_gallery.setOnClickListener(mOnClickListener);
activityStatus = true;
if (mCameraView != null) {
mCameraView.addCallback(mCallback);
}
fab = findViewById(R.id.take_picture);
if (fab != null) {
fab.setOnClickListener(mOnClickListener);
}
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowTitleEnabled(false);
}
//toolbar.setTitle("Camera");
toolbar.setNavigationIcon(R.drawable.ic_back_arrow);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeCamera();
}
});
//Listen for capture image and close camera
registerReceiver(syncCamReceiver, new IntentFilter("Camera"));
}
#Override
public void onBackPressed() {
closeCamera();
super.onBackPressed();
}
/**CLose camera**/
private void closeCamera(){
try{
unregisterReceiver(syncCamReceiver);
}
catch (Exception e){
Log.d(TAG,"Error while unregistering");
}
SN88Constant.getIk6Obj(getApplicationContext()).sendPhotoSwitch(false);
CamActivity.this.finish();
}
BroadcastReceiver syncCamReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
if (intent.getAction().equalsIgnoreCase("Camera")) {
//0 for open cam, 1 take picture 2 close camera
if(intent.getIntExtra(Constants.CAMERA_REQUEST_TYPE,-1)==1){
fab .performClick();
}
else if(intent.getIntExtra(Constants.CAMERA_REQUEST_TYPE,-1)==2){
CamActivity.this.finish();
}
}
}
};
#Override
protected void onResume() {
activityStatus = true;
try {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
if (mCameraView != null)
mCameraView.start();
} else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
ConfirmationDialogFragment
.newInstance(R.string.camera_permission_confirmation,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION,
R.string.camera_permission_not_granted)
.show(getSupportFragmentManager(), FRAGMENT_DIALOG);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
}
}catch (Exception e){
Log.d(TAG,"Camera_onresume"+e.toString());
}
super.onResume();
}
#Override
protected void onPause() {
mCameraView.stop();
super.onPause();
}
#Override
protected void onDestroy() {
closeCamera();
activityStatus = false;
if (mBackgroundHandler != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
mBackgroundHandler.getLooper().quitSafely();
} else {
mBackgroundHandler.getLooper().quit();
}
mBackgroundHandler = null;
}
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA_PERMISSION:
if (permissions.length != 1 || grantResults.length != 1) {
throw new RuntimeException("Error on requesting camera permission.");
}
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, R.string.camera_permission_not_granted,
Toast.LENGTH_SHORT).show();
}
// No need to start camera here; it is handled by onResume
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.aspect_ratio:
FragmentManager fragmentManager = getSupportFragmentManager();
if (mCameraView != null
&& fragmentManager.findFragmentByTag(FRAGMENT_DIALOG) == null) {
final Set<AspectRatio> ratios = mCameraView.getSupportedAspectRatios();
final AspectRatio currentRatio = mCameraView.getAspectRatio();
AspectRatioFragment.newInstance(ratios, currentRatio)
.show(fragmentManager, FRAGMENT_DIALOG);
}
return true;
case R.id.switch_flash:
if (mCameraView != null) {
mCurrentFlash = (mCurrentFlash + 1) % FLASH_OPTIONS.length;
item.setTitle(FLASH_TITLES[mCurrentFlash]);
item.setIcon(FLASH_ICONS[mCurrentFlash]);
mCameraView.setFlash(FLASH_OPTIONS[mCurrentFlash]);
}
return true;
case R.id.switch_camera:
if (mCameraView != null) {
try {
int facing = mCameraView.getFacing();
mCameraView.setFacing(facing == CameraView.FACING_FRONT ?
CameraView.FACING_BACK : CameraView.FACING_FRONT);
}catch (Exception e){
e.printStackTrace();
}
}
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onAspectRatioSelected(#NonNull AspectRatio ratio) {
if (mCameraView != null) {
//Toast.makeText(this, ratio.toString(), Toast.LENGTH_SHORT).show();
try {
mCameraView.setAspectRatio(ratio);
}catch (Exception e){
Log.d(TAG,"onAspectRatioSelected"+e.toString());
}
}
}
private Handler getBackgroundHandler() {
if (mBackgroundHandler == null) {
HandlerThread thread = new HandlerThread("background");
thread.start();
mBackgroundHandler = new Handler(thread.getLooper());
}
return mBackgroundHandler;
}
private CameraView.Callback mCallback
= new CameraView.Callback() {
#Override
public void onCameraOpened(CameraView cameraView) {
Log.d(TAG, "onCameraOpened");
}
#Override
public void onCameraClosed(CameraView cameraView) {
Log.d(TAG, "onCameraClosed");
}
#Override
public void onPictureTaken(CameraView cameraView, final byte[] data) {
Log.d(TAG, "onPictureTaken " + data.length);
Toast.makeText(cameraView.getContext(), R.string.picture_taken, Toast.LENGTH_SHORT)
.show();
getBackgroundHandler().post(new Runnable() {
#Override
public void run() {
String folderPath = Environment.getExternalStorageDirectory() + "/DCIM/Camera";
File folder = new File(folderPath);
if (!folder.exists()) {
File wallpaperDirectory = new File(folderPath);
wallpaperDirectory.mkdir();
}
File file = new File(folderPath,"/Img"+System.currentTimeMillis()+ ".png");
OutputStream os = null;
try {
os = new FileOutputStream(file);
os.write(data);
os.close();
scanFile(file.getAbsolutePath());
} catch (IOException e) {
Log.w(TAG, "Cannot write to " + file, e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
// Ignore
}
}
}
}
});
}
};
public static class ConfirmationDialogFragment extends DialogFragment {
private static final String ARG_MESSAGE = "message";
private static final String ARG_PERMISSIONS = "permissions";
private static final String ARG_REQUEST_CODE = "request_code";
private static final String ARG_NOT_GRANTED_MESSAGE = "not_granted_message";
public static ConfirmationDialogFragment newInstance(#StringRes int message,
String[] permissions, int requestCode, #StringRes int notGrantedMessage) {
ConfirmationDialogFragment fragment = new ConfirmationDialogFragment();
Bundle args = new Bundle();
args.putInt(ARG_MESSAGE, message);
args.putStringArray(ARG_PERMISSIONS, permissions);
args.putInt(ARG_REQUEST_CODE, requestCode);
args.putInt(ARG_NOT_GRANTED_MESSAGE, notGrantedMessage);
fragment.setArguments(args);
return fragment;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Bundle args = getArguments();
return new AlertDialog.Builder(getActivity())
.setMessage(args.getInt(ARG_MESSAGE))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] permissions = args.getStringArray(ARG_PERMISSIONS);
if (permissions == null) {
throw new IllegalArgumentException();
}
ActivityCompat.requestPermissions(getActivity(),
permissions, args.getInt(ARG_REQUEST_CODE));
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(),
args.getInt(ARG_NOT_GRANTED_MESSAGE),
Toast.LENGTH_SHORT).show();
}
})
.create();
}
}
//Scans the saved file so it appears in the gallery
private void scanFile(String path) {
MediaScannerConnection.scanFile(this,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
}
/*
* open gallery for image preview
* */
private void openGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
}
// Getting error :
E/CamActivity: mCameraViewjava.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.camera2.CaptureRequest$Builder.set(android.hardware.camera2.CaptureRequest$Key, java.lang.Object)' on a null object reference
public class userListActivity extends AppCompatActivity {
public void getPhoto() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getPhoto();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.share_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.share) {
if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else {
getPhoto();
}
} else if (item.getItemId() == R.id.logout) {
ParseUser.logOut();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
setTitle("User Feed");
final ListView listView = findViewById(R.id.listView);
final ArrayList<String> usernames = new ArrayList<String>();
final ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, usernames);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), userFeedActivity.class);
intent.putExtra("username", usernames.get(i));
startActivity(intent);
}
});
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereNotEqualTo("username",ParseUser.getCurrentUser().getUsername());
query.addAscendingOrder("username");
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
for (ParseUser user : objects) {
usernames.add(user.getUsername());
}
listView.setAdapter(arrayAdapter);
}
} else {
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImage = data.getData();
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
Log.i("Image Selected", "Good work");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
ParseFile file = new ParseFile("image.png", byteArray);
ParseObject object = new ParseObject("Image");
object.put("image", file);
object.put("username", ParseUser.getCurrentUser().getUsername());
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(userListActivity.this, "Image has been shared!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(userListActivity.this, "There has been an issue uploading the image :(", Toast.LENGTH_SHORT).show();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnKeyListener {
Boolean signUpModeActive = true;
TextView loginTextView;
EditText usernameEditText;
EditText passwordEditText;
public void showUserList() {
Intent intent = new Intent(getApplicationContext(), userListActivity.class);
startActivity(intent);
}
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if (i == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
signUpClicked(view);
}
return false;
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.loginTextView) {
Button signUpButton = findViewById(R.id.signUpButton);
if (signUpModeActive) {
signUpModeActive = false;
signUpButton.setText("Login");
loginTextView.setText("or, Sign Up");
} else {
signUpModeActive = true;
signUpButton.setText("Sign Up");
loginTextView.setText("or, Login");
}
} else if (view.getId() == R.id.logoimageView || view.getId() == R.id.backgroudLayout) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0);
}
}
public void signUpClicked(View view) {
if (usernameEditText.getText().toString().matches("") || passwordEditText.getText().toString().matches("")) {
Toast.makeText(this, "A username and a password are required.",Toast.LENGTH_SHORT).show();
} else {
if (signUpModeActive) {
ParseUser user = new ParseUser();
user.setUsername(usernameEditText.getText().toString());
user.setPassword(passwordEditText.getText().toString());
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.i("Signup", "Success");
showUserList();
} else {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
// Login
ParseUser.logInInBackground(usernameEditText.getText().toString(), passwordEditText.getText().toString(), new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e) {
if (user != null) {
Log.i("Login","ok!");
showUserList();
} else {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Instagram");
loginTextView = findViewById(R.id.loginTextView);
loginTextView.setOnClickListener(this);
usernameEditText = findViewById(R.id.usernameEditText);
passwordEditText = findViewById(R.id.passwordEditText);
ImageView logoImageView = findViewById(R.id.logoimageView);
ConstraintLayout backgroundLayout = findViewById(R.id.backgroudLayout);
logoImageView.setOnClickListener(this);
backgroundLayout.setOnClickListener(this);
passwordEditText.setOnKeyListener(this);
if (ParseUser.getCurrentUser() != null) {
showUserList();
}
ParseAnalytics.trackAppOpenedInBackground(getIntent());
}
public class userFeedActivity extends AppCompatActivity {
LinearLayout linLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_feed);
Intent intent = getIntent();
String username = intent.getStringExtra("username");
setTitle(username + "'s Photos");
linLayout = findViewById(R.id.linLayout);
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Image");
query.whereEqualTo("username", username);
query.orderByDescending("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null && objects.size() > 0) {
for (ParseObject object : objects) {
ParseFile file = (ParseFile) object.get("image");
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e == null && data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,data.length);
ImageView imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
imageView.setImageBitmap(bitmap);
linLayout.addView(imageView);
}
}
});
}
}
}
});
}
I EDITED IT
THIS I MY WHOLE CODE NOW
PLEASE HELP
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
Button facedetect;
GraphicOverlay graphicOverlay;
CameraView cameraView;
AlertDialog alertDialog;
Bitmap captureImage, saveImage;
Bitmap b1,b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
facedetect = findViewById(R.id.detect_face_btn);
graphicOverlay = findViewById(R.id.graphic_overlay);
cameraView = findViewById(R.id.camera_view);
facedetect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraView.start();
cameraView.captureImage();
graphicOverlay.clear();
}
});
cameraView.addCameraKitListener(new CameraKitEventListenerAdapter() {
#Override
public void onEvent(CameraKitEvent event) {
super.onEvent(event);
}
#Override
public void onError(CameraKitError error) {
super.onError(error);
}
#Override
public void onImage(CameraKitImage image) {
super.onImage(image);
alertDialog.show();
b1 = image.getBitmap();
b1 = Bitmap.createScaledBitmap(b1, cameraView.getWidth(), cameraView.getHeight(), false);
cameraView.stop();
getImageFromLocal();`enter code here`
// if ( compareImages(b1,b2)==true) {
// Toast.makeText(getApplicationContext(),"True",Toast.LENGTH_SHORT).show();
// }
// Toast.makeText(getApplicationContext(),"False",Toast.LENGTH_SHORT).show();
processFaceDetaection(b1);
}
#Override
public void onVideo(CameraKitVideo video) {
super.onVideo(video);
}
});
}
private void processFaceDetaection(Bitmap bitmap) {
FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(bitmap);
FirebaseVisionFaceDetectorOptions firebaseVisionFaceDetectorOptions = new FirebaseVisionFaceDetectorOptions.Builder().build();
// High-accuracy landmark detection and face classification
FirebaseVisionFaceDetectorOptions landmarkdetectionfacedetection =
new FirebaseVisionFaceDetectorOptions.Builder()
.setPerformanceMode(FirebaseVisionFaceDetectorOptions.ACCURATE)
.setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS)
.setClassificationMode(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS)
.build();
// Real-time contour detection of multiple faces
FirebaseVisionFaceDetectorOptions contourdetectionfacedetection =
new FirebaseVisionFaceDetectorOptions.Builder()
.setContourMode(FirebaseVisionFaceDetectorOptions.ALL_CONTOURS)
.build();
FirebaseVisionFaceDetector firebaseVisionFaceDetector = FirebaseVision.getInstance().getVisionFaceDetector(firebaseVisionFaceDetectorOptions);
// FirebaseVisionFaceDetector firebaseVisionFaceDetector = FirebaseVision.getInstance().getVisionFaceDetector(contourdetectionfacedetection);
firebaseVisionFaceDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionFace>>() {
#Override
public void onSuccess(List<FirebaseVisionFace> firebaseVisionFaces) {
getFaceResult(firebaseVisionFaces);
compareFaceFromLocal();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
alertDialog.dismiss();
Toast.makeText(MainActivity.this, "Error : " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void compareFaceFromLocal() {
if (compareImages(b1, b2) == true) {
Toast.makeText(getApplicationContext(), "True", Toast.LENGTH_SHORT).show();
}
Toast.makeText(getApplicationContext(), "False", Toast.LENGTH_SHORT).show();
}
private void getFaceResult(List<FirebaseVisionFace> firebaseVisionFaces) {
int counter = 0;
for (FirebaseVisionFace face : firebaseVisionFaces) {
Rect rect = face.getBoundingBox();
ReactOverlay reactOverlay = new ReactOverlay(graphicOverlay, rect);
graphicOverlay.add(reactOverlay);
counter = counter + 1;
}
Toast.makeText(MainActivity.this, "No. of faces detected : " + counter, Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
/**
* Get the angle by which an image must be rotated given the device's current
* orientation.
*/
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private int getRotationCompensation(String cameraId, Activity activity, Context context)
throws CameraAccessException {
// Get the device's current rotation relative to its "native" orientation.
// Then, from the ORIENTATIONS table, look up the angle the image must be
// rotated to compensate for the device's rotation.
int deviceRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
int rotationCompensation = ORIENTATIONS.get(deviceRotation);
// On most devices, the sensor orientation is 90 degrees, but for some
// devices it is 270 degrees. For devices with a sensor orientation of
// 270, rotate the image an additional 180 ((270 + 270) % 360) degrees.
CameraManager cameraManager = (CameraManager) context.getSystemService(CAMERA_SERVICE);
int sensorOrientation = cameraManager
.getCameraCharacteristics(cameraId)
.get(CameraCharacteristics.SENSOR_ORIENTATION);
rotationCompensation = (rotationCompensation + sensorOrientation + 270) % 360;
// Return the corresponding FirebaseVisionImageMetadata rotation value.
int result;
switch (rotationCompensation) {
case 0:
result = FirebaseVisionImageMetadata.ROTATION_0;
break;
case 90:
result = FirebaseVisionImageMetadata.ROTATION_90;
break;
case 180:
result = FirebaseVisionImageMetadata.ROTATION_180;
break;
case 270:
result = FirebaseVisionImageMetadata.ROTATION_270;
break;
default:
result = FirebaseVisionImageMetadata.ROTATION_0;
Log.e(TAG, "Bad rotation value: " + rotationCompensation);
}
return result;
}
#Override
protected void onPause() {
super.onPause();
cameraView.stop();
}
#Override
protected void onResume() {
super.onResume();
cameraView.start();
}
private void getImageFromLocal() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
/*Compare two images.
* #param bitmap1
* #param bitmap2
* #return true iff both images have the same dimensions and pixel values.*/
public static boolean compareImages(Bitmap bitmap1, Bitmap bitmap2) {
if (bitmap1.getWidth() != bitmap2.getWidth() ||
bitmap1.getHeight() != bitmap2.getHeight()) {
return false;
}
for (int y = 0; y < bitmap1.getHeight(); y++) {
for (int x = 0; x < bitmap1.getWidth(); x++) {
if (bitmap1.getPixel(x, y) != bitmap2.getPixel(x, y)) {
return false;
}
}
}
return true;
}
public static Uri imageURI;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 0) {
if (data != null) {
try {
b2 = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
System.exit(0);
Log.e("result", "BAD");
}
}
}
Here is my code. I am getting null in googleapiclient.
public class MapsActivity extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener, AdapterView.OnItemClickListener, DriverListner {
View view;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private static String TAG = "MAP LOCATION";
Context mContext;
TextView mLocationMarkerText;
private LatLng mCenterLatLong;
private AddressResultReceiver mResultReceiver;
protected String mAddressOutput;
protected String mAreaOutput;
protected String mCityOutput;
protected String mStateOutput;
EditText mLocationAddress;
TextView mLocationText;
private static final int REQUEST_CODE_AUTOCOMPLETE = 1;
AutoCompleteTextView edtDropLocation;
LatLng source;
LatLng destination;
LinearLayout lytBottomView;
private List < DriverDetail > driverDetailsList = new ArrayList < > ();
DriverListAdapter driverListAdapter;
RecyclerView rv_driver_truck;
DriverDetail driverDetail;
Button book;
int driverId = 0, userId = 0;
String currentLocation = "", dropLocation = "", currentLat = "", currentLong = "", dropLat = "", dropLong = "", token = "",
vehicleId = "", bookingDateTime = "", truckRent = "";
private LocationRequest mLocationRequest;
Date currentTime;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_maps, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
userId = Integer.parseInt(TruckApplication.ReadStringPreferences(SharedPrefData.PREF_UserId));
token = TruckApplication.ReadStringPreferences(SharedPrefData.PREF_TOKEN);
currentTime = Calendar.getInstance().getTime();
Log.e("##dateandtime", String.valueOf(currentTime));
mLocationMarkerText = view.findViewById(R.id.locationMarkertext);
rv_driver_truck = view.findViewById(R.id.rv_driver_truck);
mLocationAddress = view.findViewById(R.id.Address);
mLocationText = view.findViewById(R.id.Locality);
edtDropLocation = view.findViewById(R.id.edtDropLocation);
lytBottomView = view.findViewById(R.id.lytBottomView);
book = view.findViewById(R.id.book);
edtDropLocation.setAdapter(new MapFragment.GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item_text));
edtDropLocation.setOnItemClickListener(this);
mLocationText.setOnClickListener(view - > openAutocompleteActivity());
mapFragment.getMapAsync(this);
if (checkPlayServices()) {
if (!AppUtils.isLocationEnabled(getContext())) {
AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
dialog.setMessage("Location not enabled!");
dialog.setPositiveButton("Open location settings", (paramDialogInterface, paramInt) - > {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
});
dialog.setNegativeButton("Cancel", (paramDialogInterface, paramInt) - > {});
dialog.show();
}
buildGoogleApiClient();
} else {
Toast.makeText(mContext, "Location not supported in this device", Toast.LENGTH_SHORT).show();
}
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
rv_driver_truck.setLayoutManager(linearLayoutManager);
rv_driver_truck.setItemAnimator(new DefaultItemAnimator());
getDriverList();
book.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendBookRequest();
}
});
mResultReceiver = new AddressResultReceiver(new Handler());
return view;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnCameraChangeListener(cameraPosition - > {
Log.d("##Camera postion change" + "", cameraPosition + "");
mCenterLatLong = cameraPosition.target;
mMap.clear();
try {
Location mLocation = new Location("");
mLocation.setLatitude(mCenterLatLong.latitude);
mLocation.setLongitude(mCenterLatLong.longitude);
currentLat = String.valueOf(mCenterLatLong.latitude);
currentLong = String.valueOf(mCenterLatLong.longitude);
startIntentService(mLocation);
mLocationMarkerText.setText(getCompleteAddressString(mLocation.getLatitude(), mLocation.getLongitude()));
} catch (Exception e) {
e.printStackTrace();
}
});
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
}
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
changeMap(mLastLocation);
Log.d(TAG, "ON connected");
} else
try {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
} catch (Exception e) {
e.printStackTrace();
}
try {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
try {
if (location != null)
changeMap(location);
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
}
#Override
public void onStart() {
super.onStart();
try {
mGoogleApiClient.connect();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onStop() {
super.onStop();
try {
} catch (RuntimeException e) {
e.printStackTrace();
}
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {}
return false;
}
return true;
}
private void changeMap(Location location) {
Log.d(TAG, "Reaching map" + mMap);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mMap != null) {
mMap.getUiSettings().setZoomControlsEnabled(false);
LatLng latLong;
latLong = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLong).zoom(10 f).tilt(50).build();
mMap.setMyLocationEnabled(true);
/* mMap.getUiSettings().setMyLocationButtonEnabled(true);*/
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// mLocationMarkerText.setText("Lat : " + location.getLatitude() + "," + "Long : " + location.getLongitude());
getCompleteAddressString(location.getLatitude(), location.getLongitude());
mLocationMarkerText.setText(getCompleteAddressString(location.getLatitude(), location.getLongitude()));
startIntentService(location);
} else {
Toast.makeText(getContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
#Override
public void onItemClick(AdapterView << ? > parent, View view, int position, long id) {
String str = (String) parent.getItemAtPosition(position);
Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
LatLng lastLocation = source;
edtDropLocation.setText(str);
dropLocation = str;
Geocoder coder = new Geocoder(getContext());
try {
ArrayList < Address > adresses = (ArrayList < Address > ) coder.getFromLocationName(str, 50);
for (Address add: adresses) {
double longitude = add.getLongitude();
double latitude = add.getLatitude();
dropLat = String.valueOf(latitude);
dropLong = String.valueOf(longitude);
destination = new LatLng(latitude, longitude);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(destination);
mMap.clear();
markerOptions.title(str);
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.droppoint));
mMap.animateCamera(CameraUpdateFactory.newLatLng(destination));
mMap.addMarker(markerOptions);
getDriverList();
lytBottomView.setVisibility(View.VISIBLE);
driverListAdapter = new DriverListAdapter(getActivity(), driverDetailsList, this);
rv_driver_truck.setAdapter(driverListAdapter);
/* new GetPathFromLocation(lastLocation, destination, new DirectionPointListener() {
#Override
public void onPath(PolylineOptions polyLine) {
mMap.addPolyline(polyLine);
lytBottomView.setVisibility(View.VISIBLE);
}
}).execute();*/
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public DriverDetail driverDetail(DriverDetail driverDetail1) {
driverDetail = driverDetail1;
driverId = driverDetail1.getId();
truckRent = driverDetail1.getVehicleRent();
// Log.e("##DriverId", truckRent);
return driverDetail;
}
class AddressResultReceiver extends ResultReceiver {
public AddressResultReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
mAddressOutput = resultData.getString(AppUtils.LocationConstants.RESULT_DATA_KEY);
mAreaOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_AREA);
mCityOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_CITY);
mStateOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_STREET);
displayAddressOutput();
if (resultCode == AppUtils.LocationConstants.SUCCESS_RESULT) {
}
}
}
protected void displayAddressOutput() {
try {
if (mAreaOutput != null)
mLocationAddress.setText(mAddressOutput);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void startIntentService(Location mLocation) {
Intent intent = new Intent(getContext(), FetchAddressIntentService.class);
intent.putExtra(AppUtils.LocationConstants.RECEIVER, mResultReceiver);
intent.putExtra(AppUtils.LocationConstants.LOCATION_DATA_EXTRA, mLocation);
getActivity().startService(intent);
}
private void openAutocompleteActivity() {
try {
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
.build(getActivity());
startActivityForResult(intent, REQUEST_CODE_AUTOCOMPLETE);
} catch (GooglePlayServicesRepairableException e) {
GoogleApiAvailability.getInstance().getErrorDialog(getActivity(), e.getConnectionStatusCode(),
0 /* requestCode */ ).show();
} catch (GooglePlayServicesNotAvailableException e) {
String message = "Google Play Services is not available: " +
GoogleApiAvailability.getInstance().getErrorString(e.errorCode);
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_AUTOCOMPLETE) {
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(mContext, data);
LatLng latLong;
latLong = place.getLatLng();
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLong).zoom(19 f).tilt(70).build();
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(mContext, data);
} else if (resultCode == RESULT_CANCELED) {
}
}
#SuppressLint("LongLogTag")
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
String strAdd = "";
Geocoder geocoder = new Geocoder(getContext(), Locale.getDefault());
try {
List < Address > addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i <= returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
currentLocation = strAdd;
Log.e("My Current loction address", strReturnedAddress.toString());
} else {
Log.w("My Current loction address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current loction address", "Canont get Address!");
}
return strAdd;
}
private void getDriverList() {
ApiInterface apiInterface = RetrofitManager.getInstance().create(ApiInterface.class);
Call < OnlineDriverList > call = apiInterface.getDriverList();
call.enqueue(new Callback < OnlineDriverList > () {
#Override
public void onResponse(#NonNull Call < OnlineDriverList > call, Response < OnlineDriverList > response) {
// refreshLayout.setRefreshing(false);
if (response.isSuccessful()) {
OnlineDriverList onlineDriverList = response.body();
if (onlineDriverList.getDriverDetails().size() == 0) {
Toast.makeText(getContext(), "No Driver is Available at current Time ", Toast.LENGTH_SHORT).show();
} else {
driverDetailsList = onlineDriverList.getDriverDetails();
TruckBo.getInstance().setDriverArrayList(driverDetailsList);
// driverListAdapter.setData(driverDetailsList);
// refreshLayout.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onFailure(Call < OnlineDriverList > call, Throwable t) {
//refreshLayout.setRefreshing(false);
Log.d("Error", t.getLocalizedMessage());
}
});
}
public void sendBookRequest() {
ApiInterface apiInterface = RetrofitManager.getInstance().create(ApiInterface.class);
Call < UserRegistration > call = apiInterface.booking(driverId, userId, truckRent, currentLocation, dropLocation,
currentLat, currentLong, dropLat, dropLong, token, "", ""
);
call.enqueue(new Callback < UserRegistration > () {
#Override
public void onResponse(Call < UserRegistration > call, Response < UserRegistration > response) {
if (response.isSuccessful()) {
Toast.makeText(getContext(), "Wait For Respond From Driver Side", Toast.LENGTH_SHORT).show();
lytBottomView.setVisibility(View.GONE);
} else {}
}
#Override
public void onFailure(Call < UserRegistration > call, Throwable t) {
Log.e("Error", t.getLocalizedMessage());
}
});
}
}
I am getting null here:
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
}
The first time it is not going to the current location and I am getting null googleapiclient, and on move marker, I am fetching address in starting I am not getting current location.
My MainActivity looks like this:-
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback, LocationListener {
public static GoogleMap mMap;
public boolean flag = false;
public static boolean markerAlready = false;
public static PlaceAutocompleteFragment placeAutoComplete;
private LocationManager mLocationManager = null;
private String provider = null;
Circle c;
private Marker mCurrentPosition = null;
Marker marker;
public static Location location;
CircleOptions mOptions;
public static Location l;
FancyButton button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btnGuide);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Opens guides's details!", Toast.LENGTH_SHORT).show();
}
});
int perm = ContextCompat.checkSelfPermission(
MainActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION);
if (perm == PackageManager.PERMISSION_GRANTED) {
start();
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
}
} else {
ActivityCompat.requestPermissions(
MainActivity.this,
new String[] {Manifest.permission.ACCESS_COARSE_LOCATION},
44
);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == 44) { //write request
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
start();
}
}
else if (Build.VERSION.SDK_INT >= 23 && !shouldShowRequestPermissionRationale(permissions[0])) {
Toast.makeText(MainActivity.this, "Go to Settings and Grant the permission to use this feature.", Toast.LENGTH_SHORT).show();
}
}
public void start()
{
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingSearchView searchView = findViewById(R.id.floating_search_view);
searchView.setSearchHint("");
placeAutoComplete = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete);
Fragment a = getFragmentManager().findFragmentById(R.id.place_autocomplete);
a.setUserVisibleHint(false);
placeAutoComplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
if (marker != null)
marker.remove();
flag = true;
Log.d("Maps", "Place selected: " + place.getLatLng());
marker = mMap.addMarker(new MarkerOptions().position(place.getLatLng()).title(place.getName().toString()).zIndex(800));
mMap.moveCamera(CameraUpdateFactory.newLatLng(place.getLatLng()));
mMap.animateCamera(CameraUpdateFactory.zoomIn());
mMap.animateCamera(CameraUpdateFactory.zoomTo(13), 2000, null);
}
#Override
public void onError(Status status) {
Log.d("Maps", "An error occurred: " + status);
}
});
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
flag = false;
mMap.clear();
locateCurrentPosition();
placeAutoComplete.setText(null);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
//region NavDrawer Activity
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.emergency){
List<String> HelpLineNumbers = new ArrayList<>();
HelpLineNumbers.add("Women's Helpline");
HelpLineNumbers.add("Police");
HelpLineNumbers.add("Hospital");
HelpLineNumbers.add("Fire Department");
HelpLineNumbers.add("Ambulance");
HelpLineNumbers.add("Men's Helpline");
final CharSequence[] helpLine = HelpLineNumbers.toArray(new String[HelpLineNumbers.size()]);
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setTitle("Helpline Numbers");
mBuilder.setItems(helpLine, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String selectedText = helpLine[i].toString();
}
});
AlertDialog alertDialogObject = mBuilder.create();
alertDialogObject.show();
}
List<String> HelpLineNumbers = new ArrayList<>();
HelpLineNumbers.add("Women's Helpline");
HelpLineNumbers.add("Police");
HelpLineNumbers.add("Hospital");
HelpLineNumbers.add("Fire Department");
HelpLineNumbers.add("Ambulance");
HelpLineNumbers.add("Men's Helpline");
final CharSequence[] helpLine = HelpLineNumbers.toArray(new String[HelpLineNumbers.size()]);
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setTitle("Helpline Numbers");
mBuilder.setItems(helpLine, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String selectedText = helpLine[i].toString();
}
});
AlertDialog alertDialogObject = mBuilder.create();
//Show the dialog
alertDialogObject.show();
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.myProfile) {
// Handle the camera action
} else if (id == R.id.myTrips) {
} else if (id == R.id.fir) {
} else if (id == R.id.logout) {
} else if (id == R.id.contactus) {
} else if (id == R.id.feedback) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setupBottomNavigationView()
{
Log.d("BottomNv", "setupBottomNavigationView: setting up botNavView");
BottomNavigationViewEx bottomNavigationViewEx = findViewById(R.id.bnve);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(this,bottomNavigationViewEx);
}
//endregion
//region Maps Methods
public void onMapReady(GoogleMap googleMap) {
LocationManager lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {
Log.e("Error", "onMapReady: ");
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {
Log.e("Error", "onMapReady: " );
}
if(!gps_enabled && !network_enabled)
{
buildAlertMessageNoGps();
}
mMap = googleMap;
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (isProviderAvailable() && (provider != null))
{
locateCurrentPosition();
}
setupBottomNavigationView();
}
public void locateCurrentPosition()
{
int status = getPackageManager().checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
getPackageName());
if (status == PackageManager.PERMISSION_GRANTED) {
location = mLocationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
// mLocationManager.addGpsStatusListener(this);
long minTime = 5000;// ms
float minDist = 5.0f;// meter
mLocationManager.requestLocationUpdates(provider, minTime, minDist, this);
l=location;
if(l != null)
placeAutoComplete.setBoundsBias(new LatLngBounds(new LatLng(l.getLatitude(),l.getLongitude()),new LatLng(l.getLatitude()+2,l.getLongitude()+2)));
}
}
private void updateWithNewLocation(Location location) {
if (location != null && provider != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
if(!flag)
addBoundaryToCurrentPosition(lat, lng);
CameraPosition camPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lng)).zoom(12f).build();
if (mMap != null && !flag)
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(camPosition));
} else {
Log.d("Location error", "Something went wrong");
}
}
//*****************************************************************//
private void addBoundaryToCurrentPosition(double lat, double lang) {
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
String addressStr = "";
try {
List<Address> myList = myLocation.getFromLocation(lat,lang, 1);
Address address;
address = (Address) myList.get(0);
Log.d("LOCC", address.getAddressLine(0));
addressStr += address.getAddressLine(0) ;
} catch (IOException e) {
e.printStackTrace();
}
MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(new LatLng(lat, lang));
mMarkerOptions.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_location));
mMarkerOptions.anchor(0.5f, 0.5f);
if( mOptions == null)
{
mOptions = new CircleOptions()
.center(new LatLng(lat, lang)).radius(5000)
.strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF);
c = mMap.addCircle(mOptions);
}
else {
c.remove();
mOptions = new CircleOptions()
.center(new LatLng(lat, lang)).radius(5000)
.strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF);
c = mMap.addCircle(mOptions);
}
if (mCurrentPosition != null)
mCurrentPosition.remove();
mCurrentPosition = mMap.addMarker(mMarkerOptions);
mCurrentPosition.setTitle(addressStr);
}
private boolean isProviderAvailable() {
mLocationManager = (LocationManager) getSystemService(
Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = mLocationManager.getBestProvider(criteria, true);
if (mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
return true;
}
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
return true;
}
if (provider != null) {
return true;
}
return false;
}
#Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
#Override
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
case LocationProvider.AVAILABLE:
break;
}
}
public void buildAlertMessageNoGps()
{
new MaterialDialog.Builder(this)
.title("Location")
.content("Enable Location")
.positiveText("Enable GPS!")
.negativeText("No, Thanks!")
.cancelable(false)
.positiveColor(Color.rgb(232,42,42))
.negativeColor(Color.rgb(232,42,42))
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
Toast.makeText(MainActivity.this, "Location Access Required!!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
})
.show();
}
//endregion
}
As you can see in the method addBoundaryToCurrentPosition(), below that "//******//" (it's a part of MainActivity), I've set a marker at current location towards the end of the method which is supposed to refresh after every 5000ms.
Moreover I have a bottomNavigationView which is supposed to show nearby places. It's code is as below:-
public class BottomNavigationViewHelper {
private static final String TAG = "BottomNavigationViewHel";
static Menu menu;
static MenuItem menuItem;
public static Location l;
public static void setupBottomNavigationView(BottomNavigationViewEx bottomNavigationViewEx)
{
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavView");
bottomNavigationViewEx.enableAnimation(true);
bottomNavigationViewEx.enableItemShiftingMode(false);
bottomNavigationViewEx.enableShiftingMode(false);
bottomNavigationViewEx.setTextVisibility(true);
menu = bottomNavigationViewEx.getMenu();
}
public static void enableNavigation(final Context context, BottomNavigationViewEx view)
{
view.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.ic_hospital:
menuItem = menu.getItem(0);
menuItem.setChecked(true);
String Hospital = "hospital";
Log.d("onClick", "Button is Clicked");
MainActivity.mMap.clear();
locate(MainActivity.location);
MainActivity.markerAlready = false;
MainActivity.placeAutoComplete.setText("Hospitals near me");
String urlhospital = getUrl(MainActivity.l.getLatitude(), MainActivity.l.getLongitude(), Hospital);
Object[] DataTransferhospital = new Object[2];
DataTransferhospital[0] = MainActivity.mMap;
DataTransferhospital[1] = urlhospital;
Log.d("onClick", urlhospital);
GetNearbyPlacesData getNearbyPlacesDatahospital = new GetNearbyPlacesData();
getNearbyPlacesDatahospital.execute(DataTransferhospital);
break;
case R.id.ic_police:
menuItem = menu.getItem(1);
menuItem.setChecked(true);
String Police = "police";
Log.d("onClick", "Button is Clicked");
MainActivity.mMap.clear();
locate(MainActivity.location);
MainActivity.markerAlready = false;
MainActivity.placeAutoComplete.setText("Police Stations near me");
String urlpolice = getUrl(MainActivity.l.getLatitude(), MainActivity.l.getLongitude(), Police);
Object[] DataTransferpolice = new Object[2];
DataTransferpolice[0] = MainActivity.mMap;
DataTransferpolice[1] = urlpolice;
Log.d("onClick", urlpolice);
GetNearbyPlacesData getNearbyPlacesDatapolice = new GetNearbyPlacesData();
getNearbyPlacesDatapolice.execute(DataTransferpolice);
break;
case R.id.ic_food:
menuItem = menu.getItem(2);
menuItem.setChecked(true);
String Restaurant = "restaurant";
Log.d("onClick", "Button is Clicked");
MainActivity.mMap.clear();
MainActivity.markerAlready = false;
MainActivity.placeAutoComplete.setText("Restaurants near me");
locate(MainActivity.location);
String urlrestaurant = getUrl(MainActivity.l.getLatitude(), MainActivity.l.getLongitude(), Restaurant);
Object[] DataTransferrestaurant = new Object[2];
DataTransferrestaurant[0] = MainActivity.mMap;
DataTransferrestaurant[1] = urlrestaurant;
Log.d("onClick", urlrestaurant);
GetNearbyPlacesData getNearbyPlacesDatarestaurant = new GetNearbyPlacesData();
getNearbyPlacesDatarestaurant.execute(DataTransferrestaurant);
break;
}
return false;
}
});
}
private static String getUrl(double latitude, double longitude, String nearbyPlace) {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + 10000);
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "AIzaSyATuUiZUkEc_UgHuqsBJa1oqaODI-3mLs0");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}
public static void locate(Location location) {
if (location != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
CameraPosition camPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lng)).zoom(12f).build();
if (MainActivity.mMap != null) {
MainActivity.mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(camPosition));
} else {
Log.d("Location error", "Something went wrong");
}
final MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(new LatLng(lat, lng));
mMarkerOptions.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_location));
final Marker m = MainActivity.mMap.addMarker(mMarkerOptions);
CircleOptions mOptions;
final Circle c;
mOptions = new CircleOptions()
.center(new LatLng(lat, lng)).radius(5000)
.strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF);
c = MainActivity.mMap.addCircle(mOptions);
}
}
}
In this I've created a method locate() , towards the end, which is called in switch cases. It fetches current location from MainActivity and sets marker after clearing the map.
The problem that I face is that when I click one of the buttons in BottomNavView, at first only one marker for current location is visible (that by BottomNav) but after some random time, marker by MainActivity also starts showing up. Hence two markers for current location show up.
I've tried creating a handler to remove marker by bottomNav after 5000ms but marker of MainActivity starts showing after random amount of time.
How do I prevent two markers from showing up simultaneously while at the same time ensuring that at least on of the markers is visible at all times??
First, you need to change your Marker variable name to more a readable name because it makes you confuse:
private Marker mCurrentPosition = null;
Marker marker;
What current position means? is it location or marker? What is marker? I think the better name for the above code is following:
private Marker mMarkerCurrentPosition = null;
private Marker mMarkerSelectedPlace;
Second, you adding a marker with BottomNavigationViewHelper.locate without removing the previous marker:
public static void locate(Location location) {
...
final Marker m = MainActivity.mMap.addMarker(mMarkerOptions);
...
}
Furthermore, you should change your code so you can't access the MainActivity variable outside the class by modifying the method parameters to something like this:
public static void locate(GoogleMap map, Location location) {
}
Last, don't use GoogleMap.clear() to clear your markers. Instead, try to always removing all the markers added to the GoogleMap one by one. You can achieve it by always adding the item to a list. Then, you can remove each item by iterating the lists. For example:
List<Marker> markers;
// add 3 marker
markers.add(mMap.addMarker(mMarkerOptions));
markers.add(mMap.addMarker(mMarkerOptions));
markers.add(mMap.addMarker(mMarkerOptions));
// remove markers
for (Iterator<Marker> it = markers.listIterator(); it.hasNext(); ) {
Marker marker = iter.next();
// remove the marker from map
marker.remove();
// remove marker from list
iter.remove();
}