private void onFavoriteItemSelected(boolean favorited) {
    Observable<Boolean> obsAction;

    if (favorited) {
      obsAction =
          Observable.create(
              (Subscriber<? super Boolean> subscriber) -> {
                try {
                  FavoritesUtils.addToFavorites(getActivity(), FAVORITE_VIDEOS, mFeedItem);
                  mFeedItem = new FeedItem.Builder(mFeedItem).setFavorited(true).build();
                  subscriber.onNext(true);
                } catch (Exception e) {
                  Timber.w(e, "Unable to add FeedItem to favorites");
                  subscriber.onError(e);
                }
                subscriber.onCompleted();
              });
      obsAction = AndroidObservable.bindFragment(this, obsAction).subscribeOn(Schedulers.io());
      bindSubscription(
          obsAction.subscribe(
              result -> {
                if (result) {
                  Toast.makeText(getActivity(), R.string.added_to_favorites, Toast.LENGTH_SHORT)
                      .show();
                }
                configureOverflow(result);
              }));
    } else {
      obsAction =
          Observable.create(
              (Subscriber<? super Boolean> subscriber) -> {
                try {
                  FavoritesUtils.removeFromFavorites(getActivity(), FAVORITE_VIDEOS, mFeedItem);
                  mFeedItem = new FeedItem.Builder(mFeedItem).setFavorited(false).build();
                  subscriber.onNext(false);
                } catch (Exception e) {
                  Timber.w(e, "Unable to remove FeedItem from favorites");
                  subscriber.onError(e);
                }
                subscriber.onCompleted();
              });
      obsAction = AndroidObservable.bindFragment(this, obsAction).subscribeOn(Schedulers.io());
      bindSubscription(
          obsAction.subscribe(
              result -> {
                if (!result) {
                  Toast.makeText(getActivity(), R.string.removed_from_favorites, Toast.LENGTH_SHORT)
                      .show();
                }
                configureOverflow(result);
              }));
    }
  }
  /** Tries reading one particular file as a post. */
  public Optional<Post> parsePost(FileNode node) {
    String fileName = node.getPath();

    // check for match
    Matcher matcher = POST_TITLE_PATTERN.matcher(fileName);
    if (!matcher.matches()) return Optional.absent();

    try {
      // get date
      int year = Integer.valueOf(matcher.group(1));
      int month = Integer.valueOf(matcher.group(2)) - 1; // java Calendar is 0 based
      int day = Integer.valueOf(matcher.group(3));
      Calendar calendar = Calendar.getInstance();
      calendar.set(year, month, day);

      // get title
      String title = formatTitle(matcher.group(4));

      return Optional.of(new Post(title, calendar.getTime(), node));

    } catch (NumberFormatException nfe) {
      Timber.w(nfe, "failed to parse post tile \"" + fileName + "\"");
      return Optional.absent();
    }
  }
Exemple #3
0
 @DebugLog
 public Metadata lookupArtistInfo(final String artistName) {
   Call<Artist> call = mLastFM.getArtist(artistName);
   Response<Artist> response;
   try {
     response = call.execute();
   } catch (IOException e) {
     return null;
   }
   Artist artist = response.body();
   if (artist == null) {
     Timber.w("Failed to retrieve artist %s", artistName);
     return null;
   }
   Metadata.Builder bob = Metadata.builder();
   bob.putString(KEY_ARTIST_NAME, artist.getName());
   bob.putString(KEY_ARTIST_SUMMARY, artist.getWikiSummary());
   bob.putString(KEY_ARTIST_BIO, artist.getWikiText());
   Date lastChanged = artist.getWikiLastChanged();
   if (lastChanged != null) {
     bob.putLong(KEY_LAST_MODIFIED, lastChanged.getTime());
   }
   bob.putUri(KEY_ARTIST_URL_URI, Uri.parse(artist.getUrl()));
   bob.putString(KEY_ARTIST_MBID, artist.getMbid());
   return bob.build();
 }
  public static void buildComplexMissionItem(MavLinkDrone drone, Bundle itemBundle) {
    MissionItem missionItem = MissionItemType.restoreMissionItemFromBundle(itemBundle);
    if (missionItem == null || !(missionItem instanceof MissionItem.ComplexItem)) return;

    final MissionItemType itemType = missionItem.getType();
    switch (itemType) {
      case SURVEY:
        Survey updatedSurvey = buildSurvey(drone, (Survey) missionItem);
        if (updatedSurvey != null) itemType.storeMissionItem(updatedSurvey, itemBundle);
        break;

      case SPLINE_SURVEY:
        Survey updatedSplineSurvey = buildSplineSurvey(drone, (Survey) missionItem);
        if (updatedSplineSurvey != null) itemType.storeMissionItem(updatedSplineSurvey, itemBundle);
        break;

      case STRUCTURE_SCANNER:
        StructureScanner updatedScanner =
            buildStructureScanner(drone, (StructureScanner) missionItem);
        if (updatedScanner != null) itemType.storeMissionItem(updatedScanner, itemBundle);
        break;

      default:
        Timber.w("Unrecognized complex mission item.");
        break;
    }
  }
  private List<QuranRow> getBookmarkRows(BookmarkData data, boolean groupByTags) {
    List<QuranRow> rows;

    List<Tag> tags = data.getTags();
    List<Bookmark> bookmarks = data.getBookmarks();

    if (groupByTags) {
      rows = getRowsSortedByTags(tags, bookmarks);
    } else {
      rows = getSortedRows(bookmarks);
    }

    int lastPage = mQuranSettings.getLastPage();
    boolean showLastPage = lastPage != Constants.NO_PAGE_SAVED;
    if (showLastPage && (lastPage > Constants.PAGES_LAST || lastPage < Constants.PAGES_FIRST)) {
      showLastPage = false;
      Timber.w("Got invalid last saved page as %d", lastPage);
    }

    if (showLastPage) {
      rows.add(0, QuranRowFactory.fromCurrentPageHeader(mAppContext));
      rows.add(1, QuranRowFactory.fromCurrentPage(mAppContext, lastPage));
    }

    return rows;
  }
 public static void onUpgrade(
     SQLiteDatabase database, int oldVersion, int newVersion, Context context) {
   Timber.w(
       "onUpgrade(): %s: Upgrading database from version %d to version %d.",
       TABLE_LIST_ITEMS, oldVersion, newVersion);
   database.execSQL("DROP TABLE IF EXISTS " + TABLE_LIST_ITEMS);
   onCreate(database, context);
 }
  public WifiNetworkStatus getWifiNetworkStatus() {
    if (wifiNetworkStatus == null) {
      Timber.w("Cannot find valid instance of WifiNetworkStatus, trying to instantiate a new one");
      wifiNetworkStatus = new WifiNetworkStatus();
    }

    return wifiNetworkStatus;
  }
Exemple #8
0
 public PagePosition parseAnchor(String anchor) {
   if (anchor == null || !(anchor.length() > 1 && anchor.charAt(0) == 't')) {
     Timber.w("Anchor '%s' is invalid", anchor);
     return new PagePosition(PagePosition.TOP);
   } else {
     return new PagePosition(Integer.valueOf(anchor.substring(1)));
   }
 }
Exemple #9
0
  private void resolveSignInError() {
    if (!signInConnectionResult.hasResolution()) {
      Timber.w("no resolution found");
      GooglePlayServicesUtil.getErrorDialog(
              signInConnectionResult.getErrorCode(), LoginActivity.this, 0)
          .show();
      return;
    }

    if (!authInProgress) {
      try {
        Timber.w("attempting to resolve failed connection");
        authInProgress = true;
        signInConnectionResult.startResolutionForResult(LoginActivity.this, REQUEST_OAUTH);
      } catch (IntentSender.SendIntentException e) {
        Timber.e(e, "failed to send resolution intent");
      }
    }
  }
 private void allowPermissionsIfNeeded() {
   if (Build.VERSION.SDK_INT >= 23) {
     UiObject allowPermissions = mDevice.findObject(new UiSelector().text("Allow"));
     if (allowPermissions.exists()) {
       try {
         allowPermissions.click();
       } catch (UiObjectNotFoundException e) {
         Timber.w(e, "There is no permissions dialog to interact with ");
       }
     }
   }
 }
 @Nullable
 private BackendConfig getCustomBackend() {
   SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
   String backend = prefs.getString(CUSTOM_BACKEND_PREFERENCE, null);
   if (backend != null) {
     try {
       return BackendConfig.byName().apply(backend);
     } catch (NoSuchElementException ex) {
       Timber.w("Could not find backend with name: %s", backend);
     }
   }
   return null;
 }
