@Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final PackageManager pm = getPackageManager();
    if (pm == null) {
      launchInternalPicker();
      return;
    }

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("application/zip");

    try {
      if (pm.queryIntentActivities(intent, PackageManager.GET_ACTIVITIES).size() > 0) {
        intent = new Intent();
        intent.setType("application/zip");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, REQUEST_PICK_FILE);
      } else {
        throw new ActivityNotFoundException();
      }
    } catch (ActivityNotFoundException e) {
      Timber.e(e, "No activity found to handle file picking! Falling back to default!");
      launchInternalPicker();
    }
  }
 @Override
 public void execute(Bundle args) {
   try {
     Collection<CategoryItem> categories = radioApi.listPrimaryCategories();
     // FileRadioApi implementation returns null due to IOException
     if (categories == null) {
       syncResult.stats.numIoExceptions++;
     } else {
       ContentResolver contentResolver = context.getContentResolver();
       Cursor cursor =
           contentResolver.query(
               CategoryColumns.CONTENT_URI, CategoryColumns.ALL_COLUMNS, null, null, null);
       try {
         contentResolver.applyBatch(
             context.getString(R.string.content_authority), prepareBatch(cursor, categories));
       } catch (RemoteException e) {
         Timber.e(e, "RemoteException while sync of categories");
       } catch (OperationApplicationException e) {
         Timber.e(e, "OperationApplicationException while sync of categories");
         throw new IllegalStateException(e);
       }
     }
   } catch (RetrofitError error) {
     Timber.e(error, "Failed to sync categories");
     syncResult.stats.numIoExceptions++;
   }
 }
Example #3
0
 /**
  * Stores the current state of the widget.
  *
  * <p>It replaces any stored state for the widget.
  *
  * @param decks an array of {@link DeckStatus} objects, one for each of the know decks.
  */
 public static void storeWidgetStatus(Context context, DeckStatus[] decks) {
   openDBIfClosed(context);
   try {
     mMetaDb.beginTransaction();
     try {
       // First clear all the existing content.
       mMetaDb.execSQL("DELETE FROM widgetStatus");
       for (DeckStatus deck : decks) {
         mMetaDb.execSQL(
             "INSERT INTO widgetStatus(deckId, deckName, newCards, lrnCards, dueCards, progress, eta) "
                 + "VALUES (?, ?, ?, ?, ?, ?, ?)",
             new Object[] {
               deck.mDeckId,
               deck.mDeckName,
               deck.mNewCards,
               deck.mLrnCards,
               deck.mDueCards,
               deck.mProgress,
               deck.mEta
             });
       }
       mMetaDb.setTransactionSuccessful();
     } finally {
       mMetaDb.endTransaction();
     }
   } catch (IllegalStateException e) {
     Timber.e(e, "MetaDB.storeWidgetStatus: failed");
   } catch (SQLiteException e) {
     Timber.e(e, "MetaDB.storeWidgetStatus: failed");
     closeDB();
     Timber.i("MetaDB:: Trying to reset Widget: " + resetWidget(context));
   }
 }
  public List<WiFiApConfig> getSortedWifiApConfigsList() {
    App.getTraceUtils().startTrace(TAG, "getSortedWifiApConfigsList", Log.DEBUG);

    if (getWifiNetworkStatus().isEmpty()) {
      updateWifiApConfigs();
      App.getTraceUtils()
          .partialTrace(TAG, "getSortedWifiApConfigsList", "updateWifiApConfigs", Log.DEBUG);
    }

    List<WiFiApConfig> list = null;

    synchronized (wifiNetworkStatusLock) {
      list = new ArrayList<WiFiApConfig>(getWifiNetworkStatus().values());
      App.getTraceUtils()
          .partialTrace(TAG, "getSortedWifiApConfigsList", "new ArrayList", Log.DEBUG);

      try {
        Collections.sort(list);
      } catch (IllegalArgumentException e) {
        Timber.e("config_list", configListToDBG().toString());
        Timber.e(e, "Exception during sort of WiFiAPConfigs");
      }
    }

    App.getTraceUtils()
        .partialTrace(TAG, "getSortedWifiApConfigsList", "Collections.sort", Log.DEBUG);
    App.getTraceUtils().stopTrace(TAG, "getSortedWifiApConfigsList", Log.DEBUG);

    return list;
  }
  // TODO: Implement Telescope/Crashlytics here!
  private void logError(Throwable e) {

    // "java.util.NoSuchElementException "   --> No items in Observable
    // "java.net.UnknownHostException"       --> No Internet Connection
    // "retrofit.HttpException"              --> Malformed URL or Address
    // "com.google.gson.JsonSyntaxException" --> Bad JSON
    // "com.google.gson.JsonParseException"
    // "com.google.gson.JsonIOException"
    Timber.e(e.getMessage());
    Timber.e(e, "Error Trace");
  }
Example #6
0
 // 添加MsgBean列表
 public void addMgList(List<MsgBean> newMsgList) {
   if (newMsgList == null) {
     Timber.e("没有更多的聊天记录了");
     return;
   }
   for (int i = 0; i < newMsgList.size(); i++) {
     msgList.add(0, newMsgList.get(i));
   }
   Timber.e("增加了: \t" + newMsgList.size());
   notifyDataSetChanged();
   mRecyclerView.smoothScrollBy(0, msgList.size() * 200);
 }
Example #7
0
 /**
  * Stores a custom dictionary for a given deck.
  *
  * @param dictionary integer number of dictionary, -1 if not set (standard dictionary will be
  *     used)
  */
 public static void storeLookupDictionary(Context context, long did, int dictionary) {
   openDBIfClosed(context);
   Cursor cur = null;
   try {
     cur = mMetaDb.rawQuery("SELECT _id FROM customDictionary" + " WHERE did = " + did, null);
     if (cur.moveToNext()) {
       mMetaDb.execSQL(
           "UPDATE customDictionary "
               + "SET did = "
               + did
               + ", "
               + "dictionary="
               + Integer.toString(dictionary)
               + " "
               + "WHERE _id="
               + cur.getString(0)
               + ";");
       Timber.i("MetaDB:: Store custom dictionary (%d) for deck %d", dictionary, did);
     } else {
       mMetaDb.execSQL(
           "INSERT INTO customDictionary (did, dictionary) VALUES (?, ?)",
           new Object[] {did, dictionary});
       Timber.i("MetaDB:: Store custom dictionary (%d) for deck %d", dictionary, did);
     }
   } catch (Exception e) {
     Timber.e(e, "Error storing custom dictionary to MetaDB ");
   } finally {
     if (cur != null && !cur.isClosed()) {
       cur.close();
     }
   }
 }
Example #8
0
 /**
  * Stores the state of the whiteboard for a given deck.
  *
  * @param state 1 if the whiteboard should be shown, 0 otherwise
  */
 public static void storeWhiteboardState(Context context, long did, boolean whiteboardState) {
   int state = (whiteboardState) ? 1 : 0;
   openDBIfClosed(context);
   Cursor cur = null;
   try {
     cur = mMetaDb.rawQuery("SELECT _id FROM whiteboardState" + " WHERE did  = " + did, null);
     if (cur.moveToNext()) {
       mMetaDb.execSQL(
           "UPDATE whiteboardState "
               + "SET did = "
               + did
               + ", "
               + "state="
               + Integer.toString(state)
               + " "
               + "WHERE _id="
               + cur.getString(0)
               + ";");
       Timber.d("Store whiteboard state (%d) for deck %d", state, did);
     } else {
       mMetaDb.execSQL(
           "INSERT INTO whiteboardState (did, state) VALUES (?, ?)", new Object[] {did, state});
       Timber.d("Store whiteboard state (%d) for deck %d", state, did);
     }
   } catch (Exception e) {
     Timber.e(e, "Error storing whiteboard state in MetaDB ");
   } finally {
     if (cur != null && !cur.isClosed()) {
       cur.close();
     }
   }
 }
  private synchronized void loadSubscriptions() {
    mEnabledExtensions = new ArrayList<>();
    mSubscriptions = new HashMap<>();
    mTokens = new HashMap<>();

    String serializedSubscriptions = mSharedPrefs.getString(PREF_SUBSCRIPTIONS, null);
    if (serializedSubscriptions == null) {
      setDefaultEnabledExtensions();
      return;
    }

    JSONArray jsonArray;
    try {
      jsonArray = new JSONArray(serializedSubscriptions);
    } catch (JSONException e) {
      Timber.e(e, "Deserializing subscriptions failed");
      return;
    }

    for (int i = 0; i < jsonArray.length(); i++) {
      String subscription = jsonArray.optString(i, null);
      if (subscription == null) {
        continue;
      }
      String[] arr = subscription.split("\\|", 2);
      ComponentName extension = ComponentName.unflattenFromString(arr[0]);
      String token = arr[1];
      mEnabledExtensions.add(extension);
      mSubscriptions.put(extension, token);
      mTokens.put(token, extension);
      Timber.d("Restored subscription: " + extension + " token: " + token);
    }
  }
  private void enableExtension(ComponentName extension) {
    if (extension == null) {
      Timber.e("enableExtension: empty extension");
    }

    if (mSubscriptions.containsKey(extension)) {
      // already subscribed
      Timber.d("enableExtension: already subscribed to " + extension);
      return;
    }

    // subscribe
    String token = UUID.randomUUID().toString();
    while (mTokens.containsKey(token)) {
      // create another UUID on collision
      /**
       * As the number of enabled extensions is rather low compared to the UUID number space we
       * shouldn't have to worry about this ever looping.
       */
      token = UUID.randomUUID().toString();
    }
    Timber.d("enableExtension: subscribing to " + extension);
    mSubscriptions.put(extension, token);
    mTokens.put(token, extension);
    mContext.startService(
        new Intent(IncomingConstants.ACTION_SUBSCRIBE)
            .setComponent(extension)
            .putExtra(IncomingConstants.EXTRA_SUBSCRIBER_COMPONENT, mSubscriberComponentName)
            .putExtra(IncomingConstants.EXTRA_TOKEN, token));
  }
Example #11
0
  /** @return the current video conversion progress in % (0 to 1) */
  public float getVideoConversionProgress(VideoConversion conversion) {
    if (!conversion.getProgressFile().exists()) return 0;

    // amount of frames in this video
    int totalFrames = conversion.getImageCount() * FRAMERATE * IMAGE_LENGTH_IN_SECONDS;

    // read progress file
    BufferedReader reader = null;
    try {
      reader = new BufferedReader(new FileReader(conversion.getProgressFile()));
      long currentFrame = 0;
      String line;
      while ((line = reader.readLine()) != null) {
        currentFrame = Integer.valueOf(line.substring(6)); // reads first line "frame=<number>"
        for (int i = 0; i < 8; ++i) reader.readLine(); // reads the 9 additional progress lines
      }
      return ((float) currentFrame) / totalFrames;

    } catch (IOException e) {
      Timber.e("failed to read progress", e);
      return 0;
    } finally {
      ioUtils.close(reader);
    }
  }
Example #12
0
 private void sendError(Bundle resultData) {
   Timber.e("Error receiving result");
   BaseCommand command = resultData.getParcelable(ARG_COMMAND_CLASS);
   if (command instanceof SyncContactsCommand) {
     _bus.post(new SyncAllContactsErrorEvent());
   }
 }
