【问题标题】:Null Pointer Exception causing force close while trying to run multiple threads尝试运行多个线程时导致强制关闭的空指针异常
【发布时间】:2012-10-20 05:00:10
【问题描述】:

我正在尝试在后台运行一项服务,该服务会发送有关手机位置的短信。在服务中,我使用计时器。发送消息的代码运行正常,但是当我尝试将代码放入以查找用户位置时,我总是遇到错误。

我尝试调用一个新线程并使用了一个循环器,但现在我得到了一个指向这两行代码的空指针异常:

sendSmsMessage();

在这个方法中:

if (coordinates.equals(null) || coordinates.equals("") || coordinates == null || coordinates == ""){
        coordinates = "Could Not Receive Location";
    }

所以,我要问的问题是为什么会发生此错误?如果您能帮助我,将不胜感激。如果我只是忽略了一些非常简单的事情,请指出。谢谢!

代码如下:

    public class MessageService extends Service{
int counter = 0;
private Timer timer = new Timer();
public String textTime, phoneNumber;
public int updateInterval;
int lat, lng;
String coordinates, latitude, longitude;
LocationManager locationManager;

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

@Override
public int onStartCommand(Intent intent, int flags, int startId){
    //receives the intent extras from the calling intent
    textTime = intent.getStringExtra("textTime");
    phoneNumber = intent.getStringExtra("phone");

    phoneNumber = "5556";

    //the following if statement has to do with transferring the string textTime into a number that can be used
    if (textTime.equals("15 Minutes")) {
        updateInterval = (15 * (60000));
    }else if (textTime.equals("30 Minutes")) {
        updateInterval = (30 * (60000));
    }else if (textTime.equals("1 Hour")){
        updateInterval = (60 * (60000));
    }else {
        updateInterval = (15 * (60000));
    }

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

    new Thread(){
        public void run(){
            Looper.prepare();
            // 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);
                    lat = (int) (location.getLatitude() * 1E6);
                    lng = (int) (location.getLongitude() * 1E6);

                    latitude = Integer.toString(lat);
                    longitude = Integer.toString(lng);

                    coordinates = "Coordinates: " + latitude + ", " + longitude + ". Latitude: " + latitude + " Longitude: " + longitude + ". Respond 'END' to stop texts."; 
                }

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

                public void onProviderEnabled(String provider) {}

                public void onProviderDisabled(String provider) {}
              };

              Looper.loop();

              if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
              }else{
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
              }

        }
    }.start();


    //the following method should use a timer to send a sms message in a timed interval. It also should implement using a different thread
    doSomethingRepeatedly();

    return START_STICKY;

}

public void doSomethingRepeatedly(){
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            //the following code should be what is done repeatedly
            //Log.d("MessageService", String.valueOf(++counter));

            sendSmsMessage();
        }
    }, 0, updateInterval);
}

//the following code handles sending the text message
public void sendSmsMessage(){
    SmsManager sms = SmsManager.getDefault();
    if (coordinates.equals(null) || coordinates.equals("") || coordinates == null || coordinates == ""){
        coordinates = "Could Not Receive Location";
    }

    sms.sendTextMessage(phoneNumber, null, "test" , null, null);

}

public void onDestroy() {
    super.onDestroy();

    if (timer != null) {
        timer.cancel();
    }
}




}//end of service

这是 logcat 的输出:

    10-19 20:23:28.096: E/AndroidRuntime(944): FATAL EXCEPTION: Timer-0
10-19 20:23:28.096: E/AndroidRuntime(944): java.lang.NullPointerException
10-19 20:23:28.096: E/AndroidRuntime(944):  at com.app.MessageService.sendSmsMessage(MessageService.java:113)
10-19 20:23:28.096: E/AndroidRuntime(944):  at com.app.MessageService$2.run(MessageService.java:105)
10-19 20:23:28.096: E/AndroidRuntime(944):  at      java.util.Timer$TimerImpl.run(Timer.java:284)

【问题讨论】:

    标签: java android multithreading timer


    【解决方案1】:

    你需要更换

    coordinates.equals(null)  
    

    coordinates == null
    

    因为第一个永远不会评估为true,所以每次coordinatesnull 时都会抛出一个NullPointerException()

    【讨论】:

    • 非常感谢!这解决了我的问题!我认为这将是一件简单的事情,然而,有时简单的错误会导致最严重的头痛。我真的很感激!
    【解决方案2】:

    如果您的coordinates 为空,那么第一个条件oordinates.equals(null) 将导致NullPointerException

    另外,我还有一个观察。比较coordinates == "" 没有用,因为您已经以正确的方式使用它,即坐标.equals("")。

    更改您的 if
    if (coordinates.equals(null) || coordinates.equals("") || 
                                        coordinates == null || coordinates == ""){
        coordinates = "Could Not Receive Location";
    }
    

    if (coordinates == null || coordinates.equals("")){
        coordinates = "Could Not Receive Location";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-11
      • 1970-01-01
      • 2014-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多