简体   繁体   English

Android Spinner引发Null指针异常

[英]Android spinner throws a Null pointer exception

So I have a service that contains a Timer. 所以我有一个包含计时器的服务。 The service is meant to run even when the app in the background and is supposed to pull the user to the app when the timer executes the method(from another activity). 该服务旨在在后台运行应用程序时运行,并应在计时器执行方法(来自另一个活动)时将用户拉到应用程序。 The service is triggered on and off by a toggle button. 该服务由一个切换按钮打开和关闭。 Currently my R.id reference to my spinner keeps throwing a NullPointerException that i don't know how to fix. 目前,我对微调器的R.id参考不断抛出NullPointerException,我不知道如何解决。 Can someone please help me out? 有人可以帮我吗?

The Method the Timer is running: 计时器正在运行的方法:

 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;
        }

My service code: 我的服务代码:

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();
    }
}

the button: 按钮:

    @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();
        }

    }

the stack trace: 堆栈跟踪:

  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)

You should not create a instance of Activity class. 您不应创建Activity类的实例。

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

This results in NullPointerException when you initialize views. 初始化视图时,这会导致NullPointerException

Can i Create the object of a activity in other class? 我可以在其他课程中创建活动的对象吗?

Also what you are doing seems to be a design issue. 另外,您正在做的事情似乎是设计问题。

As previous comments already pointed out, service wont have any UI, so you cannot make findViewById method call. 正如前面的评论所指出的那样,服务将没有任何UI,因此您无法进行findViewById方法调用。

If you want your service to change the UI, bind to this service from your activity and using callbacks/delegates, you can notify the activity to change the UI from the service. 如果您想让服务更改UI,并从您的活动和使用回调/代理将其绑定到此服务,则可以通知活动从服务更改UI。

Activity objects are not supposed to be initialized by calling its constructor. 不应该通过调用活动对象的构造函数来初始化活动对象。 By doing so, your overriden method onCreate() never get called, so the views are not initialized and findViewById will fail. 这样,就不会调用您的重写方法onCreate(),因此不会初始化视图,并且findViewById将失败。

You should instead start the activity in the service instead of calling its contructor, something like this: 您应该改为在服务中启动活动,而不是调用其构造函数,如下所示:

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

You can have a static getter in Locator class to get the instance of the Activity, so that you can use it in the Service. 您可以在Locator类中使用一个静态getter来获取Activity的实例,以便可以在Service中使用它。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM