簡體   English   中英

空指針異常導致嘗試運行多個線程時強制關閉

[英]Null Pointer Exception causing force close while trying to run multiple threads

我正在嘗試在后台運行一項服務,該服務發送手機位置的短信。 在服務中,我使用計時器。 發送消息的代碼可以正確運行,但是當我嘗試將代碼放入以查找用戶位置時,總是會遇到錯誤。

我試圖調用一個新線程並使用了循環程序,但是現在我得到了一個nullpointerexception,它指向這兩行代碼:

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)

您需要更換

coordinates.equals(null)  

coordinates == null

由於第一個永遠不會取值為true ,因此每次coordinatesnull時,它將拋出NullPointerException()

如果coordinates為null,則第一個條件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";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM