如何从活动的onCreate访问方法而不会获得NullPointerException

时间:2015-11-08 11:00:54

标签: android android-activity

我正在尝试在创建活动时设置闹钟但我得到空指针异常。但是,当我通过按钮点击设置闹钟时效果很好。

所以我尝试了很多东西,包括在活动的onCreate()方法内的不同线程上设置方法但仍然获得NPE。

我还尝试将我的活动的onCreate方法设置为public,但结果仍然相同。有什么建议吗?

logcat的:



11-08 13:51:17.109: E/AndroidRuntime(26046): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.snapttechtechnologies.stevekamau.wehappening/com.snapttechtechnologies.stevekamau.wehappening.activities.AddEvent}: java.lang.NullPointerException
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2429)
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at android.app.ActivityThread.access$800(ActivityThread.java:151)
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at android.os.Handler.dispatchMessage(Handler.java:110)
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at android.os.Looper.loop(Looper.java:193)
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at android.app.ActivityThread.main(ActivityThread.java:5333)
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at java.lang.reflect.Method.invokeNative(Native Method)
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at java.lang.reflect.Method.invoke(Method.java:515)
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at dalvik.system.NativeStart.main(Native Method)
11-08 13:51:17.109: E/AndroidRuntime(26046): Caused by: java.lang.NullPointerException
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at com.snapttechtechnologies.stevekamau.wehappening.helper.ScheduleClient.setAlarmForNotification(ScheduleClient.java:60)
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at com.snapttechtechnologies.stevekamau.wehappening.activities.AddEvent.setAlarmTime(AddEvent.java:54)
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at com.snapttechtechnologies.stevekamau.wehappening.activities.AddEvent.onCreate(AddEvent.java:38)
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at android.app.Activity.performCreate(Activity.java:5343)
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
11-08 13:51:17.109: E/AndroidRuntime(26046): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2331)




AddEvent.java



public class AddEvent extends AppCompatActivity {
    private ScheduleClient scheduleClient;
    // This is the date picker used to select the date for our notification
    private DatePicker picker;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.events_wehappened);
        // Create a new service client and bind our activity to this service
        scheduleClient = new ScheduleClient(this);
        scheduleClient.doBindService();

      
        setAlarmTime();
    }

    public void setAlarmTime() {
        String input = "Sun Nov 08 2015 13:38";
        Calendar cal = Calendar.getInstance();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm", Locale.ENGLISH);
        try {
            date = sdf.parse(input);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        cal.setTime(date);
        cal.add(Calendar.MINUTE, -60);
        // Ask our service to set an alarm for that date, this activity talks to the client that talks to the service
        scheduleClient.setAlarmForNotification(cal);
        // Notify the user what they just did
        Toast.makeText(this, "Notification set for: " + cal, Toast.LENGTH_SHORT).show();
    }
    /**
     * This is the onClick called from the XML to set a new notification
     */
    public void onDateSelectedButtonClick(View v) {
        String input = "Sun Nov 08 2015 13:38";
        Calendar cal = Calendar.getInstance();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm", Locale.ENGLISH);
        try {
            date = sdf.parse(input);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        cal.setTime(date);
        cal.add(Calendar.MINUTE, -60);
        // Ask our service to set an alarm for that date, this activity talks to the client that talks to the service
        scheduleClient.setAlarmForNotification(cal);
        // Notify the user what they just did
        Toast.makeText(this, "Notification set for: " + cal, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStop() {
        // When our activity is stopped ensure we also stop the connection to the service
        // this stops us leaking our activity into the system *bad*
        if (scheduleClient != null)
            scheduleClient.doUnbindService();
        super.onStop();
    }




ScheduleClient.java



/**
 * This is our service client, it is the 'middle-man' between the
 * service and any activity that wants to connect to the service
 *
 * @author paul.blundell
 */
public class ScheduleClient {

    // The hook into our service
    private ScheduleService mBoundService;
    // The context to start the service in
    private Context mContext;
    // A flag if we are connected to the service or not
    private boolean mIsBound;
    /**
     * When you attempt to connect to the service, this connection will be called with the result.
     * If we have successfully connected we instantiate our service object so that we can call methods on it.
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with our service has been established,
            // giving us the service object we can use to interact with our service.
            mBoundService = ((ScheduleService.ServiceBinder) service).getService();
        }

        public void onServiceDisconnected(ComponentName className) {
            mBoundService = null;
        }
    };

    public ScheduleClient(Context context) {
        mContext = context;
    }

    /**
     * Call this to connect your activity to your service
     */
    public void doBindService() {
        // Establish a connection with our service
        mContext.bindService(new Intent(mContext, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }

    /**
     * Tell our service to set an alarm for the given date
     *
     * @param c a date to set the notification for
     */
    public void setAlarmForNotification(Calendar c) {
        mBoundService.setAlarm(c);
    }

    /**
     * When you have finished with the service call this method to stop it
     * releasing your connection and resources
     */
    public void doUnbindService() {
        if (mIsBound) {
            // Detach our existing connection.
            mContext.unbindService(mConnection);
            mIsBound = false;
        }
    }
}




1 个答案:

答案 0 :(得分:1)

绑定服务不是同步的。您在请求绑定服务连接后立即调用服务方法,并且绑定尚未完成。

您可以使用onServiceConnected()上的ServiceConnection回调来了解服务的绑定时间。