Android微调器抛出Null指针异常

时间:2014-08-15 15:40:22

标签: java android nullpointerexception

所以我有一个包含Timer的服务。即使应用程序处于后台,该服务也可以运行,并且当计时器执行该方法时(来自另一个活动),该服务应该将用户拉到应用程序。通过切换按钮触发和关闭服务。目前我对我的微调器的R.id引用不断抛出一个我不知道如何解决的NullPointerException。有人可以帮帮我吗?

计时器正在运行的方法:

 public String TemperatureCatch()
        {
/*this line throws the error */            Spinner reeferchoice = (Spinner)findViewById(R.id.optionselecti);
                String reeferChoicei = reeferchoice.getSelectedItem().toString();
                if (reeferChoicei.equals("Yes")) {
                    final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 500);
                    tg.startTone(ToneGenerator.TONE_CDMA_ABBR_ALERT);
                    AlertDialog.Builder alert = new AlertDialog.Builder(this);
                    alert.setTitle("Temperature");
                    alert.setMessage("Input Temperature in F° (-20 to 65) ");
                    final EditText input = new EditText(this);
                    input.setInputType(InputType.TYPE_CLASS_PHONE);
                    alert.setView(input);
                    alert.setPositiveButton("Check-In", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            temperaturei = input.getText().toString();
                            Toast.makeText(getBaseContext(), "Updated", Toast.LENGTH_SHORT).show();
                            Updater(temperaturei);
                        }
                    });
                    alert.show();
                } else if (reeferChoicei.equals("No")) {
                    temperaturei = "DRY";
                    Updater(temperaturei);
                }
            return temperaturei;
        }

我的服务代码:

import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;

import java.util.Timer;
import java.util.TimerTask;

public class MyService extends Service {
    Locator locator;
    Timer myTimer;
    @Override
    public void onCreate() {
        locator = new Locator();
        myTimer = new Timer();
    }
    private class MyTimerTask extends TimerTask
    {

        @Override
        public void run() {
            Handler handler = new Handler(Looper.getMainLooper());

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    locator.TemperatureCatch();
                }
            }, 1000);
        }
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        MyTimerTask myTimerTask = new MyTimerTask();
            myTimer.scheduleAtFixedRate(myTimerTask, 0, 15000);
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        myTimer.cancel();
    }
}

按钮:

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {

        if (isChecked)
        {
 startService(new Intent(this, MyService.class));
            Toast.makeText(this,"Check-In will be done every 15 seconds",Toast.LENGTH_SHORT).show();
        }
        else
        {
stopService(new Intent(this, MyService.class));
            Toast.makeText(this,"Manual Check-In enabled",Toast.LENGTH_SHORT).show();
        }

    }

堆栈跟踪:

  Process: com.example.adrian.trucktracker, PID: 9617
    java.lang.NullPointerException
            at android.app.Activity.findViewById(Activity.java:1952)
            at com.example.adrian.trucktracker.Locator.TemperatureCatch(Locator.java:192)
            at com.example.adrian.trucktracker.MyService$MyTimerTask$1.run(MyService.java:32)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5872)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:668)
            at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:0)

您不应该创建Activity类的实例。

locator = new Locator(); // do not do this

初始化视图时会产生NullPointerException

Can i Create the object of a activity in other class?

你所做的事情似乎也是一个设计问题。

答案 1 :(得分:0)

正如先前的评论已经指出的那样,服务不会有任何UI,因此您无法进行findViewById方法调用。

如果您希望服务更改UI,从活动绑定到此服务并使用回调/委托,您可以通知活动更改服务中的UI。

答案 2 :(得分:0)

不应该通过调用其构造函数来初始化Activity对象。通过这样做,您的覆盖方法onCreate()永远不会被调用,因此视图不会被初始化,findViewById将失败。

您应该在服务中启动活动而不是调用其构造函数,如下所示:

Intent t = new Intent (this, Locator.class);
t.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(t);

您可以在Locator类中使用静态getter来获取Activity的实例,以便您可以在服务中使用它。