Exemple #12
0
  @Override
  protected void onCreate(Bundle icicle) {
    Themes.setThemeLegacy(this);
    super.onCreate(icicle);

    mCol = CollectionHelper.getInstance().getCol(this);
    if (mCol == null) {
      finish();
      return;
    }
    Bundle extras = getIntent().getExtras();
    if (extras != null && extras.containsKey("did")) {
      mDeck = mCol.getDecks().get(extras.getLong("did"));
    } else {
      mDeck = mCol.getDecks().current();
    }
    registerExternalStorageListener();

    if (mCol == null) {
      Timber.w("DeckOptions - No Collection loaded");
      finish();
    } else {
      mPref = new DeckPreferenceHack();
      mPref.registerOnSharedPreferenceChangeListener(this);

      this.addPreferencesFromResource(R.xml.deck_options);
      this.buildLists();
      this.updateSummaries();
      // Set the activity title to include the name of the deck
      String title = getResources().getString(R.string.deckpreferences_title);
      if (title.contains("XXX")) {
        try {
          title = title.replace("XXX", mDeck.getString("name"));
        } catch (JSONException e) {
          title = title.replace("XXX", "???");
        }
      }
      this.setTitle(title);
    }

    // Add a home button to the actionbar
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  }
 private void animateActionButtonVisibility(final boolean videoExist) {
   ActionButton videoBtn = binding.playVideoBtn;
   videoBtn.setEnabled(videoExist);
   Runnable r =
       () -> {
         // Button alpha may change during transition, we may have to wait until its end
         // to check its state.
         Timber.w("Action btn alpha: " + videoBtn.getAlpha());
         boolean actionBtnShouldAnimate =
             (videoExist && videoBtn.getAlpha() != 1) || (!videoExist && videoBtn.getAlpha() != 0);
         if (!actionBtnShouldAnimate) {
           return;
         }
         Animator alphaAnimator = AnimatorUtils.getAlphaAnimator(videoBtn, !videoExist);
         alphaAnimator.setDuration(600);
         alphaAnimator.start();
       };
   // Wait just in case transition is still in progress.
   videoBtn.postDelayed(r, ACTION_BUTTON_VISIBILITY_ANIM_DELAY);
 }
  public void updateWifiConfigWithScanResults(List<ScanResult> scanResults) {
    List<String> scanResultsStrings = new ArrayList<String>();

    synchronized (wifiNetworkStatusLock) {
      // clear all the savedConfigurations AP status
      if (!getWifiNetworkStatus().isEmpty()) {
        App.getTraceUtils().startTrace(TAG, "Clear scan status from AP configs", Log.DEBUG);
        for (WiFiApConfig conf : getWifiNetworkStatus().values()) {
          conf.clearScanStatus();
        }
        App.getTraceUtils().stopTrace(TAG, "Clear scan status from AP configs", Log.DEBUG);
      }

      if (scanResults != null) {
        for (ScanResult res : scanResults) {
          scanResultsStrings.add(res.SSID + " level: " + res.level);
          String currSSID = ProxyUtils.cleanUpSSID(res.SSID);
          SecurityType security = ProxyUtils.getSecurity(res);
          APLNetworkId aplNetworkId = new APLNetworkId(currSSID, security);

          if (getWifiNetworkStatus().containsKey(aplNetworkId)) {
            WiFiApConfig conf = getWifiNetworkStatus().get(aplNetworkId);
            if (conf != null) {
              conf.updateScanResults(res);
            }
          } else {
            if (getWifiNetworkStatus().getNotConfiguredWifi().containsKey(aplNetworkId)) {
              getWifiNetworkStatus().getNotConfiguredWifi().remove(aplNetworkId);
            }

            getWifiNetworkStatus().getNotConfiguredWifi().put(aplNetworkId, res);
          }
        }
      } else {
        Timber.w("No ScanResults available for updateWifiConfigWithScanResults");
      }
    }

    Timber.d("Updating from scanresult: " + TextUtils.join(", ", scanResultsStrings.toArray()));
  }
