acitivity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_height="fill_parent" android:layout_width="fill_parent"> <fragment android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" android:name="com.google.android.gms.maps.SupportMapFragment"/> </RelativeLayout>
MainActivity.java
public class MainActivity extends FragmentActivity { GoogleMap map; Location currentLocation; LocationManager manager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); MapsInitializer.initialize(this); } @Override public void onResume() { super.onResume(); if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Location Manager"); builder.setMessage("位置情報をONにしますか?"); builder.setPositiveButton("はい", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); moveToYourLocation(); } }); builder.setNegativeButton("いいえ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); builder.create().show(); } else { moveToYourLocation(); } } protected void moveToYourLocation(){ CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(new LatLng((float)currentLocation.getLatitude(), (float)currentLocation.getLongitude()), 13); map.moveCamera(cu); }
GPS機能がONになっていない場合はダイアログを表示して、ONにするように促します。
OFFの場合はアプリを終了させます。
ONになった後に自分の位置情報をマップに反映させ表示したいのですが、問題が発生したとされ強制終了されます。
moveToYourLocation()がnullだと表示されるのですが、失敗する原因が良く分かりません。
どこが間違っているのでしょうか?
----追記のエラーログです----
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.examples.mymapactivity.MainActivity.moveToYorLocation(MainActivity.java:65)
at com.examples.mymapactivity.MainActivity$1.onClick(MainActivity.java:48)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:160)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5335)
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:1016)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/09/20 14:02
2015/09/20 14:21
2015/09/20 15:02
2015/09/20 15:21
2015/09/21 03:15