Example #13
0
  /*
   * Starts an appropriate intent or dialog for user interaction to resolve
   * the current error preventing the user from being signed in. This could be
   * a dialog allowing the user to select an account, an activity allowing the
   * user to consent to the permissions being requested by your app, a setting
   * to enable device networking, etc.
   */
  private void resolveSignInError() {
    if (mSignInIntent != null) {
      // We have an intent which will allow our user to sign in or
      // resolve an error. For example if the user needs to
      // select an account to sign in with, or if they need to consent
      // to the permissions your app is requesting.

      try {
        // Send the pending intent that we stored on the most recent
        // OnConnectionFailed callback. This will allow the user to
        // resolve the error currently preventing our connection to
        // Google Play services.
        mSignInProgress = STATE_IN_PROGRESS;
        startIntentSenderForResult(mSignInIntent.getIntentSender(), RC_SIGN_IN, null, 0, 0, 0);
      } catch (SendIntentException e) {
        Timber.e(TAG, "Sign in intent could not be sent: " + e.getLocalizedMessage());
        // The intent was canceled before it was sent. Attempt to
        // connect to
        // get an updated ConnectionResult.
        mSignInProgress = STATE_SIGN_IN;
        mGoogleApiClient.connect();
      }
    } else {
      // Google Play services wasn't able to provide an intent for some
      // error types, so we show the default Google Play services error
      // dialog which may still start an intent on our behalf if the
      // user can resolve the issue.
      showDialog(DIALOG_PLAY_SERVICES_ERROR);
    }
  }
Example #14
0
 /** Pulls bitmap from diskcache */
 private @Nullable ParcelFileDescriptor createPipe(final ArtInfo artInfo) {
   final byte[] bytes = mL2Cache.getBytes(artInfo.cacheKey());
   if (bytes == null) {
     return null;
   }
   try {
     final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
     final OutputStream out = new ParcelFileDescriptor.AutoCloseOutputStream(pipe[1]);
     final ParcelFileDescriptor in = pipe[0];
     final Scheduler.Worker worker = mScheduler.createWorker();
     worker.schedule(
         new Action0() {
           @Override
           public void call() {
             try {
               IOUtils.write(bytes, out);
               out.flush();
             } catch (IOException e) {
               Timber.w("createPipe(e=%s) for %s", e.getMessage(), artInfo);
             } finally {
               IOUtils.closeQuietly(out);
               worker.unsubscribe();
             }
           }
         });
     return in;
   } catch (IOException e) {
     Timber.e(e, "createPipe() for %s", artInfo);
     return null;
   }
 }
 public <T> void unregister(T subscriber) {
   try {
     EventBus.getDefault().unregister(subscriber);
   } catch (EventBusException e) {
     Timber.e(e, "The object [" + subscriber + "] was not registered when trying to unregister!");
   }
 }
Example #16
0
 /**
  * Returns the language associated with the given deck, model and card model, for the given type.
  *
  * @param qa the part of the card for which to store the association, {@link
  *     #LANGUAGES_QA_QUESTION}, {@link #LANGUAGES_QA_ANSWER}, or {@link #LANGUAGES_QA_UNDEFINED}
  *     return the language associate with the type, as a two-characters, lowercase string, or the
  *     empty string if no association is defined
  */
 public static String getLanguage(Context context, long did, int ord, int qa) {
   openDBIfClosed(context);
   String language = "";
   Cursor cur = null;
   try {
     String query =
         "SELECT language FROM languages "
             + "WHERE did = "
             + did
             + " AND ord = "
             + ord
             + " AND qa = "
             + qa
             + " "
             + "LIMIT 1";
     cur = mMetaDb.rawQuery(query, null);
     Timber.v("getLanguage: %s", query);
     if (cur.moveToNext()) {
       language = cur.getString(0);
     }
   } catch (Exception e) {
     Timber.e(e, "Error fetching language ");
   } finally {
     if (cur != null && !cur.isClosed()) {
       cur.close();
     }
   }
   return language;
 }
  public static void store(List<Category> categories) {
    if (categories == null || categories.size() == 0) {
      return;
    }

    SQLiteDatabase database = new ZhihuDatabase(App.getAppContext()).getWritableDatabase();
    database.beginTransaction();
    boolean newInsert = false;
    try {
      for (Category category : categories) {
        Cursor cursor =
            database.rawQuery(
                buildCategoryQueryUri(AppConstant.CATEGORY_EXIST_SQL, category), null);
        if (cursor == null || cursor.getCount() == 0) {
          save(category, database);
          newInsert = true;
        }
        IOUtils.close(cursor);
      }
      database.setTransactionSuccessful();
      if (newInsert) {
        App.getAppContext()
            .getContentResolver()
            .notifyChange(ZhihuProvider.CATEGORY_CONTENT_URI, null);
      }
    } catch (Exception e) {
      Timber.e(e, PersistUtils.class.getSimpleName());
    } finally {
      database.endTransaction();
    }
    // App.getAppContext().getContentResolver().notifyChange();
    IOUtils.close(database);
  }
Example #18
0
 /**
  * Return the current status of the widget.
  *
  * @return an int array, containing due, progress, eta
  */
 public static int[] getWidgetSmallStatus(Context context) {
   openDBIfClosed(context);
   Cursor cursor = null;
   try {
     cursor =
         mMetaDb.query(
             "smallWidgetStatus",
             new String[] {"progress", "left", "eta"},
             null,
             null,
             null,
             null,
             null);
     while (cursor.moveToNext()) {
       return (new int[] {cursor.getInt(0), cursor.getInt(1), cursor.getInt(2)});
     }
   } catch (SQLiteException e) {
     Timber.e(e, "Error while querying widgetStatus");
   } finally {
     if (cursor != null && !cursor.isClosed()) {
       cursor.close();
     }
   }
   return null;
 }
Example #19
0
  public static void sendMavlinkMessage(MavLinkDrone drone, MavlinkMessageWrapper messageWrapper) {
    if (drone == null || messageWrapper == null) return;

    MAVLinkMessage message = messageWrapper.getMavLinkMessage();
    if (message == null) return;

    message.compid = drone.getCompid();
    message.sysid = drone.getSysid();

    // Set the target system and target component for MAVLink messages that support those
    // attributes.
    try {
      Class<?> tempMessage = message.getClass();
      Field target_system = tempMessage.getDeclaredField("target_system");
      Field target_component = tempMessage.getDeclaredField("target_component");

      target_system.setByte(message, (byte) message.sysid);
      target_component.setByte(message, (byte) message.compid);
    } catch (NoSuchFieldException
        | SecurityException
        | IllegalAccessException
        | IllegalArgumentException
        | ExceptionInInitializerError e) {
      Timber.e(e, e.getMessage());
    }

    drone.getMavClient().sendMavMessage(message, null);
  }
Example #20
0
  private Object readValueFromDisk(InputStream is) throws IOException {
    BufferedReader fss = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    String className = fss.readLine();

    if (className == null) {
      return null;
    }

    String line = null;
    String content = "";
    while ((line = fss.readLine()) != null) {
      content += line;
    }

    fss.close();

    Class<?> clazz;
    try {
      if (className.contains("google")) {
        clazz = Class.forName(className);
        return mJsonFactory.createJsonParser(content).parseAndClose(clazz, null);
      } else {
        clazz = Class.forName(className);
        return mGson.fromJson(content, clazz);
      }
    } catch (IllegalArgumentException e) {
      Timber.e("Deserializing from disk failed", e);
      return null;
    } catch (ClassNotFoundException e) {
      throw new IOException(e.getMessage());
    }
  }
