Пример #1
0
  private void createTrackStats(String local_id, int type) {
    TrackStats stats = new TrackStats(local_id, type, android_id);

    realm.beginTransaction();
    realm.copyToRealm(stats);
    realm.commitTransaction();
  }
  // 2016-03-29 시청예약시 데이타베이스 처리를 programId 로 하는데 서버에서 programId를 중복으로 보내고 있다
  // 그래서 시청시간을 추가함.
  public void removeWatchTvReserveAlarmWithProgramIdAndStartTime(
      String programId, String startTime) {
    int iSeq = 0;
    Realm realm = Realm.getInstance(mContext);
    realm.beginTransaction();
    RealmResults<WatchTvObject> results =
        mRealm
            .where(WatchTvObject.class)
            .equalTo("sProgramId", programId)
            .equalTo("sProgramBroadcastingStartTime", startTime)
            .findAll();
    if (results.size() > 0) {
      WatchTvObject obj = results.get(0);
      iSeq = obj.getiSeq();
      obj.removeFromRealm();
    } else {
      //
    }
    realm.commitTransaction();

    AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(mContext, WatchTvAlarmBroadcastReceiver.class);
    PendingIntent pendingIntent =
        PendingIntent.getBroadcast(mContext, iSeq, intent, PendingIntent.FLAG_NO_CREATE);
    if (pendingIntent != null) {
      alarmManager.cancel(pendingIntent);
      pendingIntent.cancel();
    }
  }
Пример #3
0
 /** Remove todos os objetos RealmVideo salvos no banco. */
 public static void cleanVideos() {
   Realm realm = Realm.getDefaultInstance();
   RealmResults<RealmVideo> results = realm.where(RealmVideo.class).findAll();
   realm.beginTransaction();
   results.clear();
   realm.commitTransaction();
 }
  public final void initialize(@NonNull final Realm realm) {
    Contracts.requireNonNull(realm, "realm == null");

    synchronized (_lock$maximumKeys) {
      if (_initialized) {
        throw new IllegalStateException(RealmIdGenerator.class + " is already initialized.");
      }

      final val maximumKeys = getMaximumKeys();

      final val configuration = realm.getConfiguration();
      final val realmSchema = realm.getSchema();
      for (final val modelClass : configuration.getRealmObjectClasses()) {
        final val objectSchema = realmSchema.get(modelClass.getSimpleName());
        if (objectSchema.hasPrimaryKey()) {
          final val primaryKeyField = objectSchema.getPrimaryKey();
          final val primaryKey = realm.where(modelClass).max(primaryKeyField);

          final long primaryKeyValue;
          if (primaryKey != null) {
            primaryKeyValue = primaryKey.longValue();
          } else {
            primaryKeyValue = 0L;
          }

          maximumKeys.put(modelClass, new AtomicLong(primaryKeyValue));
        }
      }

      _initialized = true;
    }
  }
  public void createOrUpdateQuests(
      int id,
      int type,
      String text,
      String answer,
      String other,
      String title,
      String icon,
      String color,
      int status) {
    Realm realm = Realm.getInstance(context);
    realm.beginTransaction();

    QuestModel quest = getQuest(id);

    if (quest == null) {
      quest = realm.createObject(QuestModel.class);
    }

    quest.setId(id);
    quest.setType(type);
    quest.setText(text);
    quest.setAnswer(answer);
    quest.setOther(other);
    quest.setTitle(title);
    quest.setIcon(icon);
    quest.setColor(color);
    /*quest.setStatus(status);*/

    realm.commitTransaction();
  }
 public void UpdateStatus(int id, int status) {
   Realm realm = Realm.getInstance(context);
   QuestModel toEdit = realm.where(QuestModel.class).equalTo("id", id).findFirst();
   realm.beginTransaction();
   toEdit.setStatus(status);
   realm.commitTransaction();
 }
