Esempio n. 1
0
  private void saveConfiguration(FilterListItem filterListItem) {
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    String sql = null, contentValuesString = null, title = null;

    if (filterListItem != null && filterListItem instanceof Filter) {
      sql = ((Filter) filterListItem).getSqlQuery();
      ContentValues values = ((Filter) filterListItem).valuesForNewTasks;
      if (values != null)
        contentValuesString = AndroidUtilities.contentValuesToSerializedString(values);
      title = ((Filter) filterListItem).title;
    }

    Preferences.setString(WidgetConfigActivity.PREF_TITLE + mAppWidgetId, title);
    Preferences.setString(WidgetConfigActivity.PREF_SQL + mAppWidgetId, sql);
    Preferences.setString(WidgetConfigActivity.PREF_VALUES + mAppWidgetId, contentValuesString);

    if (filterListItem instanceof FilterWithCustomIntent) {
      String flattenedName =
          ((FilterWithCustomIntent) filterListItem).customTaskList.flattenToString();
      Preferences.setString(WidgetConfigActivity.PREF_CUSTOM_INTENT + mAppWidgetId, flattenedName);
      String flattenedExtras =
          AndroidUtilities.bundleToSerializedString(
              ((FilterWithCustomIntent) filterListItem).customExtras);
      if (flattenedExtras != null)
        Preferences.setString(
            WidgetConfigActivity.PREF_CUSTOM_EXTRAS + mAppWidgetId, flattenedExtras);
    }
  }
  /** @param resource if null, updates all resources */
  @Override
  public void updatePreferences(Preference preference, Object value) {
    Resources r = getResources();

    if (r.getString(R.string.p_rmd_quietStart).equals(preference.getKey())) {
      int index =
          AndroidUtilities.indexOf(
              r.getStringArray(R.array.EPr_quiet_hours_start_values), (String) value);
      Preference endPreference = findPreference(getString(R.string.p_rmd_quietEnd));
      if (index <= 0) {
        preference.setSummary(r.getString(R.string.rmd_EPr_quiet_hours_desc_none));
        endPreference.setEnabled(false);
      } else {
        String setting = r.getStringArray(R.array.EPr_quiet_hours_start)[index];
        preference.setSummary(r.getString(R.string.rmd_EPr_quiet_hours_start_desc, setting));
        endPreference.setEnabled(true);
      }
    } else if (r.getString(R.string.p_rmd_quietEnd).equals(preference.getKey())) {
      int index =
          AndroidUtilities.indexOf(
              r.getStringArray(R.array.EPr_quiet_hours_end_values), (String) value);
      int quietHoursStart = Preferences.getIntegerFromString(R.string.p_rmd_quietStart, -1);
      if (index == -1 || quietHoursStart == -1)
        preference.setSummary(r.getString(R.string.rmd_EPr_quiet_hours_desc_none));
      else {
        String setting = r.getStringArray(R.array.EPr_quiet_hours_end)[index];
        preference.setSummary(r.getString(R.string.rmd_EPr_quiet_hours_end_desc, setting));
      }
    } else if (r.getString(R.string.p_rmd_time).equals(preference.getKey())) {
      int index =
          AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_rmd_time_values), (String) value);
      String setting = r.getStringArray(R.array.EPr_rmd_time)[index];
      preference.setSummary(r.getString(R.string.rmd_EPr_rmd_time_desc, setting));
    } else if (r.getString(R.string.p_rmd_ringtone).equals(preference.getKey())) {
      if (value == null
          || "content://settings/system/notification_sound".equals(value)) // $NON-NLS-1$
      preference.setSummary(r.getString(R.string.rmd_EPr_ringtone_desc_default));
      else if ("".equals(value)) // $NON-NLS-1$
      preference.setSummary(r.getString(R.string.rmd_EPr_ringtone_desc_silent));
      else preference.setSummary(r.getString(R.string.rmd_EPr_ringtone_desc_custom));
    } else if (r.getString(R.string.p_rmd_persistent).equals(preference.getKey())) {
      if ((Boolean) value)
        preference.setSummary(r.getString(R.string.rmd_EPr_persistent_desc_true));
      else preference.setSummary(r.getString(R.string.rmd_EPr_persistent_desc_false));
    } else if (r.getString(R.string.p_rmd_maxvolume).equals(preference.getKey())) {
      if ((Boolean) value)
        preference.setSummary(r.getString(R.string.rmd_EPr_multiple_maxvolume_desc_true));
      else preference.setSummary(r.getString(R.string.rmd_EPr_multiple_maxvolume_desc_false));
    } else if (r.getString(R.string.p_rmd_vibrate).equals(preference.getKey())) {
      if ((Boolean) value) preference.setSummary(r.getString(R.string.rmd_EPr_vibrate_desc_true));
      else preference.setSummary(r.getString(R.string.rmd_EPr_vibrate_desc_false));
    } else if (r.getString(R.string.p_rmd_nagging).equals(preference.getKey())) {
      if ((Boolean) value) preference.setSummary(r.getString(R.string.rmd_EPr_nagging_desc_true));
      else preference.setSummary(r.getString(R.string.rmd_EPr_nagging_desc_false));
    } else if (r.getString(R.string.p_rmd_snooze_dialog).equals(preference.getKey())) {
      if (value == null || ((Boolean) value) == true)
        preference.setSummary(r.getString(R.string.rmd_EPr_snooze_dialog_desc_true));
      else preference.setSummary(r.getString(R.string.rmd_EPr_snooze_dialog_desc_false));
    }
  }
Esempio n. 3
0
  private void showFile(final Metadata m) {
    final String fileType =
        m.containsNonNullValue(FileMetadata.FILE_TYPE)
            ? m.getValue(FileMetadata.FILE_TYPE)
            : FileMetadata.FILE_TYPE_OTHER;
    final String filePath = m.getValue(FileMetadata.FILE_PATH);

    if (fileType.startsWith(FileMetadata.FILE_TYPE_AUDIO)) {
      RecognizerApi.play(
          activity,
          m.getValue(FileMetadata.FILE_PATH),
          new PlaybackExceptionHandler() {
            @Override
            public void playbackFailed(String file) {
              showFromIntent(filePath, fileType);
            }
          });
    } else if (fileType.startsWith(FileMetadata.FILE_TYPE_IMAGE)) {
      AlertDialog image = new AlertDialog.Builder(activity).create();
      ImageView imageView = new ImageView(activity);
      imageView.setLayoutParams(
          new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
      Bitmap bitmap = AndroidUtilities.readScaledBitmap(filePath);

      if (bitmap == null) {
        Toast.makeText(activity, R.string.file_err_memory, Toast.LENGTH_LONG).show();
        return;
      }

      imageView.setImageBitmap(bitmap);
      image.setView(imageView);

      image.setButton(
          activity.getString(R.string.DLG_close),
          new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface d, int which) {
              return;
            }
          });
      image.show();
    } else {
      String useType = fileType;
      if (fileType.equals(FileMetadata.FILE_TYPE_OTHER)) {
        String extension = AndroidUtilities.getFileExtension(filePath);

        MimeTypeMap map = MimeTypeMap.getSingleton();
        String guessedType = map.getMimeTypeFromExtension(extension);
        if (!TextUtils.isEmpty(guessedType)) useType = guessedType;
        if (useType != guessedType) {
          m.setValue(FileMetadata.FILE_TYPE, useType);
          metadataService.save(m);
        }
      }
      showFromIntent(filePath, useType);
    }
  }
