Я попытался инициализировать LocationManager
и использовать Button
, чтобы получить место, полученное в качестве Toast
на экране, однако я считаю, что LocationManager равна нулю:LocationManager является недействительным после инициализации
/MyLocationTest: Не удалось инициализировать LocationManager
java.lang.NullPointerException
at com.example.mylocationtest.MainActivity$1.onClick(MainActivity.java:46)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Первая строка является сообщением, что я печатаю на Logcat
потому что LocationManager
является недействительным, даже если я инициализировать его, как это в onCreate
:
locMan=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
//set a click listener for the button:
btn_loc.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v)
{
boolean isGPSReady,isNetworkReady;
if(locMan==null)
{
Log.d("MyLocationTest", "Failed to initialize LocationManager");
}
isGPSReady=locMan.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkReady=locMan.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isNetworkReady && !isGPSReady)
{
Toast.makeText(getBaseContext(),"Sorry,location could not be enabled",Toast.LENGTH_SHORT).show();
}
else if(isNetworkReady)
{
//the third parameter is a looper that controls where the callback happens from...
locMan.requestSingleUpdate(LocationManager.NETWORK_PROVIDER,locEar_network, null);
latitude=loc.getLatitude();
longitude=loc.getLongitude();
Toast.makeText(getBaseContext(),"The latitude is "+latitude+" and the longitude is "+longitude+" and the accuracy is "+loc.getAccuracy(),Toast.LENGTH_SHORT).show();
}
else if(isGPSReady)
{
locMan.requestSingleUpdate(LocationManager.GPS_PROVIDER,locEar_gps,null);
latitude=loc.getLatitude();
longitude=loc.getLongitude();
Toast.makeText(getBaseContext(),"The latitude is "+latitude+" and the longitude is "+longitude+ "and the accuracy is "+loc.getAccuracy(),Toast.LENGTH_SHORT).show();
}
}
});
В моем манифесте, я использовал следующую команду, чтобы убедиться, что уровень API 9, является minSDKVersion для requestSingleUpdate
и приложение разрешается доступ к прекрасному местоположению:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mylocationtest" >m
<uses-sdk android:minSdkVersion="9"
android:targetSdkVersion="18"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
EDIT:
The entire class is here as a pastebin
Как я могу гарантировать, что LocationManager никогда не имеет значения null?
Вы не показывают код, где "LOC" (от которого вы звоните loc.getLatitude)() инициализируется. Я предполагаю, что это то, что является нулевым. Вероятно, вам нужно ждать выполнения onLocationChanged(). – NickT
, к чему относится ваш 'this'? – user3322955
это в 'onCreate', поэтому оно относится к' Activity' – vamsiampolu