why am I getting Error Attempt to invoke virtual method 'double android.location.Location.getLongitude()' on a null object reference - nullpointerexception

the weather forecasting add in this fumction there they are showing error in logcat is longitude and latitude that "
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLongitude()' on a null object reference
at com.example.weatherforecasting.MainActivity.onCreate(MainActivity.java:62)
in that
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this , Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},PERMISSION_CODE);
}else {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
**cityName = getCityName(location.getLongitude(), location.getLatitude());
getWeatherInfo(cityName);**
}
private String getCityName(double longitude , double latitude){
String cityName = "Not found";
Geocoder gcd = new Geocoder(getBaseContext() , Locale.getDefault());
try {
**List<Address> addresses = gcd.getFromLocation(latitude , longitude, 10);**
for (Address adr : addresses){
if (adr!=null){
String city = adr.getLocality();
if (city != null && !city.equals("")){
cityName = city;
}else {
Log.d("TAG", "CITY NOT FOUND");
Toast.makeText(this, "City Not Found", Toast.LENGTH_SHORT).show();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return cityName;
}
I tried to adjust but still facing error

Related

Get Address from current location Kotlin

I get the current location like this:
val fusedLocationClient: FusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(LocalContext.current)
fun getLastKnownLocation() {
fusedLocationClient.lastLocation.addOnSuccessListener { location ->
if (location != null) {
longitude.value = location.longitude
latitude.value = location.latitude
}
}
}
How I can get the Address from it?
Update
I implemented like this:
fun getLastKnownLocation() {
fusedLocationClient.lastLocation.addOnSuccessListener { location ->
if (location != null) {
longitude.value = location.longitude
latitude.value = location.latitude
val geocoder = Geocoder(app)
if (Build.VERSION.SDK_INT >= 33) {
geocoder.getFromLocation(
location.latitude, location.longitude, 1
) { addresses ->
address.value = addresses.first().toString()
}
}
else {
try {
val addresses = geocoder.getFromLocation(location.latitude, location.longitude, 1
)?.firstOrNull()
address.value = addresses.toString()
} catch (Exp: Exception) {
address.value = "No Address found"
println("$Exp")
}
}
}
}
}
But got this exception: java.io.IOException: eccc: DEADLINE_EXCEEDED: deadline exceeded after 4.907678698s
val geocoder = Geocoder(this, Locale.getDefault())
val addresses = geocoder.getFromLocation(location.latitude, location.longitude, 1)
https://developer.android.com/reference/kotlin/android/location/Geocoder

Google Places OpeningHours.getWeekdayText() is NULL for some locations

I'm using google places to retrieve information for a place such as the business name, address, OpenHours and LatLng.
This works 95% of the time, but for some places I receive the error...
"Attempt to invoke virtual method 'java.util.List com.google.android.libraries.places.api.model.OpeningHours.getWeekdayText()' on a null object reference"
Looking on Google maps, I do see these places have open hours information.
//Add a marker when a POI on map is clicked.
map.setOnPoiClickListener { poi ->
map.clear()
val poiMarker = map.addMarker(
MarkerOptions()
.position(poi.latLng)
.title(poi.name)
)
poiMarker?.showInfoWindow()
placeId = poi.placeId
Timber.i("Place ID: $placeId")
//https://developers.google.com/maps/documentation/places/android-sdk/reference/com/google/android/libraries/places/api/net/PlacesClient#fetchPlace(com.google.android.libraries.places.api.net.FetchPlaceRequest)
val placeFields = listOf(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.OPENING_HOURS, Place.Field.LAT_LNG)
val request = FetchPlaceRequest.newInstance(placeId, placeFields)
if (!Places.isInitialized()) {
Places.initialize(requireContext(), apiKey, Locale.US);
}
val placesClient = Places.createClient(requireContext())
placesClient.fetchPlace(request)
.addOnSuccessListener { response: FetchPlaceResponse ->
val place = response.place
setLiveDataPlace(place)
}.addOnFailureListener { exception: Exception ->
if (exception is ApiException) {
Timber.i( "Place not found: ${exception.message}")
}
}
binding.buttonSave.visibility = View.VISIBLE
}
}
fun setLiveDataPlace(place: Place){
placeId = place.id as String
placeName = place.name as String
placeAddress = place.address as String
try {
placeOpenMonday = place.openingHours.weekdayText[0]
placeOpenTuesday = place.openingHours.weekdayText[1]
placeOpenWednesday = place.openingHours.weekdayText[2]
placeOpenThursday = place.openingHours.weekdayText[3]
placeOpenFriday = place.openingHours.weekdayText[4]
placeOpenSaturday = place.openingHours.weekdayText[5]
placeOpenSunday = place.openingHours.weekdayText[6]
} catch(e : Exception) {
Timber.i("Open hours exception: ${e.message}")
}
placeLat = place.latLng.latitude.toString()
placeLng = place.latLng.longitude.toString()
Timber.i("Place: $place")
}

getExternalStoragePublicDirectory is deprecated and getExternalFilesDir is not working

i'm trying to take a photo and upload it. weird thing is, it's working on my android 9 device, but not working on the android 11 device... input field remains as "no file chosen" even after taking the photo.
here are the codes related to photo upload system
private String mCM;
private ValueCallback<Uri[]> mUMA;
private final static int FCR=1;
ActivityResultLauncher<Intent> startActivityIntent = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
Uri[] results = null;
if (result.getResultCode() == Activity.RESULT_OK) {
if(null == mUMA){
return;
}
if(result.getData() == null || result.getData().getData() == null){
if(mCM != null){
results = new Uri[]{Uri.parse(mCM)};
}
}else{
String dataString = result.getData().getDataString();
if(dataString != null){
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mUMA.onReceiveValue(results);
mUMA = null;
});
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, perms, FCR);
} else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, FCR);
} else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, FCR);
}
if (mUMA != null) {
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (MainActivity.this.getPackageManager().resolveActivity(takePictureIntent, 0) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
} catch (IOException ex) {
Log.e("TAG", "ioexception log", ex);
}
if (photoFile != null) {
mCM = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityIntent.launch(chooserIntent);
return true;
}
private File createImageFile() throws IOException{
String imageFileName = java.util.UUID.randomUUID().toString();
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
// File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName,".jpg",storageDir);
}
this is the last deprecation warning i have left in my app. it's working fine on all 3 of my test devices(android 7-9-11) with "getExternalStoragePublicDirectory"
I tried again with "getExternalFilesDir" and checked "Internal shared storage\Android\data-myapp-\files\Pictures"
there are files but 0bytes...
i can hardcode like this and it works on all 3 devices without any deprecation warnings...
File storageDir = new File("/storage/emulated/0/Pictures/");
but its probably even worse than using deprecated api?

How to fix '0 level missing for abstractListDefinition 0' error when using Emulator.getNumber()

I used docx4j to read the docx file. And I need to read the paragraph number format characters. I use Emulator.getNumber() to process, but I got this error. How should I deal with it?
try {
PPr pPr = ((P) p).getPPr();
if (pPr != null && pPr.getNumPr() != null) {
Emulator.ResultTriple triple = Emulator.getNumber(wordprocessingMLPackage, pPr);
if (triple != null) {
order = triple.getNumString();
}
}
} catch (Exception e) {
// throw error '0 level missing for abstractListDefinition 0'
e.printStackTrace();
}
Any help would be appreciated.Thanks.
docx4j version: 6.1.2
docx4j's html output uses it like so:
// Numbering
String numberText=null;
String numId=null;
String levelId=null;
if (pPrDirect.getNumPr()!=null) {
numId = pPrDirect.getNumPr().getNumId()==null ? null : pPrDirect.getNumPr().getNumId().getVal().toString();
levelId = pPrDirect.getNumPr().getIlvl()==null ? null : pPrDirect.getNumPr().getIlvl().getVal().toString();
}
ResultTriple triple = org.docx4j.model.listnumbering.Emulator.getNumber(
conversionContext.getWmlPackage(), pStyleVal, numId, levelId);
if (triple==null) {
getLog().debug("computed number ResultTriple was null");
} else {
if (triple.getBullet() != null) {
//numberText = (triple.getBullet() + " ");
numberText = "\u2022 ";
} else if (triple.getNumString() == null) {
getLog().error("computed NumString was null!");
numberText = ("?");
} else {
numberText = (triple.getNumString() + " ");
}
}
if (numberText!=null) {
currentParent.appendChild(document.createTextNode(
numberText + " "));
}
XSL-FO output:
if (pPrDirect!=null && pPrDirect.getNumPr()!=null) {
triple = org.docx4j.model.listnumbering.Emulator.getNumber(
conversionContext.getWmlPackage(), pStyleVal,
pPrDirect.getNumPr().getNumId().getVal().toString(),
pPrDirect.getNumPr().getIlvl().getVal().toString() );
} else {
// Get the effective values; since we already know this,
// save the effort of doing this again in Emulator
Ilvl ilvl = pPr.getNumPr().getIlvl();
String ilvlString = ilvl == null ? "0" : ilvl.getVal().toString();
triple = null;
if (pPr.getNumPr().getNumId()!=null) {
triple = org.docx4j.model.listnumbering.Emulator.getNumber(
conversionContext.getWmlPackage(), pStyleVal,
pPr.getNumPr().getNumId().getVal().toString(),
ilvlString );
}
}

How to move map marker like moving car on road from source to destination

I want to move marker on Google map from source to destination like Uber or Ola and i am working on google map, I am new so Please help me how it is possible ...?
My code is :
public void onMapReady(GoogleMap googleMap) {
GoogleMap gMap = googleMap;
addMarks1(gMap);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
gMap.setMyLocationEnabled(true);
gMap.getUiSettings().setZoomControlsEnabled(true);
// Turns on 3D buildings
gMap.setBuildingsEnabled(true);
}
private void addMarks1(GoogleMap googleMap) {
googleMap.clear();
// updateRouteOnMAp();
double d_lat=Double.valueOf(rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_START_LAT));
double d_loing=Double.valueOf(rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_START_LNG));
fromPosition=new LatLng(d_lat,d_loing);
toPosition=new LatLng(Double.valueOf(rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_END_LAT)),
Double.valueOf(rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_END_LNG)));
List<Marker> markersList = new ArrayList<Marker>();
Marker StartLatLon= googleMap.addMarker(new MarkerOptions().position(fromPosition).title("Start Point").icon(BitmapDescriptorFactory.fromResource(R.drawable.red_car_image)));
Marker EndLatLon= googleMap.addMarker(new MarkerOptions().position(toPosition).icon(BitmapDescriptorFactory.fromResource(R.drawable.red_car_image)));
markersList.add(StartLatLon);
markersList.add(EndLatLon);
builder = new LatLngBounds.Builder();
for (Marker m : markersList) {
builder.include(m.getPosition());
}
int padding = 150;
LatLngBounds bounds = builder.build();
cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
googleMap.animateCamera(cu);
traceMe(googleMap);
}
private void traceMe(final GoogleMap googleMap) {
String srcParam;
String destParam;
String startLat=rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_START_LAT);
String startLng=rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_START_LNG);
GPSTracker gpsTracker=new GPSTracker(getActivity());
srcParam = startLat + "," + startLng;
destParam = gpsTracker.getLatitude() + "," + gpsTracker.getLongitude();
Log.d("drop lat pp2", ":" + destParam);
String modes[] = {"driving", "walking", "bicycling", "transit"};
String url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + srcParam + "&destination=" + destParam + "&sensor=false&units=metric&mode=driving";
StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("dkp lat long", ":" + response);
JSONObject jsonObject=null;
try {
jsonObject=new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
MapDirectionsParser parser = new MapDirectionsParser();
List<List<HashMap<String, String>>> routes = parser.parse(jsonObject);
for (int i = 0; i < routes.size(); i++) {
points = new ArrayList<LatLng>();
List<HashMap<String, String>> path = routes.get(i);
Log.d("dkp lat long", ":" + path);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
}
Log.d("dkp points lat long", ":" + points);
drawPoints(points, googleMap);
String str_dist=parser.distance();
//String str_dur=parser.duration();
if (!str_dist.equals("null"))
{
distance= Integer.parseInt(str_dist);
//estimate_distance= (distance/100)+50;
//rideEstimateDistance.setText((estimate_distance-50)+"-"+estimate_distance);
Log.d("dkp kkk distance", ":" + distance);
}
/*if (!str_dur.equals("null"))
{
int duration=Integer.parseInt(parser.duration());
estimate_duration= duration/60;
ideEstimateDistance.setText((estimate_distance-50)+"-"+estimate_distance);
Log.d("dkp kkk duration", ":" + duration);
}*/
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Log.d("error ocurred", "TimeoutError");
//Toast.makeText(getActivity(), "TimeoutError", Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
Log.d("error ocurred", "AuthFailureError");
//Toast.makeText(getActivity(), "AuthFailureError", Toast.LENGTH_LONG).show();
} else if (error instanceof ServerError) {
Log.d("error ocurred", "ServerError");
// emailEdt.requestFocus();
// Toast.makeText(getActivity(), "Please enter valid email or password", Toast.LENGTH_LONG).show();
// Toast.makeText(getActivity(), "ServerError", Toast.LENGTH_LONG).show();
} else if (error instanceof NetworkError) {
Log.d("error ocurred", "NetworkError");
//Toast.makeText(getActivity(), "NetworkError", Toast.LENGTH_LONG).show();
} else if (error instanceof ParseError) {
Log.d("error ocurred", "ParseError");
//Toast.makeText(getActivity(), "ParseError", Toast.LENGTH_LONG).show();
}
}
});
// MyApplication.getInstance().addToRequestQueue(jsonObjectRequest, "jreq");
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonObjectRequest);
}
private void drawPoints(ArrayList<LatLng> points, GoogleMap mMaps) {
if (points == null) {
return;
}
traceOfMe = points;
PolylineOptions polylineOpt = new PolylineOptions();
for (LatLng latlng : traceOfMe) {
polylineOpt.add(latlng);
}
polylineOpt.color(Color.BLUE);
if (mPolyline != null) {
mPolyline.remove();
mPolyline = null;
}
if (mMaps != null) {
mPolyline = mMaps.addPolyline(polylineOpt);
} else {
}
if (mPolyline != null)
mPolyline.setWidth(7);
}
You will have to remove the marker from the map using googleMap.clear() and redraw it again in the new location.