Exemple #15
0
 public static Typeface getTypeface(Context ctx, String path) {
   try {
     if (path.startsWith(fAssetPathPrefix)) {
       return Typeface.createFromAsset(ctx.getAssets(), path.replaceFirst("/android_asset/", ""));
     } else {
       return Typeface.createFromFile(path);
     }
   } catch (RuntimeException e) {
     Timber.w(e, "Runtime error in getTypeface for File: %s", path);
     if (!corruptFonts.contains(path)) {
       // Show warning toast
       String name = new File(path).getName();
       Resources res = AnkiDroidApp.getAppResources();
       Toast toast =
           Toast.makeText(ctx, res.getString(R.string.corrupt_font, name), Toast.LENGTH_LONG);
       toast.show();
       // Don't warn again in this session
       corruptFonts.add(path);
     }
     return null;
   }
 }
  public void changeTimeSummaryStartingPoint(int newStartingPoint) {
    try {
      int currentStartingPoint = Settings.getStartingPointForTimeSummary(getContext());
      if (currentStartingPoint == newStartingPoint) {
        return;
      }

      switch (newStartingPoint) {
        case GetProjectTimeSince.WEEK:
          Settings.useWeekForTimeSummaryStartingPoint(getContext());
          break;
        case GetProjectTimeSince.MONTH:
          Settings.useMonthForTimeSummaryStartingPoint(getContext());
          break;
        default:
          throw new InvalidStartingPointException(
              "Starting point '" + newStartingPoint + "' is not valid");
      }

      eventBus.post(new TimeSummaryStartingPointChangeEvent());

      performWithView(
          view -> {
            if (GetProjectTimeSince.WEEK == newStartingPoint) {
              view.showChangeTimeSummaryStartingPointToWeekSuccessMessage();
              return;
            }

            view.showChangeTimeSummaryStartingPointToMonthSuccessMessage();
          });
    } catch (InvalidStartingPointException e) {
      Timber.w(e, "Unable to set new starting point");

      performWithView(ProjectView::showChangeTimeSummaryStartingPointErrorMessage);
    }
  }
  /**
   * Create a new fragment and specify the fragment to show based on nav item clicked
   *
   * @param menuItem
   * @return
   */
  protected boolean selectDrawerItem(MenuItem menuItem) {
    Triple<Fragment, String, Boolean> fragmentTagIsFoundTriple = null;

    _lastMenuItemIDRequested = menuItem.getItemId();
    switch (_lastMenuItemIDRequested) {
      case R.id.drawer_menu_item_calendar:
        Timber.i("Calendar selected from Drawer");
        fragmentTagIsFoundTriple =
            _findFragmentByTagOrReturnNewInstance(CALENDAR_FRAGMENT_TAG, Calendar.class);
        break;
      case R.id.drawer_menu_item_guidelines_and_policies:
        Timber.i("Guidelines And Policies selected from Drawer");
        fragmentTagIsFoundTriple =
            _findFragmentByTagOrReturnNewInstance(
                GUIDELINES_POLICIES_FRAGMENT_TAG, GuidelinesAndPolicies.class);
        break;
      case R.id.drawer_menu_item_about:
        Timber.i("About selected from Drawer");
        fragmentTagIsFoundTriple =
            _findFragmentByTagOrReturnNewInstance(ABOUT_FRAGMENT_TAG, About.class);
        break;
      case R.id.drawer_menu_item_my_account:
        Timber.i("My Account selected from Drawer");
        fragmentTagIsFoundTriple =
            _findFragmentByTagOrReturnNewInstance(MY_ACCOUNT_FRAGMENT_TAG, MyAccount.class);
        break;
      default:
        Timber.w("No layout mapped to the menu item requested, moving to the default, Calendar");
        fragmentTagIsFoundTriple =
            _findFragmentByTagOrReturnNewInstance(CALENDAR_FRAGMENT_TAG, Calendar.class);
    }
    if (fragmentTagIsFoundTriple == null) {
      return false;
    }

    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    // If the fragment was already created(isFound), just show it. If not,
    // Insert the fragment by replacing any existing fragment.
    // Don't forget to tag it so it can be retrieved later without loading it again

    if (_isFragmentFoundAndVisible(fragmentTagIsFoundTriple)) {
      Timber.d("Drawer Item: " + menuItem.getTitle() + " already being shown. Not changing screen");
    } else if (!_isFragmentFoundAndVisible(fragmentTagIsFoundTriple)) {
      fragmentTransaction =
          _addHideAllVisibleFragmentsToFragmentTransaction(
                  stringFragmentHashMap, fragmentTransaction)
              .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
              .show(fragmentTagIsFoundTriple.getLeft());
      // On the first time opening the drawer there is a special case where the backstack will be
      // empty, so adding
      // will cause the user to see a blank screen with nothing if they press back
      if (_isFirstTimeSelectDrawerItem) {
        _isFirstTimeSelectDrawerItem = false;
      } else {
        fragmentTransaction.addToBackStack(null);
      }

      fragmentTransaction.commit();
    } else {
      // To make sure the backstack works correctly, we split this into 2 separate transactions
      // This one JUST adds it to the correct frame, and the 2nd one hides/unhides
      getSupportFragmentManager()
          .beginTransaction()
          .add(
              R.id.mainactivity_content_frame,
              fragmentTagIsFoundTriple.getLeft(),
              fragmentTagIsFoundTriple.getMiddle())
          .commit();

      _addHideAllVisibleFragmentsToFragmentTransaction(stringFragmentHashMap, fragmentTransaction)
          .addToBackStack(null)
          .commit();
    }

    // Highlight the selected item
    menuItem.setChecked(true);
    // Set action bar title
    _mDrawerLayout.closeDrawers();
    return true;
  }
