- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我想要做的就是让用户获得他喜欢的类型的位置列表。例如,如果输入是医院,我的应用程序将使用搜索字符串“医院”打开谷歌地图。但正如文档中所建议的那样,使用像 geo:0,0?q=hospital
这样的地理编码 uri 显示坐标 0 纬度和 0 经度附近的所有医院。因此,当我尝试使用以下代码首先获取用户坐标时。
Places Decoder.java
package com.kkze.Mappy;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
public class PlacesDecoder extends Activity {
Intent intentThatCalled;
public double latitude;
public double longitude;
public LocationManager locationManager;
public Criteria criteria;
public String bestProvider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intentThatCalled = getIntent();
String voice2text = intentThatCalled.getStringExtra("v2txt");
getLocation(voice2text);
}
public static boolean isLocationEnabled(Context context)
{
int locationMode = 0;
String locationProviders;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
try
{
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}
else
{
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
public void getLocation(String voice2txt) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
Location location = locationManager.getLastKnownLocation(bestProvider);
if (isLocationEnabled(PlacesDecoder.this)) {
Log.e("TAG", "GPS is on");
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(PlacesDecoder.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
searchNearestPlace(voice2txt);
}
else
{
AlertDialog.Builder notifyLocationServices = new AlertDialog.Builder(PlacesDecoder.this);
notifyLocationServices.setTitle("Switch on Location Services");
notifyLocationServices.setMessage("Location Services must be turned on to complete this action. Also please take note that if on a very weak network connection, such as 'E' Mobile Data or 'Very weak Wifi-Connections' it may take even 15 mins to load. If on a very weak network connection as stated above, location returned to application may be null or nothing and cause the application to crash.");
notifyLocationServices.setPositiveButton("Ok, Open Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent openLocationSettings = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
PlacesDecoder.this.startActivity(openLocationSettings);
finish();
}
});
notifyLocationServices.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
notifyLocationServices.show();
}
}
public void searchNearestPlace(String v2txt) {
Log.e("TAG", "Started");
v2txt = v2txt.toLowerCase();
String[] placesS = {"accounting", "airport", "aquarium", "atm", "attraction", "bakery", "bakeries", "bank", "bar", "cafe", "campground", "casino", "cemetery", "cemeteries", "church", "courthouse", "dentist", "doctor", "electrician", "embassy", "embassies", "establishment", "finance", "florist", "food", "grocery", "groceries", "supermarket", "gym", "health", "hospital", "laundry", "laundries", "lawyer", "library", "libraries", "locksmith", "lodging", "mosque", "museum", "painter", "park", "parking", "pharmacy", "pharmacies", "physiotherapist", "plumber", "police", "restaurant", "school", "spa", "stadium", "storage", "store", "synagog", "synagogue", "university", "universities", "zoo"};
String[] placesM = {"amusement park", "animal care", "animal care", "animal hospital", "art gallery", "art galleries", "beauty salon", "bicycle store", "book store", "bowling alley", "bus station", "car dealer", "car rental", "car repair", "car wash", "city hall", "clothing store", "convenience store", "department store", "electronics store", "electronic store", "fire station", "funeral home", "furniture store", "gas station", "general contractor", "hair care", "hardware store", "hindu temple", "home good store", "homes good store", "home goods store", "homes goods store", "insurance agency", "insurance agencies", "jewelry store", "liquor store", "local government office", "meal delivery", "meal deliveries", "meal takeaway", "movie rental", "movie theater", "moving company", "moving companies", "night club", "pet store", "place of worship", "places of worship", "post office", "real estate agency", "real estate agencies", "roofing contractor", "rv park", "shoe store", "shopping mall", "subway station", "taxi stand", "train station", "travel agency", "travel agencies", "veterinary care"};
int index;
for (int i = 0; i <= placesM.length - 1; i++) {
Log.e("TAG", "forM");
if (v2txt.contains(placesM[i])) {
Log.e("TAG", "sensedM?!");
index = i;
Uri gmmIntentUri = Uri.parse("geo:" + latitude + "," + longitude + "?q=" + placesM[index]);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
finish();
}
}
for (int i = 0; i <= placesS.length - 1; i++) {
Log.e("TAG", "forS");
if (v2txt.contains(placesS[i])) {
Log.e("TAG", "sensedS?!");
index = i;
Uri gmmIntentUri = Uri.parse("geo:" + latitude + "," + longitude + "?q=" + placesS[index]);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
finish();
}
}
}
}
问题是位置始终返回 null。而且我知道一个事实,只要启用位置,另一个应用程序 Jarvis 就可以轻松完成任务,如果没有,则只是要求用户这样做。但在相同条件下,我的应用程序总是崩溃。
我做了什么:
它仍然发生。我是 Android 的初学者。请,请帮助我。没有办法解决我的问题吗?甚至认为其他应用程序以某种方式设法做到这一点。
这是我的 LogCat。
Process: com.kkze.Mappy, PID: 6742
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.kkze.Mappy/com.kkze.Mappy.PlacesDecoder}: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.kkze.Mappy.PlacesDecoder.getLocation(PlacesDecoder.java:62)
at com.kkze.Mappy.PlacesDecoder.onCreate(PlacesDecoder.java:32)
at android.app.Activity.performCreate(Activity.java:6221)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
同时检查 location!=null 需要 ACCESS_FINE_LOCATION 权限,这会扰乱我的应用,导致它始终返回 null。
最佳答案
正如 Jon Skeet 在评论中提到的,getLastKnownLocation()
方法可以而且将会返回 null。主要问题是它不会提示操作系统请求新的位置锁定,而只是检查是否有来自其他应用程序位置请求的最后一个已知位置。如果最近没有其他应用发出位置请求,则会向您返回一个空位置。
保证您实际获得位置的唯一方法是请求一个位置,这是通过调用 requestLocationUpdates()
来完成的.
传递给 onLocationChanged()
回调方法的位置不会为 null,因为回调仅发生在成功的位置锁定时。
请注意,在您的应用注册位置更新的整个过程中,它会导致额外的电池消耗,因此请务必尽快取消注册位置更新。在这里,您似乎可以在第一个位置出现后立即取消注册。
此外,您可能需要考虑在此 Activity 等待位置锁定时显示一个进度对话框,以便向用户提供应用正在等待某事的一些反馈。
这是您的代码的一般结构:
public class MainActivity extends Activity
implements LocationListener {
Intent intentThatCalled;
public double latitude;
public double longitude;
public LocationManager locationManager;
public Criteria criteria;
public String bestProvider;
String voice2text; //added
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentThatCalled = getIntent();
voice2text = intentThatCalled.getStringExtra("v2txt");
getLocation();
}
public static boolean isLocationEnabled(Context context)
{
//...............
return true;
}
protected void getLocation() {
if (isLocationEnabled(MainActivity.this)) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
//You can still do this if you like, you might get lucky:
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
Log.e("TAG", "GPS is on");
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
searchNearestPlace(voice2text);
}
else{
//This is what you need:
locationManager.requestLocationUpdates(bestProvider, 1000, 0, this);
}
}
else
{
//prompt user to enable location....
//.................
}
}
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
@Override
public void onLocationChanged(Location location) {
//Hey, a non null location! Sweet!
//remove location callback:
locationManager.removeUpdates(this);
//open the map:
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
searchNearestPlace(voice2text);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
public void searchNearestPlace(String v2txt) {
//.....
}
}
关于java - 在空对象引用上调用虚拟方法 'double android.location.Location.getLatitude()' 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32290045/
我正在尝试在 python 中编写正则表达式来查找目录路径:我的文本如下所示: text = "The public disk is: \\\\diskA\\FolderB\\SubFolderC\\
我想写一个LocationListener,它把最近最精确的位置作为它的位置。我打算在我的 LocationListener 中使用此代码: @Override public void
我想建立一个有光泽和 plotly 的交互式图表。 Shiny 有一个内置功能来获取有关用户交互的信息。比如:input$plot_click、input$plot_dblclick、input$pl
我正在使用 MobileFirst 提供的 WL.Device.Geo.acquirePosition(onGeoLocationSuccess, onGeoLocationFailure, opti
我最近开始使用 ionic 框架,它里面有 angular js。为了在屏幕之间导航,我使用了 $location.path 并且效果很好。但是,在我下载的一个示例中,我看到 $state.go 被用
谁能解释一下这种行为?我使用 history.pushState(null, null, '#test'); 推送历史状态。然后,当尝试使用console.log(window.location.ha
这里是相关代码: https://www.facebook.com/sharer/sharer.php?u={{$location.absUrl()}} https://www.facebook.c
这两个重定向之间有什么区别?我有一个应用程序,当我使用时,它可以在 chrome 和 android 4 上正常工作,但在 android 2.x.x 上不能正常工作 document.locatio
JavaScript 的区别是什么 window.location.href = window.location.href 和 window.location.reload() 功能? 最佳答案 如果
有什么区别 window.location.href="http://example.com"; window.location.replace("http://example.com"); wind
JavaScript 的区别是什么 window.location.href = window.location.href 和 window.location.reload() 功能? 最佳答案 如果
以下 3 个指令之间有区别吗? location ~* \.(png)$ { expires max; log_not_found off; } location ~ \.(png)$ {
位于正文末尾之前的以下脚本在 Internet Explorer 和 Chrome(以及任何其他浏览器)中都会被调用。但重定向到指定的 URL 仅发生在 IE 中。我还尝试了 window.locat
我正在使用 Angular ngRouter。我需要更改 url 路径以及搜索参数。我知道 $location.path 和 $location.search,但是有没有一个函数可以同时设置它们? 最
在angularjs中用$location和window.location哪个更好。 例如,我们可以使用$location.path() 或window.location.href 来完成同样的工作。
我在我的网站上使用上述 2 个命令。似乎它们对 95% 访问它应该触发的页面的人有效,但对其他人则不会。 有谁知道是否可以完全阻止这些 javascript 命令?我真的很头疼为什么它们有时不起作用。
这是我无法弄清楚的另一个错误。 我有这个类ExtendedLocation extends Location实例化时抛出 ClassCastExceptioncurrentGpsLocation =
我一直在尝试简单地将一个包含两个变量(一个字符串和一个位置)的类推送和读取到 firebase,但我一直收到此错误。 **com.google.firebase.database.DatabaseEx
我注意到 iPhone 上的“常用位置”似乎比监控 iOS 访问的应用程序 (https://developer.apple.com/reference/corelocation/clvisit) 使
在我的 javascript 代码中,在某些时候,我需要刷新窗口(用户上传了新图片但在页面中仍然可以看到它) 我想知道为什么 location.href = location.href 不刷新窗口?
我是一名优秀的程序员,十分优秀!