【问题标题】:Android Studios LocationAndroid 工作室位置
【发布时间】:2016-11-14 11:39:44
【问题描述】:

我正在尝试创建一个小应用程序,它可以定位用户当前所在的 x 和 y 坐标。问题是我在第 143 行不断收到一个空指针异常。

double lon = loc.getLongitude();

我认为我的 getLastKnownLocation() 返回 null。我正在通过虚拟设备运行它。代码如下。

package com.team23.profilebuilder;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.util.Log;
import android.location.LocationManager;

import java.util.List;

public class FindLocationActivity extends CustomActivity
{

// Buttons to be used
private Button locButton, saveButton;
// Textview to be displayed / used
private TextView locText, latText, longText, latVal, longVal;
// Location objects
private LocationManager locMan;
private LocationListener locLis;
private Location loc;

private static final String TAG = "FindLocationActivity";


@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_find_location);

    // Initialise all elements
    initialiseUIElements();
    initialiseOtherElements();

    // Set button listeners
    setListeners();
}

private void initialiseUIElements()
{
    locButton = (Button) findViewById(R.id.locButton);
    saveButton = (Button) findViewById(R.id.saveButton);
    locText = (TextView) findViewById(R.id.locText);
    latText = (TextView) findViewById(R.id.latText);
    longText = (TextView) findViewById(R.id.longText);
    latVal = (TextView) findViewById(R.id.latVal);
    longVal = (TextView) findViewById(R.id.longVal);
}

private void initialiseOtherElements()
{
    // Acquire a reference to the system LocationManager
    locMan = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    // Define a listener which responds to location updates
    locLis = new LocationListener()
    {
        // Method called when a new location is found
        @Override
        public void onLocationChanged(Location location)
        {
            loc = location;
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle)
        {

        }

        @Override
        public void onProviderEnabled(String s)
        {

        }

        @Override
        public void onProviderDisabled(String s)
        {

        }
    };
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    // Register the listener with Location Manager to receive updates
    locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locLis);
}

private void setListeners()
{
    locButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            findLocation();
        }
    });
    saveButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            saveLocation();
        }
    });
}

private void findLocation()
{
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    // Retrieve last known location
    loc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    // Retrieve values
    double lon = loc.getLongitude();
    double lat = loc.getLatitude();

    // Set TextView values
    longVal.setText(Double.toString(lon));
    latVal.setText(Double.toString(lat));
}

private void saveLocation()
{
    Log.v(TAG, "SaveLocation Method");
}
}

【问题讨论】:

  • 像这样检查空值,if(location!=null){ double latitude = location.getLatitude();双经度 = location.getLongitude(); }
  • 问题是它是空的,我希望它真正找到位置,我已经知道它是空的,因为这就是导致我的异常的原因。
  • 我已经学习了一些教程,这些教程使我达到了这一点,但我现在正在寻找有关我的问题的具体帮助,我已经阅读了 3-4 个不同的教程,它们的解释都不同,我已经被这个问题困扰了好几天了。
  • Android Hive 示例很糟糕,正如here 所解释的那样。正如herehere 所解释的那样,最新位置可以为空。尤其是在虚拟设备上,除非该虚拟设备具有某种模拟位置提供程序,否则它将为空。

标签: android android-studio location


【解决方案1】:

我在没有运行时权限的情况下使用目标 22 测试了下面的源代码,它对我来说很好。

检查 null 以获取 Location,并检查您设备中的 GPS 是否已打开。..

package com.team23.profilebuilder;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.util.Log;
import android.location.LocationManager;

import java.util.List;

public class FindLocationActivity extends CustomActivity
{

// Buttons to be used
private Button locButton, saveButton;
// Textview to be displayed / used
private TextView locText, latText, longText, latVal, longVal;
// Location objects
private LocationManager locMan;
private LocationListener locLis;
private Location loc;

private static final String TAG = "FindLocationActivity";


@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_find_location);

    // Initialise all elements
    initialiseUIElements();
    initialiseOtherElements();

    // Set button listeners
    setListeners();
}

private void initialiseUIElements()
{
    locButton = (Button) findViewById(R.id.locButton);
    saveButton = (Button) findViewById(R.id.saveButton);
    locText = (TextView) findViewById(R.id.locText);
    latText = (TextView) findViewById(R.id.latText);
    longText = (TextView) findViewById(R.id.longText);
    latVal = (TextView) findViewById(R.id.latVal);
    longVal = (TextView) findViewById(R.id.longVal);
}

private void initialiseOtherElements()
{
    // Acquire a reference to the system LocationManager
    locMan = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    // Define a listener which responds to location updates
    locLis = new LocationListener()
    {
        // Method called when a new location is found
        @Override
        public void onLocationChanged(Location location)
        {
            loc = location;
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle)
        {

        }

        @Override
        public void onProviderEnabled(String s)
        {

        }

        @Override
        public void onProviderDisabled(String s)
        {

        }
    };
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    // Register the listener with Location Manager to receive updates
    locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locLis);
}

private void setListeners()
{
    locButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            findLocation();
        }
    });
    saveButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            saveLocation();
        }
    });
}

private void findLocation()
{
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    // Retrieve last known location
    loc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

   if (loc!=null) {
        // Retrieve values
        double lon = loc.getLongitude();
        double lat = loc.getLatitude();
        // Set TextView values
        longVal.setText(Double.toString(lon));
        latVal.setText(Double.toString(lat));
    }
}

private void saveLocation()
{
    Log.v(TAG, "SaveLocation Method");
}
}

【讨论】:

    猜你喜欢
    • 2020-11-13
    • 2017-07-21
    • 2020-06-16
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多