Exemple #18
0
  public static void textToSpeech(String text, long did, int ord, int qa) {
    mTextToSpeak = text;
    mQuestionAnswer = qa;
    mDid = did;
    mOrd = ord;
    Timber.d("ReadText.textToSpeech() method started for string '%s'", text);
    // get the user's existing language preference
    String language = getLanguage(mDid, mOrd, mQuestionAnswer);
    Timber.d("ReadText.textToSpeech() method found language choice '%s'", language);
    // rebuild the language list if it's empty
    if (availableTtsLocales.isEmpty()) {
      buildAvailableLanguages();
    }
    // Check, if stored language is available
    for (int i = 0; i < availableTtsLocales.size(); i++) {
      if (language.equals(NO_TTS)) {
        // user has chosen not to read the text
        return;
      } else if (language.equals(availableTtsLocales.get(i).getISO3Language())) {
        speak(mTextToSpeak, language);
        return;
      }
    }

    // Otherwise ask the user what language they want to use
    Resources res = mReviewer.get().getResources();
    final StyledDialog.Builder builder = new StyledDialog.Builder(mReviewer.get());
    if (availableTtsLocales.size() == 0) {
      // builder.setTitle(res.getString(R.string.no_tts_available_title));
      Timber.w("ReadText.textToSpeech() no TTS languages available");
      builder.setMessage(res.getString(R.string.no_tts_available_message));
      builder.setIcon(R.drawable.ic_dialog_alert);
      builder.setPositiveButton(res.getString(R.string.dialog_ok), null);
    } else {
      ArrayList<CharSequence> dialogItems = new ArrayList<CharSequence>();
      final ArrayList<String> dialogIds = new ArrayList<String>();
      builder.setTitle(R.string.select_locale_title);
      // Add option: "no tts"
      dialogItems.add(res.getString(R.string.tts_no_tts));
      dialogIds.add(NO_TTS);
      for (int i = 0; i < availableTtsLocales.size(); i++) {
        dialogItems.add(availableTtsLocales.get(i).getDisplayName());
        dialogIds.add(availableTtsLocales.get(i).getISO3Language());
      }
      String[] items = new String[dialogItems.size()];
      dialogItems.toArray(items);

      builder.setItems(
          items,
          new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              String locale = dialogIds.get(which);
              Timber.d("ReadText.textToSpeech() user chose locale '%s'", locale);
              if (!locale.equals(NO_TTS)) {
                speak(mTextToSpeak, locale);
              }
              MetaDB.storeLanguage(mReviewer.get(), mDid, mOrd, mQuestionAnswer, locale);
            }
          });
    }
    // Show the dialog after short delay so that user gets a chance to preview the card
    final Handler handler = new Handler();
    final int delay = 500;
    handler.postDelayed(
        new Runnable() {
          @Override
          public void run() {
            builder.create().show();
          }
        },
        delay);
  }
