首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Android Studios位置

Android Studios位置
EN

Stack Overflow用户
提问于 2016-11-14 19:39:45
回答 1查看 99关注 0票数 0

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

代码语言:javascript
运行
复制
double lon = loc.getLongitude();

我想我的getLastKnownLocation()返回了null。我正在通过一个虚拟设备运行它。下面的代码。

代码语言:javascript
运行
复制
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");
}
}
EN

回答 1

Stack Overflow用户

发布于 2016-11-14 20:22:26

我在没有运行时许可的情况下用target 22测试了下面的源代码,它对我来说很好。

检查null Location,并检查设备中是否已打开GPS。

代码语言:javascript
运行
复制
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");
}
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40587880

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档