Пример #7
0
  @Override
  public void tearDown() throws Exception {
    super.tearDown();

    realm.close();
    Realm.deleteRealmFile(getContext());
  }
Пример #8
0
 public static void clearAllDatabaseCache() {
   // holder.timeOutMap.clear();
   Realm realm = Realm.getInstance(sContext);
   realm.clear(CacheInfo.class);
   realm.close();
   Log.d("aop-cache", "database cache has been cleared ");
 }
Пример #9
0
  /**
   * Removes the {@code tags} from the {@code books}.
   *
   * @param realm Instance of Realm to use.
   * @param books List of {@link RBook}s to remove tags from.
   * @param tags List {@link RTag}s.
   */
  public static void removeTagsFromBooks(Realm realm, List<RBook> books, List<RTag> tags) {
    if (books == null || tags == null) throw new IllegalArgumentException("No nulls allowed.");
    if (books.isEmpty() || tags.isEmpty()) return;

    // Get names of new/updated book tags.
    String newBookTagName = Minerva.prefs().getNewBookTag(null);
    String updatedBookTagName = Minerva.prefs().getUpdatedBookTag(null);

    realm.beginTransaction();
    // Loop through books and remove tags from them.
    for (int i = books.size() - 1; i >= 0; i--) {
      RBook book = books.get(i);
      for (RTag tag : tags) {
        // If the book has the tag, remove it,
        if (book.tags.remove(tag)) {
          // and remove the book from the tag.
          tag.taggedBooks.remove(book);
        }
        // Make sure that we new/updated state if we had those tags removed.
        if (newBookTagName != null && newBookTagName.equals(tag.name)) book.isNew = false;
        if (updatedBookTagName != null && updatedBookTagName.equals(tag.name))
          book.isUpdated = false;
      }
    }
    realm.commitTransaction();
  }
Пример #10
0
  /**
   * Adds the {@code tags} to the {@code books}.
   *
   * @param realm Instance of Realm to use.
   * @param books List of {@link RBook}s to add tags to.
   * @param tags List {@link RTag}s.
   */
  public static void addTagsToBooks(Realm realm, List<RBook> books, List<RTag> tags) {
    if (books == null || tags == null) throw new IllegalArgumentException("No nulls allowed.");
    if (books.isEmpty() || tags.isEmpty()) return;

    // Get names of new/updated book tags.
    String newBookTagName = Minerva.prefs().getNewBookTag(null);
    String updatedBookTagName = Minerva.prefs().getUpdatedBookTag(null);

    // Sometimes this method is called when we're already in a transaction. We can't nest them.
    boolean isInXactAlready = realm.isInTransaction();
    if (!isInXactAlready) realm.beginTransaction();

    // Loop through books and add tags to them.
    for (int i = books.size() - 1; i >= 0; i--) {
      RBook book = books.get(i);
      for (RTag tag : tags) {
        // If the book doesn't already have the tag,
        if (!book.tags.contains(tag)) {
          // add the tag to the book,
          book.tags.add(tag);
          // and add the book to the tag.
          tag.taggedBooks.add(book);
        }
        // Make sure that we set new/updated state to true if those tags were added (and it wasn't
        // already).
        if (newBookTagName != null && newBookTagName.equals(tag.name) && !book.isNew)
          book.isNew = true;
        if (updatedBookTagName != null && updatedBookTagName.equals(tag.name) && !book.isUpdated)
          book.isUpdated = true;
      }
    }
    // Again, if there's an outer transaction already ongoing, don't finish it here.
    if (!isInXactAlready) realm.commitTransaction();
  }
 public UiTag getTag(int tagId) {
   Realm realm = realmProvider.provideRealm();
   Tag tag = realm.where(Tag.class).equalTo("id", tagId).findFirst();
   UiTag uiTag = new UiTag(tag);
   realm.close();
   return uiTag;
 }
Пример #12
0
  private void savePhotos() {
    try {
      saveMemo(1);

      realm.beginTransaction();
      Photo photo = new Photo();
      photo.setId(getPhotoId());
      photo.setSource("memo");
      photo.setCreateTime(new Date());
      photo.setCreateUser(ConstUtils.USER_NAME);
      photo.setMyPosition(ConstUtils.MY_POSITION);
      photo.setRelationId(addMemo.getId());
      Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
      Log.d("AddMemoActivity", "width: " + bitmap.getWidth());
      Log.d("AddMemoActivity", "height: " + bitmap.getHeight());
      if (bitmap.getWidth() < bitmap.getHeight()) {
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, 660, 1173);
      } else {
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, 1173, 660);
      }

      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      bitmap.compress(Bitmap.CompressFormat.JPEG, 95, bos); // 参数100表示不压缩
      byte[] photoBytes = bos.toByteArray();
      photo.setPhoto(photoBytes);
      realm.copyToRealm(photo);
      realm.commitTransaction();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
Пример #13
0
  @Subscribe
  public void onMovieSearchSuccess(TitleSearchSuccessEvent event) {
    MovieFull movieFull = event.getMovieFull();
    if (!movieFull.isResponse()) {
      // failed set error on input layout
      movieSearchInputLayout.setError(movieFull.getErrorMessage());
    } else {
      // actual success
      realm.beginTransaction();
      realm.copyToRealmOrUpdate(
          new PreviousSearch(
              movieFull.getImdbId(),
              movieFull.getTitle(),
              movieFull.getPoster(),
              new Date(),
              movieFull.getYear()));
      realm.commitTransaction();

      // doing it this way to maintain descending order easily
      getListFromRealm();

      recentSearchesRecycler.getAdapter().notifyDataSetChanged();

      // clear text
      movieSearch.setText("");

      // 2 move to detail screen
      Intent i = new Intent(MainActivity.this, MovieDetailActivity.class);
      i.putExtra(MovieDetailActivity.ARG_MOVIE, event.getMovieFull());
      startActivity(i);
    }
  }
Пример #14
0
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    ImageLoaderConfiguration conf = new ImageLoaderConfiguration.Builder(getActivity()).build();
    ImageLoader imageLoader = ImageLoader.getInstance();
    imageLoader.init(conf);

    adapter = new FriendsArrayAdapter(getActivity(), R.layout.row_friends, imageLoader, this);
    setListAdapter(adapter);

    realm = Realm.getInstance(getActivity());

    RealmResults<Friend> results = realm.allObjects(Friend.class); // TODO: Run async

    if (results.size() > 0) {
      if (!compact) {
        getListView().setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);
      }
      adapter.update(results);
    }

    refreshFriends(); // TODO: Timeout on the refresh rate?
  }
Пример #15
0
  /**
   * Called when one of the cards is swiped away. Removes the associated book from the recents list.
   *
   * @param uniqueId The unique ID of the item so that the correct {@link RBook} can be retrieved.
   */
  @Override
  public void handleSwiped(long uniqueId) {
    // Remove from recents.
    realm.executeTransactionAsync(
        bgRealm ->
            bgRealm.where(RBook.class).equalTo("uniqueId", uniqueId).findFirst().isInRecents =
                false);

    // Show snackbar with "Undo" button.
    Snackbar undoSnackbar = Snackbar.make(coordinator, R.string.book_removed, Snackbar.LENGTH_LONG);
    undoSnackbar.setAction(
        R.string.undo,
        view -> {
          // Put back in recents if undo button is clicked.
          try (Realm realm = Realm.getDefaultInstance()) {
            realm.executeTransactionAsync(
                bgRealm ->
                    bgRealm
                            .where(RBook.class)
                            .equalTo("uniqueId", uniqueId)
                            .findFirst()
                            .isInRecents =
                        true);
          }
        });
    undoSnackbar.show();
  }
Пример #16
0
  public void loadRealmData() {
    Log.d("", "path: " + realm.getPath());

    RealmQuery<User> query = realm.where(User.class);
    RealmResults<User> users = query.findAll();
    generateCsvFile(users);
  }
Пример #17
0
 @Override
 public void onStart(Intent intent, int startId) {
   super.onStart(intent, startId);
   // get today's day of month to query overhead of this same day
   Calendar cal = Calendar.getInstance();
   cal.setTime(new Date());
   int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
   // query realm for overhead to be created on this day
   RealmResults<OverheadModel> overheadsList =
       realm.where(OverheadModel.class).equalTo("dayOfMonth", dayOfMonth).findAll();
   // Get iterator
   Iterator<OverheadModel> iterator = overheadsList.iterator();
   // Create new transaction for each result
   while (iterator.hasNext()) {
     OverheadModel overhead = iterator.next();
     TransactionModel transaction = new TransactionModel(-1);
     transaction.setTransactionType(CreateTransactionActivity.TRANSACTION_TYPE_EXPENSE);
     transaction.setPrice(overhead.getPrice());
     transaction.setCategory(realm.copyFromRealm(overhead.getCategory()));
     transaction.setFromAccount(realm.copyFromRealm(overhead.getFromAccount()));
     transaction.setDate(cal.getTime());
     transaction.setComment(overhead.getComment());
     transaction.setPending(false);
     transaction.setDueToOrBy(0);
     transaction.setDueName(null);
     transactionRepository.saveTransaction(transaction);
   }
   // Set alarm for next month
   this.setUpNewAlarm();
   // Kill service
   stopSelf();
 }
Пример #18
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sleep);
    Realm realm = Realm.getDefaultInstance();

    Toolbar tb = (Toolbar) findViewById(R.id.toolbar);
    tb.setTitle("Sleep Summaries");
    setSupportActionBar(tb);

    if (getSupportActionBar() != null) {
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
      getSupportActionBar().setDisplayShowHomeEnabled(true);
      final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
      upArrow.setColorFilter(Color.parseColor("#FFFFFF"), PorterDuff.Mode.SRC_ATOP);
      getSupportActionBar().setHomeAsUpIndicator(upArrow);
      tb.setTitleTextColor(Color.WHITE);
    }

    tb.setNavigationOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            onBackPressed();
          }
        });

    // Get all sleep data recorded and send this to adapter to populate the list

    RealmResults<Sleep> sleeps = realm.where(Sleep.class).findAll();
    sleeps.sort("startTime", Sort.DESCENDING);
    SleepAdapter sleepAdapter = new SleepAdapter(this, R.id.listView, sleeps, true);
    ListView listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(sleepAdapter);
  }
Пример #19
0
  public void getFlowDefinition(final DBFlow flow, final Callback<Definitions> callback) {

    final Realm realm = Realm.getDefaultInstance();
    realm.beginTransaction();
    flow.setFetching(true);
    realm.commitTransaction();

    m_api
        .getFlowDefinition(getToken(), flow.getUuid())
        .enqueue(
            new Callback<Definitions>() {
              @Override
              public void onResponse(
                  final Call<Definitions> call, final Response<Definitions> response) {
                checkResponse(response);

                realm.beginTransaction();
                flow.setFetching(false);
                realm.commitTransaction();
                realm.close();
                callback.onResponse(call, response);
              }

              @Override
              public void onFailure(Call<Definitions> call, Throwable t) {
                realm.beginTransaction();
                flow.setFetching(false);
                realm.commitTransaction();
                realm.close();
                callback.onFailure(call, t);
              }
            });
  }
Пример #20
0
 /** Close realm for current thread. */
 public static void close() throws IllegalStateException {
   Realm realm = realmCache.get();
   if (realm == null) {
     throw new IllegalStateException("realm already closed");
   }
   realm.close();
   realmCache.set(null);
 }
 /** when view is created * */
 @Override
 public void onViewCreated(View view, Bundle savedInstanceState) {
   super.onViewCreated(view, savedInstanceState);
   /** set realm instance * */
   realm = Realm.getInstance(getActivityFromBase());
   /** add change listener to realm * */
   realm.addChangeListener(this);
 }
Пример #22
0
 public static void removeDataBaseCache(String classMethodString) {
   Realm realm = Realm.getInstance(sContext);
   CacheInfo info = realm.where(CacheInfo.class).equalTo("key", classMethodString).findFirst();
   if (info != null) {
     info.removeFromRealm();
   }
   realm.close();
 }
Пример #23
0
 /**
  * Create a new {@link RBookList} as a smart list.
  *
  * @param realm Instance of Realm to use.
  * @param listName Name to use for new smart list. Assumed to not already be in use.
  * @param realmUserQuery RealmUserQuery to use to get a RealmUserQuery string to store in the
  *     list. Can be null.
  * @return The newly created and persisted smart list.
  */
 public static RBookList createNewSmartList(
     Realm realm, String listName, RealmUserQuery realmUserQuery) {
   if (listName == null || listName.isEmpty())
     throw new IllegalArgumentException("listName must be non-null and non-empty.");
   realm.beginTransaction();
   RBookList newSmartList = realm.copyToRealm(new RBookList(listName, realmUserQuery));
   realm.commitTransaction();
   return newSmartList;
 }
Пример #24
0
  private static Integer getPhotoId() {
    Realm realm = RealmUtils.getRealm();
    RealmResults<Photo> list = realm.where(Photo.class).findAll().sort("id", Sort.ASCENDING);
    realm.close();

    if (list.size() == 0) {
      return 1;
    }
    return list.last().getId() + 1;
  }
Пример #25
0
  public static void removeFavorite(Context context, MashableNewsItem newsItem) {
    Realm realm = Realm.getInstance(context);
    realm.beginTransaction();

    RealmResults<Favorites> result =
        realm.where(Favorites.class).equalTo("link", newsItem.link).findAll();

    result.clear();
    realm.commitTransaction();
  }
 public LocalDailyCacheManagerImpl(Context context) {
   RealmConfiguration config =
       new RealmConfiguration.Builder(context)
           .name("org.theotech.ceaselessandroid")
           .schemaVersion(0)
           .deleteRealmIfMigrationNeeded()
           .build();
   Realm.setDefaultConfiguration(config);
   this.realm = Realm.getDefaultInstance();
 }
Пример #27
0
 public void saveToDatabase() {
   if (mEntityList.size() > 0)
     for (int i = mEntityList.size() - 1; i >= 0; i--) {
       mRealm.beginTransaction();
       RealmZcool realmZcool = new RealmZcool();
       realmZcool.setFromEntity(mEntityList.get(i));
       mRealm.copyToRealmOrUpdate(realmZcool);
       mRealm.commitTransaction();
     }
 }
Пример #28
0
  public void markComplete(int position) {

    if (position < mResults.size()) {

      mRealm.beginTransaction();
      mResults.get(position).setCompleted(true);
      mRealm.commitTransaction();
      notifyItemChanged(position);
    }
  }
 private void add(Realm realm) {
   realm.beginTransaction();
   for (int i = 0; i < numberOfObjects; i++) {
     Student student = realm.createObject(Student.class);
     student.setName(dataGenerator.getStudentName(i));
     student.setPoints(dataGenerator.getStudentPoints(i));
     student.setCsci(dataGenerator.getCsciBool(i));
     student.setStudentid(i);
   }
   realm.commitTransaction();
 }
Пример #30
0
 public void removeWWishAsset(String assetId) {
   Realm realm = Realm.getInstance(mContext);
   realm.beginTransaction();
   RealmResults<WishObject> results =
       mRealm.where(WishObject.class).equalTo("sAssetId", assetId).findAll();
   if (results.size() > 0) {
     WishObject obj = results.get(0);
     obj.removeFromRealm();
   }
   realm.commitTransaction();
 }