【问题标题】:Attempt to invoke virtual method. App to display Location尝试调用虚方法。显示位置的应用程序
【发布时间】:2014-07-27 10:00:43
【问题描述】:

我正在尝试制作一个显示设备当前(或最后已知位置)的 Android 应用程序。 这是 logcat 中显示的错误:

07-27 14:47:53.766: E/AndroidRuntime(28080): 由: java.lang.NullPointerException:尝试调用虚拟方法 空对象上的“双 android.location.Location.getLatitude()” 参考

这是我的java代码:

package com.example.autosilence;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView lat = (TextView)findViewById(R.id.lat);
    TextView lon = (TextView)findViewById(R.id.lon);
    int b,c;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

        Location lastLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (lastLocation != null)
        {
            lat.setText(Double.toString(lastLocation.getLatitude()));
            lon.setText(Double.toString(lastLocation.getLongitude()));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

我已经在 android 清单中允许了精细和粗糙位置的权限。 为什么会这样?

【问题讨论】:

    标签: java android geolocation


    【解决方案1】:

    这可能无法解决问题,但您会在布局膨胀之前找到视图。移动

    TextView lat = (TextView)findViewById(R.id.lat);
    TextView lon = (TextView)findViewById(R.id.lon);
    

    onCreate 的内部,在setContentView() 之后。

    【讨论】:

    • 是的,你当然是对的!但这并不能解决另一个问题。还是谢谢!
    【解决方案2】:

    您是在使用模拟器还是设备来测试您的代码?

    模拟器无法检测到您的当前位置并在初始坐标中返回 null,因为您的系统不包含 GPS。所以它返回一个nullPointerException。您需要先在模拟器中配置 GPS 设置,然后再在那里运行您的定位服务代码或尝试在设备上运行它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      • 2017-01-06
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多