靠近试图运行多个线程空指针异常强制力 [英] Null Pointer Exception causing force close while trying to run multiple threads

查看:144
本文介绍了靠近试图运行多个线程空指针异常强制力的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行发送手机位置的文本消息的后台服务。在服务我用一个定时器。在code发送邮件可以正常运行,但是当我尝试把code中找到用户的位置,我总是遇到错误。

我试着打电话给一个新的线程,并使用钩子,但现在我得到它指向code这两种线NullPointerException异常:

  sendSmsMessage();

和在该方法中:

 如果(coordinates.equals(空)|| coordinates.equals()||坐标== NULL ||坐标==){
        坐标=无法接收位置;
    }

所以,我要问的问题是为什么发生这个错误?如果你能帮助我走出这将大大AP preciated。如果我只是忽视的东西很简单,请指出来。谢谢!

这里的code:

 公共类MessageService扩展服务{
INT计数器= 0;
私人定时器定时器=新的Timer();
公共字符串textTime,phoneNumber的;
公众诠释updateInterval;
诠释纬度,经度;
串坐标,经度,纬度;
的LocationManager的LocationManager;@覆盖
公众的IBinder onBind(意向为arg0){
    返回null;
}@覆盖
公众诠释onStartCommand(意向意图,诠释标志诠释startId){
    //从主叫接收意图的意图演员
    textTime = intent.getStringExtra(textTime);
    phoneNumber的= intent.getStringExtra(手机);    phoneNumber的=5556;    // if语句具有与串textTime转移到可用于一个数字来执行以下
    如果(textTime.equals(15分钟)){
        updateInterval =(15 *(60000));
    }否则如果(textTime.equals(30分钟)){
        updateInterval =(30 *(60000));
    }否则如果(textTime.equals(1小时)){
        updateInterval =(60 *(60000));
    }其他{
        updateInterval =(15 *(60000));
    }    的LocationManager =(的LocationManager)this.getSystemService(Context.LOCATION_SERVICE);    新的Thread(){
        公共无效的run(){
            尺蠖prepare()。
            //定义,响应位置更新的监听器
            LocationListener的LocationListener的=新LocationListener的(){
                公共无效onLocationChanged(地点){
                  //当一个新的位置由网络位置提供商发现调用。
                  // makeUseOfNewLocation(位置);
                    纬度=(INT)(location.getLatitude()* 1E6);
                    LNG =(INT)(location.getLongitude()* 1E6);                    纬度= Integer.toString(LAT);
                    经度= Integer.toString(LNG);                    坐标=坐标:+纬度+,+经度+纬度:+纬度+经度。回应END停止文本+经度+;
                }                公共无效onStatusChanged(字符串提供商,INT地位,捆绑演员){}                公共无效onProviderEnabled(字符串提供商){}                公共无效onProviderDisabled(字符串提供商){}
              };              Looper.loop();              如果(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,LocationListener的);
              }其他{
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,LocationListener的);
              }        }
    }。开始();
    //下面的方法应该用一个定时器在定时间隔发送短信。还应该实现使用不同的线程
    doSomethingRepeatedly();    返回START_STICKY;}公共无效doSomethingRepeatedly(){
    timer.scheduleAtFixedRate(新的TimerTask(){
        公共无效的run(){
            //下面的code应该是什么反复做
            //Log.d(\"MessageService,将String.valueOf(++计数器));            sendSmsMessage();
        }
    },0,updateInterval);
}//下面的code处理发送短信
公共无效sendSmsMessage(){
    SmsManager短信= SmsManager.getDefault();
    如果(coordinates.equals(空)|| coordinates.equals()||坐标==空||坐标==){
        坐标=无法接收位置;
    }    sms.sendTextMessage(phoneNumber的,空,测试,NULL,NULL);}公共无效的onDestroy(){
    super.onDestroy();    如果(定时器!= NULL){
        timer.cancel();
    }
}
} //服务端

这里是logcat的输出:

  20 10-19:23:28.096:E / AndroidRuntime(944):致命异常:定时器0
10-19 20:23:28.096:E / AndroidRuntime(944):显示java.lang.NullPointerException
10-19 20:23:28.096:E / AndroidRuntime(944):在com.app.MessageService.sendSmsMessage(MessageService.java:113)
10-19 20:23:28.096:E / AndroidRuntime(944):在com.app.MessageService $ 2.run(MessageService.java:105)
10-19 20:23:28.096:E / AndroidRuntime(944):在java.util.Timer中的$ TimerImpl.run(Timer.java:284)


解决方案

您需要更换

  coordinates.equals(空)

 坐标== NULL

因为第一个将永远不会计算为真正,它会抛出一个的NullPointerException()每次坐标

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:

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:

    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.

这篇关于靠近试图运行多个线程空指针异常强制力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