Example #21
0
  private void initializeSubscriptions() {
    if (downloadsSubscription != null && !downloadsSubscription.isUnsubscribed())
      downloadsSubscription.unsubscribe();

    if (threadsNumberSubscription != null && !threadsNumberSubscription.isUnsubscribed())
      threadsNumberSubscription.unsubscribe();

    threadsNumberSubscription =
        preferences.downloadThreads().asObservable().subscribe(threadsNumber::onNext);

    downloadsSubscription =
        downloadsQueueSubject
            .lift(new DynamicConcurrentMergeOperator<>(this::downloadChapter, threadsNumber))
            .onBackpressureBuffer()
            .observeOn(AndroidSchedulers.mainThread())
            .map(download -> areAllDownloadsFinished())
            .subscribe(
                finished -> {
                  if (finished) {
                    DownloadService.stop(context);
                  }
                },
                e -> Timber.e(e.getCause(), e.getMessage()));

    if (!isRunning) {
      isRunning = true;
      runningSubject.onNext(true);
    }
  }
  private int importFile(File importPath, ImporterExporter importer) {
    File file = new File(importPath, importer.getFileName());
    if (!file.exists() || !file.canRead()) {
      return ERROR_FILE_ACCESS;
    }

    importer.initializeImport(mContext);

    try {
      InputStream in = new FileInputStream(file);

      Gson gson = new Gson();

      JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
      reader.beginArray();

      while (reader.hasNext()) {
        importer.importRecord(mContext, gson, reader);
      }

      reader.endArray();
      reader.close();
    } catch (JsonParseException | IOException e) {
      // the given Json might not be valid or unreadable
      Timber.e(e, "JSON show import failed");
      return ERROR;
    }

    return SUCCESS;
  }
Example #23
0
 public static void postErrorEvent(int errorCode, ICommandListener listener) {
   if (listener != null) {
     try {
       listener.onError(errorCode);
     } catch (RemoteException e) {
       Timber.e(e, e.getMessage());
     }
   }
 }
Example #24
0
 public static void postSuccessEvent(ICommandListener listener) {
   if (listener != null) {
     try {
       listener.onSuccess();
     } catch (RemoteException e) {
       Timber.e(e, e.getMessage());
     }
   }
 }
Example #25
0
  /**
   * Eagerly creates a pipe, then blocks on a background thread while we wait for the fetcher to
   * return the bitmap, simply closing the pipe if no art was found
   */
  private @Nullable ParcelFileDescriptor createPipe2(final ArtInfo artInfo) {
    try {
      final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
      final OutputStream out = new ParcelFileDescriptor.AutoCloseOutputStream(pipe[1]);
      final ParcelFileDescriptor in = pipe[0];
      final Scheduler.Worker worker = mScheduler.createWorker();
      worker.schedule(
          new Action0() {
            @Override
            public void call() {
              OptionalBitmap bitmap = null;
              ArtworkFetcherService.Connection binder = null;
              try {
                // make a new request and wait for it to come in.
                binder = ArtworkFetcherService.bindService(getContext());
                final BlockingQueue<OptionalBitmap> queue = new LinkedBlockingQueue<>(1);
                final CompletionListener listener =
                    new CompletionListener() {
                      @Override
                      public void onError(Throwable e) {
                        Timber.w("onError(%s) for %s", e.getMessage(), artInfo);
                        queue.offer(new OptionalBitmap(null));
                      }

                      @Override
                      public void onNext(Bitmap o) {
                        queue.offer(new OptionalBitmap(o));
                      }
                    };
                if (!binder.getService().newRequest(artInfo, listener)) {
                  throw new InterruptedException("Enqueue failed");
                }
                bitmap = queue.take();
                if (bitmap.hasBitmap()) {
                  byte[] bytes = mL2Cache.bitmapToBytes(bitmap.getBitmap());
                  IOUtils.write(bytes, out);
                  out.flush();
                }
              } catch (InterruptedException | IOException e) {
                Timber.w("createPipe2(e=%s) for %s", e.getMessage(), artInfo);
                if (binder != null) {
                  binder.getService().cancelRequest(artInfo);
                }
              } finally {
                if (bitmap != null) bitmap.recycle();
                IOUtils.closeQuietly(binder);
                IOUtils.closeQuietly(out);
                worker.unsubscribe();
              }
            }
          });
      return in;
    } catch (IOException e) {
      Timber.e(e, "createPipe2() for %s", artInfo);
      return null;
    }
  }