Exemple #19
0
  /**
   * Convenience method for querying the database for an entire column. The column will be returned
   * as an ArrayList of the specified class. See Deck.initUndo() for a usage example.
   *
   * @param type The class of the column's data type. Example: int.class, String.class.
   * @param query The SQL query statement.
   * @param column The column id in the result set to return.
   * @return An ArrayList with the contents of the specified column.
   */
  public <T> ArrayList<T> queryColumn(Class<T> type, String query, int column) {
    int nullExceptionCount = 0;
    InvocationTargetException nullException = null; // to catch the null exception for reporting
    ArrayList<T> results = new ArrayList<T>();
    Cursor cursor = null;

    try {
      cursor = mDatabase.rawQuery(query, null);
      String methodName = getCursorMethodName(type.getSimpleName());
      while (cursor.moveToNext()) {
        try {
          // The magical line. Almost as illegible as python code ;)
          results.add(
              type.cast(Cursor.class.getMethod(methodName, int.class).invoke(cursor, column)));
        } catch (InvocationTargetException e) {
          if (cursor.isNull(column)) { // null value encountered
            nullExceptionCount++;
            if (nullExceptionCount == 1) { // Toast and error report first time only
              nullException = e;
              Toast.makeText(
                      AnkiDroidApp.getInstance().getBaseContext(),
                      "Error report pending: unexpected null in database.",
                      Toast.LENGTH_LONG)
                  .show();
            }
            continue; // attempt to skip this null record
          } else {
            throw new RuntimeException(e);
          }
        }
      }
    } catch (NoSuchMethodException e) {
      // This is really coding error, so it should be revealed if it ever happens
      throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
      // This is really coding error, so it should be revealed if it ever happens
      throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
      // This is really coding error, so it should be revealed if it ever happens
      throw new RuntimeException(e);
    } finally {
      if (cursor != null) {
        cursor.close();
      }
      if (nullExceptionCount > 0) {
        if (nullException != null) {
          StringBuilder sb = new StringBuilder();
          sb.append("AnkiDb.queryColumn (column " + column + "): ");
          sb.append("Exception due to null. Query: " + query);
          sb.append(" Null occurrences during this query: " + nullExceptionCount);
          AnkiDroidApp.sendExceptionReport(
              nullException, "queryColumn_encounteredNull", sb.toString());
          Timber.w(sb.toString());
        } else { // nullException not properly initialized
          StringBuilder sb = new StringBuilder();
          sb.append("AnkiDb.queryColumn(): Critical error -- ");
          sb.append("unable to pass in the actual exception to error reporting.");
          AnkiDroidApp.sendExceptionReport(
              new RuntimeException("queryColumn null"),
              "queryColumn_encounteredNull",
              sb.toString());
          Timber.e(sb.toString());
        }
      }
    }

    return results;
  }
 void logWarn(String msg) {
   Timber.w("In-app billing warning: " + msg);
 }