嗨,我是一名新开发人员。在我的应用程序中,我试图显示一个地方的纬度和经度。当应用程序启动时,我希望自动显示值以下是我的代码。
{
setContentView(R.layout.main);
if(entered)
{
loadCoords();
}
Coords coords = loadCoords();
}
private Coords loadCoords()
{
TextView latText = (TextView) findViewById(R.id.latText);
TextView lngText = (TextView) findViewById(R.id.lngText);
LocationManager myManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if(myManager != null){
//List list = myManager.getAllProviders();
String param = (String)myManager.getProviders(true).get(0);
Location loc = myManager.getLastKnownLocation(param);
if(loc != null){
Double latPoint = loc.getLatitude();
Double lngPoint = loc.getLongitude();
try {
latText.setText(latPoint.toString());
lngText.setText(lngPoint.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
else
Log.e("AndroidMaps ","Error: Location is null");
}
else
Log.e("AndroidMaps ","Error: Location Manager is null");
return null;
}
}
但是当我尝试在设备中运行我的应用程序时,它崩溃了。
以下是logcat中显示的错误
ERROR/AndroidRuntime(6311): Uncaught handler: thread main exiting due to uncaught exception
ERROR/AndroidRuntime(6311): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gis.ss/com.gis.ss.main}: java.lang.IndexOutOfBoundsException: Invalid location 0, size is 0
ERROR/AndroidRuntime(6311): Caused by: java.lang.IndexOutOfBoundsException: Invalid location 0, size is 0
谁能解释一下错误是什么......plzzz
最佳答案
您可能在这里得到空列表:
String param = (String)myManager.getProviders(true).get(0);
并尝试获取列表中的第一个会导致 java.lang.IndexOutOfBoundsException
尝试添加
<uses-permission android:name="android.permission.ACCESS_GPS" />
和<uses-permission android:name="android.permission.ACCESS_LOCATION " />
到你的菜单。
关于java - 如何在android中启动 Activity 时显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5389497/