【问题标题】:NullPointerException while fetching current GPS获取当前 GPS 时出现 NullPointerException
【发布时间】:2014-02-27 03:03:06
【问题描述】:

我有一个测试屏幕,其中有一个按钮 - 按下它会调用服务。我正在尝试实现一种方法来获取当前用户的当前 gps 位置,并且在尝试调用时崩溃。谁能告诉我是什么问题?

package com.example.whereyouapp;

import java.util.Arrays;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.widget.Toast;

public class Controller extends Service{

private static final int POLL_INTERVAL = 1000 *3;

static int number_of_times=0;

Location location;
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      // Called when a new location is found by the network location provider.
      makeUseOfNewLocation(location);
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}

    public void onProviderEnabled(String provider) {}

    public void onProviderDisabled(String provider) {}
  };

public void makeUseOfNewLocation(Location location){
    this.location=location;
}

public static double coordinatesDistance(double lat1, double lon1, double lat2, double lon2){//returns distance in kilometers between two coordiantes
    double deltaLat = Math.toRadians(lat2-lat1);
    double deltaLong = Math.toRadians(lon2 - lon1);
    lat1 = Math.toRadians(lat1);
    lat2 = Math.toRadians(lat2);
    double a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) + Math.sin(deltaLong / 2) * Math.sin(deltaLong / 2) * Math.cos(lat1) * Math.cos(lat2);
    double c = 2 * Math.asin(Math.sqrt(a));
    return 6371 * c; 
}

public int onStartCommand(Intent intent,int flags, int startId){
    Toast.makeText(this, "yololo- the service class works", Toast.LENGTH_SHORT).show();
    //sendSMS("5613500110","If you received this text message then the Service class for WhereYouApp works");

            // Register the listener with the Location Manager to receive location updates
                 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 0, locationListener);

            if(location!=null){
            double distance=coordinatesDistance(location.getLatitude(),location.getLatitude(),location.getLatitude()+2,location.getLatitude()+2);

            Toast.makeText(this, ""+distance, Toast.LENGTH_SHORT).show();
            }

    if(number_of_times==5){
        setServiceAlarm(getBaseContext(),false);
        number_of_times=-1;
    }
    number_of_times++;
    return START_STICKY;
}

public void onDestroy(){
    super.onDestroy();
    Toast.makeText(this, "yolo- the service has stopped working", Toast.LENGTH_LONG).show();
}

public void sendSMS(String phoneNumber, String message) {
    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phoneNumber, null, message, null, null);
    ContentValues values = new ContentValues(); 
    values.put("address", phoneNumber); 
    values.put("body", message); 
    getContentResolver().insert(Uri.parse("content://sms/sent"), values);
}

public static void setServiceAlarm(Context context, boolean isOn){

        Intent i = new Intent(context, Controller.class);
        PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
        AlarmManager alarmManager =        (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        if (isOn) {
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis(), POLL_INTERVAL, pi);
        } else {
            alarmManager.cancel(pi);
            pi.cancel();
        }
}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}
 }

这个类将用于测试控制器功能,它将由一个带有按钮的屏幕组成,这些按钮可以执行各种功能

package com.example.whereyouapp;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.view.View;
import android.widget.Button;

public class ControllerTestingScreen extends Activity{
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_controller_test_screen);
    //Set button colors to red, green, blue, and red, respectively
    Button button = (Button) findViewById(R.id.testbutton);
    button.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
    OnClickListener buttonListener = new View.OnClickListener(){
        public void onClick(View arg0) {

            Controller.setServiceAlarm(getBaseContext(), true);
        }
    };
    button.setOnClickListener(buttonListener);
}
}

Logcat:

    02-26 22:04:38.317: D/AndroidRuntime(1427): Shutting down VM