Example #26
0
 public void setAccentColor(int accentColor) {
   try {
     Field cursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
     cursorDrawableRes.setAccessible(true);
     cursorDrawableRes.set(this, matchZColorToCursorResourceID(accentColor));
   } catch (Exception e) {
     Timber.e(e, "Failed setting custom cursor color");
   }
 }
Example #27
0
  @Override
  public void retrieveStaleApplications() {
    SubscriptionHelper.unsubscribe(retrievalSubscription);
    retrievalSubscription =
        interactor
            .getAppEntryList()
            .zipWith(
                interactor.getActiveApplicationPackageNames().toList(),
                (allEntries, packageNames) -> {
                  final Set<PadLockEntry.AllEntries> liveLocations = new HashSet<>();
                  final Set<String> stalePackageNames = new HashSet<>();
                  // Remove all active applications from the list of entries
                  for (final String packageName : packageNames) {
                    Timber.i("Look for package: %s", packageName);
                    final List<PadLockEntry.AllEntries> foundLocations = new ArrayList<>();
                    //noinspection Convert2streamapi
                    for (final PadLockEntry.AllEntries entry : allEntries) {
                      if (entry.packageName().equals(packageName)) {
                        foundLocations.add(entry);
                      }
                    }

                    liveLocations.addAll(foundLocations);
                  }

                  // Remove any found locations
                  for (final PadLockEntry.AllEntries liveLocation : liveLocations) {
                    Timber.d(
                        "Remove live location: %s %s",
                        liveLocation.packageName(), liveLocation.activityName());
                    allEntries.remove(liveLocation);
                  }

                  // The remaining entries in the database are stale
                  for (final PadLockEntry.AllEntries entry : allEntries) {
                    Timber.i(
                        "Stale database entry: %s %s", entry.packageName(), entry.activityName());
                    stalePackageNames.add(entry.packageName());
                  }

                  return stalePackageNames;
                })
            .flatMap(Observable::from)
            .sorted(String::compareToIgnoreCase)
            .subscribeOn(getSubscribeScheduler())
            .observeOn(getObserveScheduler())
            .subscribe(
                s -> getView(view -> view.onStaleApplicationRetrieved(s)),
                throwable -> {
                  Timber.e(throwable, "onError retrieveStaleApplications");
                  getView(View::onRetrievalComplete);
                },
                () -> {
                  SubscriptionHelper.unsubscribe(retrievalSubscription);
                  getView(View::onRetrievalComplete);
                });
  }
 /** A safe way to get an instance of the Camera object. */
 private Camera getCameraInstance(boolean useFrontCamera) {
   Camera c = null;
   try {
     c = Camera.open(getCameraId(useFrontCamera));
   } catch (Exception e) {
     Timber.e(e, getString(R.string.lbl_camera_unavailable));
   }
   return c;
 }
Example #29
0
 public static void saveIntentInformation(Context context, String fields) {
   openDBIfClosed(context);
   try {
     mMetaDb.execSQL(
         "INSERT INTO intentInformation (fields) " + " VALUES (?);", new Object[] {fields});
     Timber.i("MetaDB:: Store intentInformation: " + fields);
   } catch (Exception e) {
     Timber.e(e, "Error storing intentInformation in MetaDB ");
   }
 }
Example #30
0
 @Override
 public void onCorruption(SQLiteDatabase db) {
   Timber.e("The database has been corrupted...");
   AnkiDroidApp.sendExceptionReport(
       new RuntimeException("Database corrupted"),
       "AnkiDb.MyDbErrorHandler.onCorruption",
       "Db has been corrupted ");
   CollectionHelper.getInstance().closeCollection(false);
   DatabaseErrorDialog.databaseCorruptFlag = true;
 }