Esempio n. 4
0
  @Override
  public void onPause() {
    super.onPause();

    AndroidUtilities.tryUnregisterReceiver(getActivity(), detailReceiver);
    AndroidUtilities.tryUnregisterReceiver(getActivity(), refreshReceiver);
    syncActionHelper.unregister();

    backgroundTimer.cancel();
  }
Esempio n. 5
0
 public static void showEulaBasic(Activity activity) {
   final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
   builder.setTitle(R.string.DLG_eula_title);
   builder.setMessage(AndroidUtilities.readFile(activity, R.raw.eula));
   builder.setNeutralButton(android.R.string.ok, null);
   builder.show();
 }
Esempio n. 6
0
 /** Comments button in action bar was clicked */
 protected void handleCommentsButtonClicked() {
   Intent intent = new Intent(getActivity(), TagUpdatesActivity.class);
   intent.putExtra(TagViewFragment.EXTRA_TAG_DATA, getActiveTagData());
   startActivity(intent);
   AndroidUtilities.callOverridePendingTransition(
       getActivity(), R.anim.slide_left_in, R.anim.slide_left_out);
 }
Esempio n. 7
0
 private void handleActivityNotFound(String fileType) {
   if (fileType.startsWith(FileMetadata.FILE_TYPE_AUDIO)) {
     searchMarket(
         "com.clov4r.android.nil",
         R.string.search_market_audio_title,
         R.string.search_market_audio); // $NON-NLS-1$
   } else if (fileType.equals(FileMetadata.FILE_TYPE_PDF)) {
     searchMarket(
         "com.adobe.reader",
         R.string.search_market_pdf_title,
         R.string.search_market_pdf); // $NON-NLS-1$
   } else if (AndroidUtilities.indexOf(FileMetadata.MS_FILETYPES, fileType) >= 0) {
     searchMarket(
         "com.dataviz.docstogo",
         R.string.search_market_ms_title,
         R.string.search_market_ms); // $NON-NLS-1$
   } else {
     DialogUtilities.okDialog(
         activity,
         activity.getString(R.string.file_type_unhandled_title),
         0,
         activity.getString(R.string.file_type_unhandled),
         null);
   }
 }
Esempio n. 8
0
  /**
   * Displays the EULA if necessary. This method should be called from the onCreate() method of your
   * main Activity.
   *
   * @param activity The Activity to finish if the user rejects the EULA
   */
  public static void showEula(final Activity activity) {
    if (!new Eula().shouldShowEula(activity)) return;

    final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setTitle(R.string.DLG_eula_title);
    builder.setCancelable(true);
    builder.setPositiveButton(
        R.string.DLG_accept,
        new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            accept(activity);
          }
        });
    builder.setNegativeButton(
        R.string.DLG_decline,
        new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            refuse(activity);
          }
        });
    builder.setOnCancelListener(
        new DialogInterface.OnCancelListener() {
          @Override
          public void onCancel(DialogInterface dialog) {
            refuse(activity);
          }
        });
    builder.setMessage(AndroidUtilities.readFile(activity, R.raw.eula));
    builder.show();
  }
Esempio n. 9
0
 public boolean handleOptionsMenuItemSelected(int id, Intent intent) {
   switch (id) {
     case MENU_ADDONS_ID:
       StatisticsService.reportEvent(StatisticsConstants.TLA_MENU_ADDONS);
       intent = new Intent(getActivity(), AddOnActivity.class);
       startActivityForResult(intent, ACTIVITY_ADDONS);
       return true;
     case MENU_SORT_ID:
       StatisticsService.reportEvent(StatisticsConstants.TLA_MENU_SORT);
       AlertDialog dialog =
           SortSelectionActivity.createDialog(
               getActivity(), hasDraggableOption(), this, sortFlags, sortSort);
       dialog.show();
       return true;
     case MENU_SYNC_ID:
       StatisticsService.reportEvent(StatisticsConstants.TLA_MENU_SYNC);
       syncActionHelper.performSyncAction();
       return true;
     case MENU_ADDON_INTENT_ID:
       AndroidUtilities.startExternalIntent(getActivity(), intent, ACTIVITY_MENU_EXTERNAL);
       return true;
     case MENU_NEW_FILTER_ID:
       intent = new Intent(getActivity(), CustomFilterActivity.class);
       getActivity().startActivityForResult(intent, ACTIVITY_REQUEST_NEW_FILTER);
       return true;
   }
   return false;
 }
Esempio n. 10
0
 @Override
 public void finish() {
   InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
   imm.hideSoftInputFromWindow(filterName.getWindowToken(), 0);
   super.finish();
   AndroidUtilities.callOverridePendingTransition(
       this, R.anim.slide_right_in, R.anim.slide_right_out);
 }
Esempio n. 11
0
 /**
  * Merges set values with those coming from another source, keeping the existing value if one
  * already exists
  */
 public synchronized void mergeWithoutReplacement(ContentValues other) {
   if (setValues == null) {
     setValues = new ContentValues();
   }
   for (Entry<String, Object> item : other.valueSet()) {
     if (setValues.containsKey(item.getKey())) {
       continue;
     }
     AndroidUtilities.putInto(setValues, item.getKey(), item.getValue());
   }
 }
Esempio n. 12
0
    private Filter getFilter(int widgetId) {
      // base our filter off the inbox filter, replace stuff if we have it
      Filter filter = CoreFilterExposer.buildInboxFilter(getResources());
      String sql = Preferences.getStringValue(WidgetConfigActivity.PREF_SQL + widgetId);
      if (sql != null) filter.sqlQuery = sql;
      String title = Preferences.getStringValue(WidgetConfigActivity.PREF_TITLE + widgetId);
      if (title != null) filter.title = title;
      String contentValues =
          Preferences.getStringValue(WidgetConfigActivity.PREF_VALUES + widgetId);
      if (contentValues != null)
        filter.valuesForNewTasks =
            AndroidUtilities.contentValuesFromSerializedString(contentValues);

      return filter;
    }
Esempio n. 13
0
  @Override
  public void updatePreferences(final Preference preference, Object value) {
    final Resources r = getResources();

    if (r.getString(R.string.p_showNotes).equals(preference.getKey())) {
      if (value != null && !(Boolean) value)
        preference.setSummary(R.string.EPr_showNotes_desc_disabled);
      else preference.setSummary(R.string.EPr_showNotes_desc_enabled);
      if ((Boolean) value != Preferences.getBoolean(preference.getKey(), false)) {
        taskService.clearDetails(Criterion.all);
        Flags.set(Flags.REFRESH);
      }
    } else if (r.getString(R.string.p_transparent).equals(preference.getKey())) {
      if (AndroidUtilities.getSdkVersion() < 5) {
        preference.setEnabled(false);
        preference.setSummary(R.string.EPr_transparent_desc_unsupported);
      } else if (value != null && !(Boolean) value)
        preference.setSummary(R.string.EPr_transparent_desc_disabled);
      else preference.setSummary(R.string.EPr_transparent_desc_enabled);
    }

    // statistics service
    else if (r.getString(R.string.p_statistics).equals(preference.getKey())) {
      if (value != null && !(Boolean) value)
        preference.setSummary(R.string.EPr_statistics_desc_disabled);
      else preference.setSummary(R.string.EPr_statistics_desc_enabled);
    }

    // voice input and output
    if (!addOnService.hasPowerPack()) return;

    if (r.getString(R.string.p_voiceInputEnabled).equals(preference.getKey())) {
      if (value != null && !(Boolean) value)
        preference.setSummary(R.string.EPr_voiceInputEnabled_desc_disabled);
      else preference.setSummary(R.string.EPr_voiceInputEnabled_desc_enabled);
      onVoiceInputStatusChanged(preference, (Boolean) value);
    } else if (r.getString(R.string.p_voiceRemindersEnabled).equals(preference.getKey())) {
      if (value != null && !(Boolean) value)
        preference.setSummary(R.string.EPr_voiceRemindersEnabled_desc_disabled);
      else preference.setSummary(R.string.EPr_voiceRemindersEnabled_desc_enabled);
      onVoiceReminderStatusChanged(preference, (Boolean) value);
    } else if (r.getString(R.string.p_voiceInputCreatesTask).equals(preference.getKey())) {
      if (value != null && !(Boolean) value)
        preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_disabled);
      else preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_enabled);
    }
  }
Esempio n. 14
0
  /**
   * Loads action item from the given intent
   *
   * @param intent
   */
  @SuppressWarnings("nls")
  protected void loadItem(Intent intent) {
    if (model != null) {
      // came from bundle
      isNewTask = (model.getValue(Task.TITLE).length() == 0);
      return;
    }

    long idParam = intent.getLongExtra(TOKEN_ID, -1L);

    database.openForReading();
    if (idParam > -1L) {
      model = taskService.fetchById(idParam, Task.PROPERTIES);
    }

    // not found by id or was never passed an id
    if (model == null) {
      String valuesAsString = intent.getStringExtra(TOKEN_VALUES);
      ContentValues values = null;
      try {
        if (valuesAsString != null)
          values = AndroidUtilities.contentValuesFromSerializedString(valuesAsString);
      } catch (Exception e) {
        // oops, can't serialize
      }
      model = TaskListActivity.createWithValues(values, null, taskService, metadataService);
    }

    if (model.getValue(Task.TITLE).length() == 0) {
      StatisticsService.reportEvent("create-task");
      isNewTask = true;

      // set deletion date until task gets a title
      model.setValue(Task.DELETION_DATE, DateUtilities.now());
    } else {
      StatisticsService.reportEvent("edit-task");
    }

    if (model == null) {
      exceptionService.reportError("task-edit-no-task", new NullPointerException("model"));
      finish();
      return;
    }

    // clear notification
    Notifications.cancelNotifications(model.getId());
  }
Esempio n. 15
0
  public void pushMetadataOnSave(Metadata model, GtasksInvoker invoker) throws IOException {
    AndroidUtilities.sleepDeep(1000L);

    String taskId = model.getValue(GtasksMetadata.ID);
    String listId = model.getValue(GtasksMetadata.LIST_ID);
    String parent = gtasksMetadataService.getRemoteParentId(model);
    String priorSibling = gtasksMetadataService.getRemoteSiblingId(listId, model);

    MoveRequest move = new MoveRequest(invoker, taskId, listId, parent, priorSibling);
    com.google.api.services.tasks.model.Task result = move.push();
    // Update order metadata from result
    if (result != null) {
      model.setValue(GtasksMetadata.GTASKS_ORDER, Long.parseLong(result.getPosition()));
      model.putTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC, true);
      metadataDao.saveExisting(model);
    }
  }
Esempio n. 16
0
  private void setPath(File path) {
    if (path != null && path.exists()) {
      this.path = path.getAbsolutePath();

      File[] filesAsFile = path.listFiles(filter);
      AndroidUtilities.sortFilesByDateDesc(filesAsFile);

      files = new String[filesAsFile.length];
      for (int i = 0; i < files.length; i++) {
        files[i] = filesAsFile[i].getName();
      }

      setItems(files, this);
    } else {
      log.error("Cannot access sdcard.");
      setMessage(R.string.DLG_error_sdcard + "sdcard");
    }
  }
Esempio n. 17
0
 /** If database exists, no tasks but metadata, and a backup file exists, restore it */
 private void databaseRestoreIfEmpty(Context context) {
   try {
     if (AstridPreferences.getCurrentVersion() >= UpgradeService.V3_0_0
         && !context.getDatabasePath(database.getName()).exists()) {
       // we didn't have a database! restore latest file
       File directory = BackupConstants.defaultExportDirectory();
       if (!directory.exists()) {
         return;
       }
       File[] children = directory.listFiles();
       AndroidUtilities.sortFilesByDateDesc(children);
       if (children.length > 0) {
         TasksXmlImporter.importTasks(context, children[0].getAbsolutePath(), null);
       }
     }
   } catch (Exception e) {
     Log.w("astrid-database-restore", e); // $NON-NLS-1$
   }
 }
Esempio n. 18
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    new StartupService().onStartupApplication(this);

    setUpUIComponents();

    // disable keyboard until user requests it
    AndroidUtilities.suppressVirtualKeyboard(title);

    // if we were editing a task already, restore it
    if (savedInstanceState != null && savedInstanceState.containsKey(TASK_IN_PROGRESS)) {
      Task task = savedInstanceState.getParcelable(TASK_IN_PROGRESS);
      if (task != null) {
        model = task;
      }
    }

    setResult(RESULT_OK);
  }
Esempio n. 19
0
  /** Call sync method */
  private void invokeFetchList(
      final String model,
      final boolean manual,
      final ListItemProcessor<?> processor,
      final Runnable done,
      final String lastSyncKey,
      Object... params) {
    if (!checkForToken()) return;

    long serverFetchTime = manual ? 0 : Preferences.getLong("actfm_time_" + lastSyncKey, 0);
    final Object[] getParams =
        AndroidUtilities.concat(
            new Object[params.length + 4],
            params,
            "token",
            token,
            "modified_after",
            serverFetchTime);

    new Thread(
            new Runnable() {
              @Override
              public void run() {
                JSONObject result = null;
                try {
                  result = actFmInvoker.invoke(model + "_list", getParams);
                  JSONArray list = result.getJSONArray("list");
                  processor.process(list);
                  Preferences.setLong("actfm_time_" + lastSyncKey, result.optLong("time", 0));
                  Preferences.setLong("actfm_last_" + lastSyncKey, DateUtilities.now());

                  if (done != null) done.run();
                } catch (IOException e) {
                  handleException("io-exception-list-" + model, e);
                } catch (JSONException e) {
                  handleException("json: " + result.toString(), e);
                }
              }
            })
        .start();
  }
Esempio n. 20
0
  private void onVoiceInputStatusChanged(final Preference preference, boolean newValue) {
    if (!newValue) return;

    final Resources r = getResources();
    if (!VoiceRecognizer.voiceInputAvailable(this)) {
      if (AndroidUtilities.getSdkVersion() > 6) {
        DialogUtilities.okCancelDialog(
            this,
            r.getString(R.string.EPr_voiceInputInstall_dlg),
            new OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                voiceInputAssistant.showVoiceInputMarketSearch(
                    new OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog1, int which1) {
                        ((CheckBoxPreference) preference).setChecked(false);
                      }
                    });
              }
            },
            new OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                ((CheckBoxPreference) preference).setChecked(false);
              }
            });
      } else {
        DialogUtilities.okDialog(
            this,
            r.getString(R.string.EPr_voiceInputUnavailable_dlg),
            new OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog1, int which1) {
                ((CheckBoxPreference) preference).setChecked(false);
              }
            });
      }
    }
  }
Esempio n. 21
0
  public void showVoiceInputMarketSearch(DialogInterface.OnClickListener onFail) {
    String packageName;
    if (AndroidUtilities.getSdkVersion() <= 7) {
      packageName = "com.google.android.voicesearch.x";
    } else {
      packageName = "com.google.android.voicesearch";
    }

    // User wants to install voice search, take them to the market
    Intent marketIntent = Constants.MARKET_STRATEGY.generateMarketLink(packageName);
    if (activity != null) {
      try {
        if (marketIntent == null) {
          throw new ActivityNotFoundException("No market link supplied"); // $NON-NLS-1$
        }
        activity.startActivity(marketIntent);
      } catch (ActivityNotFoundException ane) {
        DialogUtilities.okDialog(
            activity, activity.getString(R.string.EPr_marketUnavailable_dlg), onFail);
      }
    }
  }
 public static Filter getTodayFilter(Resources r) {
   int themeFlags = ThemeService.getFilterThemeFlags();
   String todayTitle = AndroidUtilities.capitalize(r.getString(R.string.today));
   ContentValues todayValues = new ContentValues();
   todayValues.put(Task.DUE_DATE.name, PermaSql.VALUE_NOON);
   Filter todayFilter =
       new Filter(
           todayTitle,
           todayTitle,
           new QueryTemplate()
               .where(
                   Criterion.and(
                       TaskCriteria.activeVisibleMine(),
                       Task.DUE_DATE.gt(0),
                       Task.DUE_DATE.lte(PermaSql.VALUE_EOD))),
           todayValues);
   todayFilter.listingIcon =
       ((BitmapDrawable)
               r.getDrawable(ThemeService.getDrawable(R.drawable.filter_calendar, themeFlags)))
           .getBitmap();
   return todayFilter;
 }
Esempio n. 23
0
  /** Synchronize with server when data changes */
  public void pushTaskOnSave(Task task, ContentValues values, GtasksInvoker invoker, boolean sleep)
      throws IOException {
    if (sleep) AndroidUtilities.sleepDeep(1000L); // Wait for metadata to be saved

    Metadata gtasksMetadata = gtasksMetadataService.getTaskMetadata(task.getId());
    com.google.api.services.tasks.model.Task remoteModel = null;
    boolean newlyCreated = false;

    String remoteId = null;
    String listId = Preferences.getStringValue(GtasksPreferenceService.PREF_DEFAULT_LIST);
    if (listId == null) {
      com.google.api.services.tasks.model.TaskList defaultList = invoker.getGtaskList(DEFAULT_LIST);
      if (defaultList != null) {
        listId = defaultList.getId();
        Preferences.setString(GtasksPreferenceService.PREF_DEFAULT_LIST, listId);
      } else {
        listId = DEFAULT_LIST;
      }
    }

    if (gtasksMetadata == null
        || !gtasksMetadata.containsNonNullValue(GtasksMetadata.ID)
        || TextUtils.isEmpty(gtasksMetadata.getValue(GtasksMetadata.ID))) { // Create case
      if (gtasksMetadata == null) {
        gtasksMetadata = GtasksMetadata.createEmptyMetadata(task.getId());
      }
      if (gtasksMetadata.containsNonNullValue(GtasksMetadata.LIST_ID)) {
        listId = gtasksMetadata.getValue(GtasksMetadata.LIST_ID);
      }

      remoteModel = new com.google.api.services.tasks.model.Task();
      newlyCreated = true;
    } else { // update case
      remoteId = gtasksMetadata.getValue(GtasksMetadata.ID);
      listId = gtasksMetadata.getValue(GtasksMetadata.LIST_ID);
      remoteModel = new com.google.api.services.tasks.model.Task();
      remoteModel.setId(remoteId);
    }

    // If task was newly created but without a title, don't sync--we're in the middle of
    // creating a task which may end up being cancelled
    if (newlyCreated
        && (!values.containsKey(Task.TITLE.name) || TextUtils.isEmpty(task.getValue(Task.TITLE)))) {
      return;
    }

    // Update the remote model's changed properties
    if (values.containsKey(Task.DELETION_DATE.name) && task.isDeleted()) {
      remoteModel.setDeleted(true);
    }

    if (values.containsKey(Task.TITLE.name)) {
      remoteModel.setTitle(task.getValue(Task.TITLE));
    }
    if (values.containsKey(Task.NOTES.name)) {
      remoteModel.setNotes(task.getValue(Task.NOTES));
    }
    if (values.containsKey(Task.DUE_DATE.name) && task.hasDueDate()) {
      remoteModel.setDue(GtasksApiUtilities.unixTimeToGtasksDueDate(task.getValue(Task.DUE_DATE)));
    }
    if (values.containsKey(Task.COMPLETION_DATE.name)) {
      if (task.isCompleted()) {
        remoteModel.setCompleted(
            GtasksApiUtilities.unixTimeToGtasksCompletionTime(task.getValue(Task.COMPLETION_DATE)));
        remoteModel.setStatus("completed"); // $NON-NLS-1$
      } else {
        remoteModel.setCompleted(null);
        remoteModel.setStatus("needsAction"); // $NON-NLS-1$
      }
    }

    if (!newlyCreated) {
      invoker.updateGtask(listId, remoteModel);
    } else {
      String parent = gtasksMetadataService.getRemoteParentId(gtasksMetadata);
      String priorSibling = gtasksMetadataService.getRemoteSiblingId(listId, gtasksMetadata);

      CreateRequest create = new CreateRequest(invoker, listId, remoteModel, parent, priorSibling);
      com.google.api.services.tasks.model.Task created = create.executePush();

      if (created != null) {
        // Update the metadata for the newly created task
        gtasksMetadata.setValue(GtasksMetadata.ID, created.getId());
        gtasksMetadata.setValue(GtasksMetadata.LIST_ID, listId);
      } else return;
    }

    task.setValue(Task.MODIFICATION_DATE, DateUtilities.now());
    gtasksMetadata.setValue(GtasksMetadata.LAST_SYNC, DateUtilities.now() + 1000L);
    metadataService.save(gtasksMetadata);
    task.putTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC, true);
    taskDao.saveExistingWithSqlConstraintCheck(task);
  }
Esempio n. 24
0
  private void sync() {
    try {
      int batchSize = 4;
      List<ClientToServerMessage<?>> messageBatch = new ArrayList<ClientToServerMessage<?>>();
      while (true) {
        synchronized (monitor) {
          while ((pendingMessages.isEmpty() && !timeForBackgroundSync())
              || !actFmPreferenceService.isLoggedIn()
              || !syncMigration) {
            try {
              if ((pendingMessages.isEmpty() || !actFmPreferenceService.isLoggedIn())
                  && notificationId >= 0) {
                notificationManager.cancel(notificationId);
                notificationId = -1;
              }
              monitor.wait();
              AndroidUtilities.sleepDeep(
                  500L); // Wait briefly for large database operations to finish (e.g. adding a task
                         // with several tags may trigger a message before all saves are done--fix
                         // this?)

              if (!syncMigration) {
                syncMigration =
                    Preferences.getBoolean(AstridNewSyncMigrator.PREF_SYNC_MIGRATION, false);
              }
            } catch (InterruptedException e) {
              // Ignored
            }
          }
        }

        boolean recordSyncSuccess = true;
        if (timeForBackgroundSync()) {
          repopulateQueueFromOutstandingTables();
          enqueueMessage(
              BriefMe.instantiateBriefMeForClass(
                  TaskListMetadata.class, NameMaps.PUSHED_AT_TASK_LIST_METADATA),
              DEFAULT_REFRESH_RUNNABLE);
          enqueueMessage(
              BriefMe.instantiateBriefMeForClass(Task.class, NameMaps.PUSHED_AT_TASKS),
              DEFAULT_REFRESH_RUNNABLE);
          enqueueMessage(
              BriefMe.instantiateBriefMeForClass(TagData.class, NameMaps.PUSHED_AT_TAGS),
              DEFAULT_REFRESH_RUNNABLE);
          enqueueMessage(
              BriefMe.instantiateBriefMeForClass(User.class, NameMaps.PUSHED_AT_USERS),
              DEFAULT_REFRESH_RUNNABLE);
          setTimeForBackgroundSync(false);
        }

        while (messageBatch.size() < batchSize && !pendingMessages.isEmpty()) {
          ClientToServerMessage<?> message = pendingMessages.remove(0);
          if (message != null) {
            messageBatch.add(message);
          }
        }

        if (!messageBatch.isEmpty() && checkForToken()) {
          JSONPayloadBuilder payload = new JSONPayloadBuilder();
          MultipartEntity entity = new MultipartEntity();
          boolean containsChangesHappened = false;
          for (int i = 0; i < messageBatch.size(); i++) {
            ClientToServerMessage<?> message = messageBatch.get(i);
            boolean success = payload.addMessage(message, entity);
            if (success) {
              if (message instanceof ChangesHappened) {
                containsChangesHappened = true;
              }
            } else {
              messageBatch.remove(i);
              i--;
            }
          }

          if (payload.getMessageCount() == 0) {
            messageBatch.clear();
            continue;
          }

          setupNotification();

          payload.addJSONObject(getClientVersion());

          JSONArray errors = null;
          try {
            JSONObject response =
                actFmInvoker.postSync(
                    payload.closeAndReturnString(), entity, containsChangesHappened, token);
            // process responses
            String time = response.optString("time");
            JSONArray serverMessagesJson = response.optJSONArray("messages");
            if (serverMessagesJson != null) {
              setWidgetSuppression(true);
              for (int i = 0; i < serverMessagesJson.length(); i++) {
                JSONObject serverMessageJson = serverMessagesJson.optJSONObject(i);
                if (serverMessageJson != null) {
                  ServerToClientMessage serverMessage =
                      ServerToClientMessage.instantiateMessage(serverMessageJson);
                  if (serverMessage != null) {
                    serverMessage.processMessage(time);
                  } else {
                    syncLog(
                        "Index "
                            + i
                            + " unable to instantiate message "
                            + serverMessageJson.toString());
                  }
                }
              }
              errors = response.optJSONArray("errors");
              boolean errorsExist = (errors != null && errors.length() > 0);
              replayOutstandingChanges(errorsExist);
              setWidgetSuppression(false);
            }

            batchSize = Math.max(12, Math.min(batchSize, messageBatch.size()) * 2);

            if (recordSyncSuccess) {
              actFmPreferenceService.setLastError(null, null);
              actFmPreferenceService.recordSuccessfulSync();
            }
          } catch (IOException e) {
            Log.e(ERROR_TAG, "IOException", e);
            batchSize = Math.max(batchSize / 2, 1);
          }

          Set<SyncMessageCallback> callbacksExecutedThisLoop = new HashSet<SyncMessageCallback>();
          Map<Integer, List<JSONArray>> errorMap = buildErrorMap(errors);
          for (int i = 0; i < messageBatch.size(); i++) {
            ClientToServerMessage<?> message = messageBatch.get(i);
            try {
              SyncMessageCallback r = pendingCallbacks.remove(message);
              if (r != null && !callbacksExecutedThisLoop.contains(r)) {
                List<JSONArray> errorList = errorMap.get(i);
                if (errorList == null || errorList.isEmpty()) {
                  r.runOnSuccess();
                } else {
                  r.runOnErrors(errorList);
                }

                callbacksExecutedThisLoop.add(r);
              }
            } catch (Exception e) {
              Log.e(ERROR_TAG, "Unexpected exception executing sync callback", e);
            }
          }

          messageBatch.clear();
        }
      }
    } catch (Exception e) {
      // In the worst case, restart thread if something goes wrong
      Log.e(ERROR_TAG, "Unexpected sync thread exception", e);
      thread = null;
      startSyncThread();
    }
  }
Esempio n. 25
0
  @Override
  public void updatePreferences(final Preference preference, Object value) {
    final Resources r = getResources();

    if (r.getString(R.string.p_showNotes).equals(preference.getKey())) {
      if (value != null && !(Boolean) value)
        preference.setSummary(R.string.EPr_showNotes_desc_disabled);
      else preference.setSummary(R.string.EPr_showNotes_desc_enabled);
      if ((Boolean) value != Preferences.getBoolean(preference.getKey(), false)) {
        taskService.clearDetails(Criterion.all);
        Flags.set(Flags.REFRESH);
      }
    } else if (r.getString(R.string.p_fullTaskTitle).equals(preference.getKey())) {
      if (value != null && (Boolean) value)
        preference.setSummary(R.string.EPr_fullTask_desc_enabled);
      else preference.setSummary(R.string.EPr_fullTask_desc_disabled);
    } else if (r.getString(R.string.p_theme).equals(preference.getKey())) {
      if (AndroidUtilities.getSdkVersion() < 5) {
        preference.setEnabled(false);
        preference.setSummary(R.string.EPr_theme_desc_unsupported);
      } else {
        int index = 0;
        if (value instanceof String && !TextUtils.isEmpty((String) value))
          index =
              AndroidUtilities.indexOf(
                  r.getStringArray(R.array.EPr_theme_settings), (String) value);
        if (index < 0) index = 0;
        preference.setSummary(
            getString(R.string.EPr_theme_desc, r.getStringArray(R.array.EPr_themes)[index]));
      }
    } else if (r.getString(R.string.p_theme_widget).equals(preference.getKey())) {
      if (AndroidUtilities.getSdkVersion() < 5) {
        preference.setEnabled(false);
        preference.setSummary(R.string.EPr_theme_desc_unsupported);
      } else {
        int index = 0;
        if (value instanceof String && !TextUtils.isEmpty((String) value))
          index =
              AndroidUtilities.indexOf(
                  r.getStringArray(R.array.EPr_theme_widget_settings), (String) value);
        if (index < 0) index = 0;
        preference.setSummary(
            getString(R.string.EPr_theme_desc, r.getStringArray(R.array.EPr_themes_widget)[index]));
      }
    }

    // pp preferences
    else if (booleanPreference(
        preference,
        value,
        R.string.p_statistics,
        R.string.EPr_statistics_desc_disabled,
        R.string.EPr_statistics_desc_enabled)) ;
    else if (booleanPreference(
        preference,
        value,
        R.string.p_autoIdea,
        R.string.EPr_ideaAuto_desc_disabled,
        R.string.EPr_ideaAuto_desc_enabled)) ;

    // voice input and output
    if (!addOnService.hasPowerPack()) return;

    if (r.getString(R.string.p_voiceInputEnabled).equals(preference.getKey())) {
      if (value != null && !(Boolean) value)
        preference.setSummary(R.string.EPr_voiceInputEnabled_desc_disabled);
      else preference.setSummary(R.string.EPr_voiceInputEnabled_desc_enabled);
      onVoiceInputStatusChanged(preference, (Boolean) value);
    } else if (r.getString(R.string.p_voiceRemindersEnabled).equals(preference.getKey())) {
      if (value != null && !(Boolean) value)
        preference.setSummary(R.string.EPr_voiceRemindersEnabled_desc_disabled);
      else preference.setSummary(R.string.EPr_voiceRemindersEnabled_desc_enabled);
      onVoiceReminderStatusChanged(preference, (Boolean) value);
    } else if (r.getString(R.string.p_voiceInputCreatesTask).equals(preference.getKey())) {
      if (value != null && !(Boolean) value)
        preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_disabled);
      else preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_enabled);
    }
  }
Esempio n. 26
0
    @SuppressWarnings("nls")
    public RemoteViews buildUpdate(Context context, int widgetId) {
      DependencyInjectionService.getInstance().inject(this);

      RemoteViews views = null;

      views = new RemoteViews(context.getPackageName(), R.layout.widget_initialized);

      int[] textIDs = TEXT_IDS;
      int[] separatorIDs = SEPARATOR_IDS;
      int numberOfTasks = 5;

      for (int i = 0; i < textIDs.length; i++) views.setTextViewText(textIDs[i], "");

      TodorooCursor<Task> cursor = null;
      Filter filter = null;
      try {
        filter = getFilter(widgetId);
        views.setTextViewText(R.id.widget_title, filter.title);

        SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(this);
        int flags = publicPrefs.getInt(SortHelper.PREF_SORT_FLAGS, 0);
        int sort = publicPrefs.getInt(SortHelper.PREF_SORT_SORT, 0);
        String query =
            SortHelper.adjustQueryForFlagsAndSort(filter.sqlQuery, flags, sort)
                    .replaceAll("LIMIT \\d+", "")
                + " LIMIT "
                + numberOfTasks;

        database.openForReading();
        cursor =
            taskService.fetchFiltered(
                query, null, Task.ID, Task.TITLE, Task.DUE_DATE, Task.COMPLETION_DATE);
        Task task = new Task();
        for (int i = 0; i < cursor.getCount() && i < numberOfTasks; i++) {
          cursor.moveToPosition(i);
          task.readFromCursor(cursor);

          String textContent = "";
          int textColor = Color.WHITE;

          textContent = task.getValue(Task.TITLE);

          if (task.isCompleted())
            textColor = context.getResources().getColor(R.color.task_list_done);
          else if (task.hasDueDate() && task.getValue(Task.DUE_DATE) < DateUtilities.now())
            textColor = context.getResources().getColor(R.color.task_list_overdue);

          if (i > 0) views.setViewVisibility(separatorIDs[i - 1], View.VISIBLE);
          views.setTextViewText(textIDs[i], textContent);
          views.setTextColor(textIDs[i], textColor);
        }

        for (int i = cursor.getCount() - 1; i < separatorIDs.length; i++) {
          if (i >= 0) views.setViewVisibility(separatorIDs[i], View.INVISIBLE);
        }
      } catch (Exception e) {
        // can happen if database is not ready
        Log.e("WIDGET-UPDATE", "Error updating widget", e);
      } finally {
        if (cursor != null) cursor.close();
      }

      updateForScreenSize(views);

      Intent listIntent = new Intent(context, TaskListActivity.class);
      String customIntent =
          Preferences.getStringValue(WidgetConfigActivity.PREF_CUSTOM_INTENT + widgetId);
      if (customIntent != null) {
        listIntent.setComponent(ComponentName.unflattenFromString(customIntent));
        String serializedExtras =
            Preferences.getStringValue(WidgetConfigActivity.PREF_CUSTOM_EXTRAS + widgetId);
        Bundle extras = AndroidUtilities.bundleFromSerializedString(serializedExtras);
        listIntent.putExtras(extras);
      }
      listIntent.putExtra(TaskListActivity.TOKEN_SOURCE, Constants.SOURCE_WIDGET);
      listIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
      if (filter != null) {
        listIntent.putExtra(TaskListActivity.TOKEN_FILTER, filter);
        listIntent.setAction("L" + widgetId + filter.sqlQuery);
      }
      PendingIntent pendingIntent =
          PendingIntent.getActivity(
              context, widgetId, listIntent, PendingIntent.FLAG_CANCEL_CURRENT);
      views.setOnClickPendingIntent(R.id.taskbody, pendingIntent);

      Intent editIntent = new Intent(context, TaskEditActivity.class);
      editIntent.setFlags(
          Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
      if (filter != null && filter.valuesForNewTasks != null) {
        String values = AndroidUtilities.contentValuesToSerializedString(filter.valuesForNewTasks);
        editIntent.putExtra(TaskEditActivity.TOKEN_VALUES, values);
        editIntent.setType(values);
      }
      pendingIntent = PendingIntent.getActivity(context, 0, editIntent, 0);
      views.setOnClickPendingIntent(R.id.widget_button, pendingIntent);

      return views;
    }
Esempio n. 27
0
 public void transitionForTaskEdit() {
   AndroidUtilities.callOverridePendingTransition(
       getActivity(), R.anim.slide_left_in, R.anim.slide_left_out);
 }
Esempio n. 28
0
 public static boolean speechRecordingAvailable(Context context) {
   return AndroidUtilities.getSdkVersion() >= 8
       && SpeechRecognizer.isRecognitionAvailable(context);
 }
Esempio n. 29
0
  @SuppressWarnings("nls")
  public static String getHistoryComment(
      final AstridActivity context, History history, User user, String linkColor, String fromView) {
    boolean hasTask = false;
    JSONArray taskAttrs = null;
    if (!TextUtils.isEmpty(history.getValue(History.TASK))) {
      try {
        taskAttrs = new JSONArray(history.getValue(History.TASK));
        hasTask = true;
      } catch (JSONException e) {
        //
      }
    }

    String item;
    String itemPosessive;
    if (FROM_TASK_VIEW.equals(fromView)) {
      item = context.getString(R.string.history_this_task);
    } else if (hasTask && taskAttrs != null) {
      item = taskAttrs.optString(1);
    } else {
      item = context.getString(R.string.history_this_list);
    }
    itemPosessive = item + "'s";

    String oldValue = history.getValue(History.OLD_VALUE);
    String newValue = history.getValue(History.NEW_VALUE);

    String result = "";
    String column = history.getValue(History.COLUMN);
    try {
      if (History.COL_TAG_ADDED.equals(column) || History.COL_TAG_REMOVED.equals(column)) {
        JSONArray tagObj = new JSONArray(newValue);
        String tagName = tagObj.getString(1);
        if (History.COL_TAG_ADDED.equals(column))
          result = context.getString(R.string.history_tag_added, item, tagName);
        else result = context.getString(R.string.history_tag_removed, item, tagName);

      } else if (History.COL_ATTACHMENT_ADDED.equals(column)
          || History.COL_ATTACHMENT_REMOVED.equals(column)) {
        JSONArray attachmentArray = new JSONArray(newValue);
        String attachmentName = attachmentArray.getString(0);
        if (History.COL_ATTACHMENT_ADDED.equals(column))
          result = context.getString(R.string.history_attach_added, attachmentName, item);
        else result = context.getString(R.string.history_attach_removed, attachmentName, item);
      } else if (History.COL_ACKNOWLEDGED.equals(column)) {
        result = context.getString(R.string.history_acknowledged, item);
      } else if (History.COL_SHARED_WITH.equals(column)
          || History.COL_UNSHARED_WITH.equals(column)) {
        JSONArray members = new JSONArray(newValue);
        String userId = history.getValue(History.USER_UUID);
        StringBuilder memberList = new StringBuilder();
        for (int i = 0; i < members.length(); i++) {
          JSONObject m = members.getJSONObject(i);
          memberList.append(userDisplay(context, userId, m));
          if (i != members.length() - 1) memberList.append(", ");
        }

        if (History.COL_SHARED_WITH.equals(column))
          result = context.getString(R.string.history_shared_with, item, memberList);
        else result = context.getString(R.string.history_unshared_with, item, memberList);
      } else if (History.COL_MEMBER_ADDED.equals(column)
          || History.COL_MEMBER_REMOVED.equals(column)) {
        JSONObject userValue = new JSONObject(newValue);
        if (history.getValue(History.USER_UUID).equals(userValue.optString("id"))
            && History.COL_MEMBER_REMOVED.equals(column))
          result = context.getString(R.string.history_left_list, item);
        else {
          String userDisplay = userDisplay(context, history.getValue(History.USER_UUID), userValue);
          if (History.COL_MEMBER_ADDED.equals(column))
            result = context.getString(R.string.history_added_user, userDisplay, item);
          else result = context.getString(R.string.history_removed_user, userDisplay, item);
        }
      } else if (History.COL_COMPLETED_AT.equals(column)) {
        if (!TextUtils.isEmpty(newValue) && !"null".equals(newValue)) {
          result = context.getString(R.string.history_completed, item);
        } else {
          result = context.getString(R.string.history_uncompleted, item);
        }
      } else if (History.COL_DELETED_AT.equals(column)) {
        if (!TextUtils.isEmpty(newValue) && !"null".equals(newValue)) {
          result = context.getString(R.string.history_deleted, item);
        } else {
          result = context.getString(R.string.history_undeleted, item);
        }
      } else if (History.COL_IMPORTANCE.equals(column)) {
        int oldPriority = AndroidUtilities.tryParseInt(oldValue, 0);
        int newPriority = AndroidUtilities.tryParseInt(newValue, 0);

        result =
            context.getString(
                R.string.history_importance_changed,
                itemPosessive,
                priorityString(oldPriority),
                priorityString(newPriority));
      } else if (History.COL_NOTES_LENGTH.equals(column)) {
        int oldLength = AndroidUtilities.tryParseInt(oldValue, 0);
        int newLength = AndroidUtilities.tryParseInt(newValue, 0);

        if (oldLength > 0 && newLength > oldLength)
          result =
              context.getString(
                  R.string.history_added_description_characters,
                  (newLength - oldLength),
                  itemPosessive);
        else if (newLength == 0)
          result = context.getString(R.string.history_removed_description, itemPosessive);
        else if (oldLength > 0 && newLength < oldLength)
          result =
              context.getString(
                  R.string.history_removed_description_characters,
                  (oldLength - newLength),
                  itemPosessive);
        else if (oldLength > 0 && oldLength == newLength)
          result = context.getString(R.string.history_updated_description, itemPosessive);
      } else if (History.COL_PUBLIC.equals(column)) {
        int value = AndroidUtilities.tryParseInt(newValue, 0);
        if (value > 0) result = context.getString(R.string.history_made_public, item);
        else result = context.getString(R.string.history_made_private, item);
      } else if (History.COL_DUE.equals(column)) {
        if (!TextUtils.isEmpty(oldValue)
            && !TextUtils.isEmpty(newValue)
            && !"null".equals(oldValue)
            && !"null".equals(newValue))
          result =
              context.getString(
                  R.string.history_changed_due_date,
                  itemPosessive,
                  dateString(context, oldValue, newValue),
                  dateString(context, newValue, oldValue));
        else if (!TextUtils.isEmpty(newValue) && !"null".equals(newValue))
          result =
              context.getString(
                  R.string.history_set_due_date,
                  itemPosessive,
                  dateString(
                      context, newValue, DateUtilities.timeToIso8601(DateUtilities.now(), true)));
        else result = context.getString(R.string.history_removed_due_date, itemPosessive);
      } else if (History.COL_REPEAT.equals(column)) {
        String repeatString = getRepeatString(context, newValue);
        if (!TextUtils.isEmpty(repeatString))
          result = context.getString(R.string.history_changed_repeat, itemPosessive, repeatString);
        else result = context.getString(R.string.history_removed_repeat, itemPosessive);
      } else if (History.COL_TASK_REPEATED.equals(column)) {
        result =
            context.getString(
                R.string.history_completed_repeating_task,
                item,
                dateString(context, newValue, oldValue));
      } else if (History.COL_TITLE.equals(column)) {
        if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
          result =
              context.getString(R.string.history_title_changed, itemPosessive, oldValue, newValue);
        else result = context.getString(R.string.history_title_set, itemPosessive, newValue);
      } else if (History.COL_NAME.equals(column)) {
        if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
          result = context.getString(R.string.history_name_changed, oldValue, newValue);
        else result = context.getString(R.string.history_name_set, newValue);
      } else if (History.COL_DESCRIPTION.equals(column)) {
        if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
          result = context.getString(R.string.history_description_changed, oldValue, newValue);
        else result = context.getString(R.string.history_description_set, newValue);
      } else if (History.COL_PICTURE_ID.equals(column)
          || History.COL_DEFAULT_LIST_IMAGE_ID.equals(column)) {
        result = context.getString(R.string.history_changed_list_picture);
      } else if (History.COL_IS_SILENT.equals(column)) {
        int value = AndroidUtilities.tryParseInt(newValue, 0);
        if (value > 0) result = context.getString(R.string.history_silenced, item);
        else result = context.getString(R.string.history_unsilenced, item);
      } else if (History.COL_IS_FAVORITE.equals(column)) {
        int value = AndroidUtilities.tryParseInt(newValue, 0);
        if (value > 0) result = context.getString(R.string.history_favorited, item);
        else result = context.getString(R.string.history_unfavorited, item);
      } else if (History.COL_USER_ID.equals(column)) {
        String userId = history.getValue(History.USER_UUID);
        JSONObject userValue = new JSONObject(newValue);
        if (FROM_TAG_VIEW.equals(fromView) && !hasTask) {
          if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
            result =
                context.getString(
                    R.string.history_changed_list_owner, userDisplay(context, userId, userValue));
          else result = context.getString(R.string.history_created_this_list);
        } else if (!TextUtils.isEmpty(oldValue)
            && !"null".equals(oldValue)
            && Task.USER_ID_UNASSIGNED.equals(userValue))
          result = context.getString(R.string.history_unassigned, item);
        else if (Task.USER_ID_UNASSIGNED.equals(oldValue)
            && userValue.optString("id").equals(ActFmPreferenceService.userId()))
          result = context.getString(R.string.history_claimed, item);
        else if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
          result =
              context.getString(
                  R.string.history_assigned_to, item, userDisplay(context, userId, userValue));
        else if (!userValue.optString("id").equals(ActFmPreferenceService.userId())
            && !Task.USER_ID_UNASSIGNED.equals(userValue.optString("id")))
          result =
              context.getString(
                  R.string.history_created_for, item, userDisplay(context, userId, userValue));
        else result = context.getString(R.string.history_created, item);
      } else {
        result = context.getString(R.string.history_default, column, newValue);
      }
    } catch (Exception e) {
      e.printStackTrace();
      result = context.getString(R.string.history_default, column, newValue);
    }

    if (TextUtils.isEmpty(result))
      result = context.getString(R.string.history_default, column, newValue);

    String userDisplay;
    if (history.getValue(History.USER_UUID).equals(Task.USER_ID_SELF)
        || history.getValue(History.USER_UUID).equals(ActFmPreferenceService.userId())) {
      userDisplay = context.getString(R.string.update_string_user_self);
    } else if (user == null) {
      userDisplay = context.getString(R.string.ENA_no_user);
    } else {
      userDisplay = user.getDisplayName(USER_NAME, USER_FIRST_NAME, USER_LAST_NAME);
    }

    return userDisplay + " " + result;
  }
Esempio n. 30
0
 @Override
 public void finish() {
   super.finish();
   AndroidUtilities.callOverridePendingTransition(
       this, R.anim.slide_right_in, R.anim.slide_right_out);
 }