02-26 22:04:38.317: W/dalvikvm(1427): threadid=1: thread exiting with uncaught exception (group=0xb1a91ba8)
02-26 22:04:38.457: D/dalvikvm(1427): GC_FOR_ALLOC freed 115K, 6% free 3270K/3460K, paused 87ms, total 103ms
02-26 22:04:38.497: E/AndroidRuntime(1427): FATAL EXCEPTION: main
02-26 22:04:38.497: E/AndroidRuntime(1427): Process: com.example.whereyouapp, PID: 1427
02-26 22:04:38.497: E/AndroidRuntime(1427): java.lang.RuntimeException: Unable to instantiate service com.example.whereyouapp.Controller: java.lang.NullPointerException
02-26 22:04:38.497: E/AndroidRuntime(1427):     at android.app.ActivityThread.handleCreateService(ActivityThread.java:2556)
02-26 22:04:38.497: E/AndroidRuntime(1427):     at android.app.ActivityThread.access$1800(ActivityThread.java:135)
02-26 22:04:38.497: E/AndroidRuntime(1427):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
02-26 22:04:38.497: E/AndroidRuntime(1427):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-26 22:04:38.497: E/AndroidRuntime(1427):     at android.os.Looper.loop(Looper.java:136)
02-26 22:04:38.497: E/AndroidRuntime(1427):     at android.app.ActivityThread.main(ActivityThread.java:5017)
02-26 22:04:38.497: E/AndroidRuntime(1427):     at java.lang.reflect.Method.invokeNative(Native Method)
02-26 22:04:38.497: E/AndroidRuntime(1427):     at java.lang.reflect.Method.invoke(Method.java:515)
02-26 22:04:38.497: E/AndroidRuntime(1427):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-26 22:04:38.497: E/AndroidRuntime(1427):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-26 22:04:38.497: E/AndroidRuntime(1427):     at dalvik.system.NativeStart.main(Native Method)
02-26 22:04:38.497: E/AndroidRuntime(1427): Caused by: java.lang.NullPointerException
02-26 22:04:38.497: E/AndroidRuntime(1427):     at android.content.ContextWrapper.getSystemService(ContextWrapper.java:540)
02-26 22:04:38.497: E/AndroidRuntime(1427):     at com.example.whereyouapp.Controller.<init>(Controller.java:30)
02-26 22:04:38.497: E/AndroidRuntime(1427):     at java.lang.Class.newInstanceImpl(Native Method)
02-26 22:04:38.497: E/AndroidRuntime(1427):     at java.lang.Class.newInstance(Class.java:1208)
02-26 22:04:38.497: E/AndroidRuntime(1427):     at android.app.ActivityThread.handleCreateService(ActivityThread.java:2553)
02-26 22:04:38.497: E/AndroidRuntime(1427):     ... 10 more
02-26 22:04:45.187: I/Process(1427): Sending signal. PID: 1427 SIG: 9
02-26 22:04:47.507: D/AndroidRuntime(1469): Shutting down VM
02-26 22:04:47.507: W/dalvikvm(1469): threadid=1: thread exiting with uncaught exception (group=0xb1a91ba8)
02-26 22:04:47.517: E/AndroidRuntime(1469): FATAL EXCEPTION: main
02-26 22:04:47.517: E/AndroidRuntime(1469): Process: com.example.whereyouapp, PID: 1469
02-26 22:04:47.517: E/AndroidRuntime(1469): java.lang.RuntimeException: Unable to instantiate service com.example.whereyouapp.Controller: java.lang.NullPointerException
02-26 22:04:47.517: E/AndroidRuntime(1469):     at android.app.ActivityThread.handleCreateService(ActivityThread.java:2556)
02-26 22:04:47.517: E/AndroidRuntime(1469):     at android.app.ActivityThread.access$1800(ActivityThread.java:135)
02-26 22:04:47.517: E/AndroidRuntime(1469):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
02-26 22:04:47.517: E/AndroidRuntime(1469):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-26 22:04:47.517: E/AndroidRuntime(1469):     at android.os.Looper.loop(Looper.java:136)
02-26 22:04:47.517: E/AndroidRuntime(1469):     at android.app.ActivityThread.main(ActivityThread.java:5017)
02-26 22:04:47.517: E/AndroidRuntime(1469):     at java.lang.reflect.Method.invokeNative(Native Method)
02-26 22:04:47.517: E/AndroidRuntime(1469):     at java.lang.reflect.Method.invoke(Method.java:515)
02-26 22:04:47.517: E/AndroidRuntime(1469):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-26 22:04:47.517: E/AndroidRuntime(1469):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-26 22:04:47.517: E/AndroidRuntime(1469):     at dalvik.system.NativeStart.main(Native Method)
02-26 22:04:47.517: E/AndroidRuntime(1469): Caused by: java.lang.NullPointerException
02-26 22:04:47.517: E/AndroidRuntime(1469):     at android.content.ContextWrapper.getSystemService(ContextWrapper.java:540)
02-26 22:04:47.517: E/AndroidRuntime(1469):     at com.example.whereyouapp.Controller.<init>(Controller.java:30)
02-26 22:04:47.517: E/AndroidRuntime(1469):     at java.lang.Class.newInstanceImpl(Native Method)
02-26 22:04:47.517: E/AndroidRuntime(1469):     at java.lang.Class.newInstance(Class.java:1208)
02-26 22:04:47.517: E/AndroidRuntime(1469):     at android.app.ActivityThread.handleCreateService(ActivityThread.java:2553)
02-26 22:04:47.517: E/AndroidRuntime(1469):     ... 10 more

【问题讨论】:

  • 您是否在 Manifest 文件中授予权限?
  • logcat 在 com.example.whereyouapp.Controller.(Controller.java:30) 非常清楚,问题是什么,为什么是问题?怎么会有人知道第 30 行在哪里?
  • 哇……好强悍的人群! Sid 可能在您的待定时进行了编辑,Ked(只是我的猜测)。
  • 被社区拒绝了♦ 所以,是的可能。
  • 让我们都退后一步。这只是一个编辑......不值得争论。 @Kedarnath,您可以通过单击个人资料中的“建议”选项卡并单击编辑来查看谁批准/拒绝了您的编辑。

标签: android gps location alarmmanager


【解决方案1】:

您在此行收到NPE

LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

因为您的Contextnull,因为Service 实际上尚未创建。将该行移到onStartCommand() 内。

很像Activity,在它启动之前没有Context。使用Activity,而不是在onCreate() 运行之前,使用Service,直到onCreate()onStartCommand() 才能使用。

See this answer 了解如何阅读您的 logcat。它会带你走很长的路。

【讨论】:

  • 它仍然给我服务内的 locationManager 错误
  • 这太糟糕了,但是,不知道是什么错误,我无能为力。除非我想用剩下的晚上来检查你的代码(我不想);)但我相信你最初的问题已经解决了。
  • 请不要让 cmets 那样。我想提供帮助,但这让我想提供的帮助要少得多……这是非常无益的。发布您遇到的错误会有所帮助。哦,通过查看我发布的链接,该链接显示了如何阅读您的 logcat。如果您想成为一名开发人员,这一点非常重要。
  • 我的模拟器上没有 gps,所以它会报错,所以我不知道是什么问题。虽然它仍然在我的手机上崩溃......
  • 在您的手机上调试。比模拟器更容易和更快。在不知道错误是什么的情况下,我真的无法帮助,而且我不会遍历代码的每一行并猜测问题是什么。
【解决方案2】:

我对您的代码进行了一些更改,最终得到了一个工作代码。

public class Controller extends Service 
{
    private static final int POLL_INTERVAL = 1000 *3;
    static int number_of_times=0;

    Location currentLocation;
    static LocationManager locationManager;
    // Define a listener that responds to location updates

    LocationListener locationListenerGps = new LocationListener() 
    {
        public void onLocationChanged(Location location) 
        {
            currentLocation = location;
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };


    public static double coordinatesDistance(double lat1, double lon1, double lat2, double lon2)
    {
        //returns distance in kilometers between two coordiantes
        double deltaLat = Math.toRadians(lat2-lat1);
        double deltaLong = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
        double a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) + Math.sin(deltaLong / 2) * Math.sin(deltaLong / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return 6371 * c; 
    }

    public int onStartCommand(Intent intent,int flags, int startId)
    {
        Toast.makeText(this, "yololo- the service class works", Toast.LENGTH_SHORT).show();
        //sendSMS("5613500110","If you received this text message then the Service class for WhereYouApp works");

        if ( locationManager != null )
        {
            System.out.println ( "not null" );
            // Register the listener with the Location Manager to receive location updates
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerGps);
        }

        if( currentLocation != null )
        {
            double distance=coordinatesDistance(currentLocation.getLatitude(),currentLocation.getLatitude(),currentLocation.getLatitude()+2,currentLocation.getLatitude()+2);
            Toast.makeText(this, ""+distance, Toast.LENGTH_SHORT).show();
        }
        else
        {
            System.out.println  ( "location not found" );
        }

        if(number_of_times==5)
        {
            setServiceAlarm(getBaseContext(),false);
            number_of_times=-1;
        }
        number_of_times++;
        return START_NOT_STICKY;
    }

    public void onDestroy()
    {
        super.onDestroy();
        Toast.makeText(this, "yolo- the service has stopped working", Toast.LENGTH_LONG).show();
    }

    public void sendSMS(String phoneNumber, String message) 
    {
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, null, null);
        ContentValues values = new ContentValues(); 
        values.put("address", phoneNumber); 
        values.put("body", message); 
        getContentResolver().insert(Uri.parse("content://sms/sent"), values);
    }

    public static void setServiceAlarm(Context context, boolean isOn)
    {
        // Acquire a reference to the system Location Manager
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Intent i = new Intent(context, Controller.class);
        PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        if (isOn) 
        {
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), POLL_INTERVAL, pi);
        } 
        else 
        {
            alarmManager.cancel(pi);
            pi.cancel();
        }
    }

    @Override
    public IBinder onBind(Intent intent) 
    {
        return null;
    }
}

这段代码在我的三星设备上完美运行。

【讨论】:

  • locationListenerGps.onLocationChanged(currentLocation); 的意义何在
  • 这是您的 lastKnownPosition 位置。
  • 我从代码中删除了这一行,但没有任何改变。为什么?
  • 我删除它只是为了看看发生了什么
  • 好吧,那是我的错误。昨天你的问题让我很紧张。它的故事很长。但是,是的,您可以省略该行。没有那行代码也可以正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-11
  • 2016-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多