[英]How to show values when the activity is launched in android
嗨,我是一名新开发人员。 在我的应用中,我试图显示某个地方的纬度和经度。 当应用启动时,我自动希望显示值。以下是我的代码。
{
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 " />
以表达自己的意思。
看来您没有获得有效的位置。
您是否打开了GPS?
如果仅在Emulator上运行它,则必须在DDMS-> Emulator Control-> Location Controls中设置位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.