在Android中处理来自CalendarProvider的空例外

时间:2016-09-25 04:43:22

标签: android android-studio firebase-authentication

基本上,我尝试创建一项活动,通过FirebaseAuth从Google日历中提取数据。我已成功将FirebaseUser对象转换为正确的帐户对象,以便从Google日历中正确调用Events方法。但是,当Events对象为null并且这是我的代码时,我正面临这个问题:

// Breakthrough 1
// Miguel has created a wonderful Google Cal API Kickstarter Repo to refer to.
// https://github.com/miguelarauj1o/GoogleCalendarQuickStart

/**
 * Breakthrough 2
 *
 * Several issues such as Firebase Support was fixed by attempting to convert FirebaseUser
 * data into an Android.Account Object so that CalendarProvider is able to identify the user
 * properly.
 *
 * However, issues regarding threading came up with an IllegalArgumentException from the start
 * and lots of research was done and these are the helpers to the solution.
 * http://stackoverflow.com/questions/20749044/how-to-get-rid-of-java-lang-illegalstateexception-while-trying-to-getauthtoken-f
 * http://stackoverflow.com/questions/17547019/calling-this-from-your-main-thread-can-lead-to-deadlock-and-or-anrs-while-getti
 */

public class CalendarProvider extends AsyncTask<Void, Void, Events> {
    static final HttpTransport transport = AndroidHttp.newCompatibleTransport();
    static final JsonFactory jsonFactory = GsonFactory.getDefaultInstance();

    static final int REQUEST_ACCOUNT_PICKER = 1000;
    static final int REQUEST_AUTHORIZATION = 1001;
    static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
    private static Events events;
    private static DateTime dt;
    private static final String PREF_ACCOUNT_NAME = "accountName";
    private static final String[] SCOPES = { CalendarScopes.CALENDAR_READONLY };

    public synchronized static void InitializeCal(SharedPreferences sp, GoogleAccountCredential credential, FirebaseUser user, Context AppContext) {
        credential = GoogleAccountCredential.usingOAuth2(
                AppContext, Arrays.asList(SCOPES))
                .setBackOff(new ExponentialBackOff())
                .setSelectedAccountName(sp.getString(PREF_ACCOUNT_NAME, user.getEmail()));

        mService = new com.google.api.services.calendar.Calendar.Builder(
                transport, jsonFactory, credential)
                .setApplicationName("Google Calendar API Android Quickstart")
                .build();
    }

    /**
     * Fetch a list of the next 10 events from the primary calendar.
     * @return List of Strings describing returned events.
     * @throws IOException
     */
    public static List<String> getDataFromApi() throws IOException {
        // List the next 10 events from the primary calendar.
        List<String> eventStrings = new ArrayList<>();
        try {
            if (events.getItems() != null) { // If there are events on this date
                List<Event> items = events.getItems();

                for (Event event : items) {
                    DateTime start = event.getStart().getDateTime();
                    if (start == null) {
                        // All-day events don't have start times, so just use
                        // the start date.
                        start = event.getStart().getDate();
                    }
                    eventStrings.add(
                            String.format("%s (%s)", event.getSummary(), start));
                }
            }
        } catch (Exception e) {
            // Else we add a string to tell'em that nothing is here today
            eventStrings.add("Nothing Today!");

            // Debugging String
            eventStrings.add(e.toString());
        }
        return eventStrings;
    }

    @Override
    protected Events doInBackground(Void... params) {
        dt = new DateTime(selectedDate);
        try {
            events = mService.events().list("primary")
                    .setMaxResults(10)
                    .setTimeMin(dt)
                    .setOrderBy("startTime")
                    .setSingleEvents(true)
                    .execute();

            return events;
        } catch (Exception e) {

        }
        return null;
    }

    @Override
    protected void onPostExecute(Events events) {
        try {
            System.out.println(getDataFromApi());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

我想知道如何正确处理这样的NullPointerExceptions,因为我不知道错误是否是故意的。

如果是,那对我来说很简单,我只是假设用户选择的特定日期没有任何内容。

但是如果它不是什么?

1 个答案:

答案 0 :(得分:1)

如果后台线程中有任何异常,则返回return null;,因此在postExectution中,事件仍然为null,并且您正在尝试打印getDataFromApi()。它将解决您的异常问题。

 @Override
        protected void onPostExecute(Events events) {
           if(this.events==null){
             Log.d("Event"," is still null");
             return;
             }

            try {
                System.out.println(getDataFromApi());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }