简体   繁体   English

空指针异常导致尝试运行多个线程时强制关闭

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

I'm trying to run a service in the background that sends texts messages of the location of the phone. 我正在尝试在后台运行一项服务,该服务发送手机位置的短信。 In the service I use a Timer. 在服务中,我使用计时器。 The code that sends the messages runs correctly but when I try to put the code in to find the users location I always run into errors. 发送消息的代码可以正确运行,但是当我尝试将代码放入以查找用户位置时,总是会遇到错误。

I tried to call a new thread and used a looper but now I'm getting a nullpointerexception which points to these two lines of code: 我试图调用一个新线程并使用了循环程序,但是现在我得到了一个nullpointerexception,它指向这两行代码:

sendSmsMessage();

and within this method: 并在此方法中:

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

So, the question I'm asking is why is this error occurring? 因此,我要问的问题是为什么会发生此错误? If you could help me out it would be greatly appreciated. 如果您能帮助我,将不胜感激。 And if I'm just overlooking something very simple please point it out. 如果我只是忽略一些非常简单的内容,请指出。 Thanks! 谢谢!

Here's the code: 这是代码:

    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

And here is the logcat output: 这是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)

You need to replace 您需要更换

coordinates.equals(null)  

with

coordinates == null

since the first one will never evaluate to true , it will throw a NullPointerException() every time coordinates is null . 由于第一个永远不会取值为true ,因此每次coordinatesnull时,它将抛出NullPointerException()

If your coordinates is null then the very first condition oordinates.equals(null) will result into NullPointerException . 如果coordinates为null,则第一个条件oordinates.equals(null)将导致NullPointerException

In addition, I have one more observation. 另外,我还有另外一个观察。 The comparison coordinates == "" is of no use as you are already using it in right way ie coordinates.equals(""). 比较coordinates == ""是没有用的,因为您已经以正确的方式使用它了,即坐标.equals(“”)。

Change your if from if从更改

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

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试运行Java多线程服务器时出现空指针异常 - Null Pointer Exception while trying to run Java multi threaded server 尝试冒泡排序时出现空指针异常 - Null Pointer Exception while trying to Bubble Sort 为什么此已处理的异常导致强制关闭? [GeoCoder] - Why is this handled exception causing a Force Close? [GeoCoder] 尝试将CS​​V文件上传到服务器时出现空指针异常 - Null pointer exception while trying to upload a CSV file to the server 尝试从另一个类修改JFrame时出现空指针异常? - Null pointer exception while trying to modify a JFrame from another class? 尝试在画布纹理视图 android 上绘制时出现空指针异常? - Getting a null pointer exception while trying to draw on canvas textureview android? 尝试创建常规对象时出现Null Pointer异常-Android - Null Pointer Exception while trying creating a general object - Android 尝试从InputStream重复读取时发生空指针异常 - Null pointer exception occurs while trying to read repeatedly from an InputStream 尝试使用File类加载文件时出现空指针异常 - null pointer exception while trying to load file using the File class 尝试在另一个 class 中使用一种方法时 Null 指针异常 - Null pointer exception while trying to use one method in another class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM