我有一个非常简单的类,它查找最后一个已知的用户坐标,然后打印其中一个。但我将loc作为空变量。应用程序没有将数据读入loc变量。

    import android.app.Activity;
    import android.content.Context;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.widget.Toast;

    public class Navigation extends Activity
    {
      /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle savedInstanceState)
      {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        /* Use the LocationManager class to obtain GPS locations */
        try
        {
            LocationManager mlocManager =
              (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            Toast.makeText(getBaseContext(),
                  "Provider Enable Status : " + mlocManager.isProviderEnabled(
                   mlocManager.getProvider("gps").getName()),
                   Toast.LENGTH_LONG).show();

            Location loc = mlocManager.getLastKnownLocation("gps");
            Toast.makeText( getApplicationContext(), "" +
                loc.getLatitude(),  Toast.LENGTH_LONG).show();
            Toast.makeText( getApplicationContext(), "" + loc,
                Toast.LENGTH_LONG).show();
         } catch (Exception e) {
           Toast.makeText(getBaseContext(), e.getMessage() +
             e.toString(), Toast.LENGTH_LONG).show();
         }
      }
   }

我已将以下侦听器添加到代码中:
        LocationListener mlocListener = new MyLocationListener();

        mlocManager.requestLocationUpdates( mlocManager.getProvider("gps").getName(), 0, 0, mlocListener);

在oncreate函数中。以下是作为
public class MyLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location loc) {
        Toast.makeText( getApplicationContext(),
            "Hi, location changed. :)", Toast.LENGTH_LONG).show();
        try {
        loc.getLatitude();
        loc.getLongitude();
        String Text = "My current location is: " +
                " Latitude = " + loc.getLatitude() +
                " Longitude = " + loc.getLongitude();
        Toast.makeText(getApplicationContext(),
                Text, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(),
                e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
}

运行完窗口后,我会执行以下操作:
转到eclipse中的ddms并设置晶格/长震级,然后单击send。
它仍然不会在函数中启动任何toast命令。

最佳答案

你可以做空检查,这绝对是解决这个问题的好方法。另一个技巧是在onresume()调用活动时使用以下命令请求位置更新:

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10f,this);
    super.onResume();
}

对于mlocmanager,请确保将其创建为实例变量(类级别)而不是本地变量(在方法中未定义,在oncreate中则为)。
这肯定会获取位置更新,而不会抛出空指针。还要确保geofix您的gps配置模拟器。使用DDMS的Emulator控件弹出按钮执行此操作。在启动活动之前,请修复一些经度和纬度值。
希望这有帮助!

07-28 03:53
查看更多