@Override
  protected void doOneByOneCrudRun(int count) throws Exception {
    final List<SimpleEntityNotNull> list = new ArrayList<>();
    for (int i = 0; i < count; i++) {
      list.add(SimpleEntityNotNullHelper.createEntity((long) i));
    }

    startClock();
    for (int i = 0; i < count; i++) {
      realm.beginTransaction();
      realm.copyToRealm(list.get(i));
      realm.commitTransaction();
    }
    stopClock(Benchmark.Type.ONE_BY_ONE_CREATE);

    startClock();
    for (int i = 0; i < count; i++) {
      realm.beginTransaction();
      realm.copyToRealmOrUpdate(list.get(i));
      realm.commitTransaction();
    }
    stopClock(Benchmark.Type.ONE_BY_ONE_UPDATE);

    deleteAll();
  }
Ejemplo n.º 2
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();
  }
Ejemplo n.º 3
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();
  }
  public void sum() {
    Log.i("DataStoreBenchmark", "Realm invoking sum");
    // super.intitalize();         Realm.deleteRealm(realmConfiguration);

    Realm realm;
    List<Long> values;
    long timeStart;
    values = new ArrayList<>();

    realm = Realm.getInstance(realmConfiguration);
    add(realm);
    check(realm);

    for (int i = 0; i < numberOfIterations; i++) {
      timeStart = Debug.threadCpuTimeNanos();
      System.gc();

      long sum = realm.where(Student.class).sumInt("points");
      long timeStop = Debug.threadCpuTimeNanos();
      long duration = timeStop - timeStart;
      values.add(duration);
    }

    realm.beginTransaction();
    realm.clear(Student.class);
    realm.commitTransaction();
    realm.close();

    finalvalues.put(SUM, values);

    System.gc();
  }
Ejemplo n.º 5
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);
              }
            });
  }
  public void loadData() {
    SimpleDateFormat formatIn = new SimpleDateFormat("MMMM d, yyyy");
    SimpleDateFormat formatOut = new SimpleDateFormat("MM/d/yy");
    ObjectMapper objectMapper = new ObjectMapper();
    JsonFactory jsonFactory = new JsonFactory();
    Random random = new Random();
    try {
      JsonParser jsonParserBlog =
          jsonFactory.createParser(getResources().openRawResource(R.raw.blog));
      List<Blog> entries =
          objectMapper.readValue(jsonParserBlog, new TypeReference<List<Blog>>() {});
      JsonParser jsonParserEmoji =
          jsonFactory.createParser(getResources().openRawResource(R.raw.emoji));
      List<String> emojies =
          objectMapper.readValue(jsonParserEmoji, new TypeReference<List<String>>() {});

      int numEmoji = emojies.size();
      for (Blog blog : entries) {
        blog.setEmoji(emojies.get(random.nextInt(numEmoji)));
        try {
          blog.setDate(formatOut.format(formatIn.parse(blog.getDate())));
        } catch (ParseException e) {
          e.printStackTrace();
        }
      }
      Realm realm = Realm.getInstance(this);
      realm.beginTransaction();
      realm.copyToRealm(entries);
      realm.commitTransaction();
      realm.close();

    } catch (Exception e) {
      throw new IllegalStateException("Could not load blog data.");
    }
  }
Ejemplo n.º 7
0
  @Override
  protected void onHandleIntent(Intent intent) {
    Log.e(TAG, "getting notifications. . . ");
    String username = intent.getStringExtra(Constants.User.USERNAME);
    TBSUserInterface service = ServiceManager.getInstance();
    try {
      Call<List<Notification>> call = service.getNotifications(username);
      Response<List<Notification>> response = call.execute();

      if (response.code() == HttpURLConnection.HTTP_OK) {
        List<Notification> notifications = response.body();
        Log.e(TAG, response.body().toString());

        Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        realm.where(Notification.class).findAll().clear();
        realm.copyToRealmOrUpdate(notifications);
        realm.commitTransaction();
        realm.close();

        notifySuccess(ACTION, "Successful");
      } else {
        String error = response.errorBody().string();
        Log.e(TAG, "Error: " + error);
        notifyFailure(ACTION, "Error");
      }

    } catch (IOException e) {
      Log.e(TAG, e.getMessage(), e);
      notifyFailure(ACTION, "Unable to connect to server");
    }
  }
Ejemplo n.º 8
0
  /**
   * getWishList로 전체 찜 목록을 가져왔을때 호출되는 함수. 기존의 Wish들을 삭제하고, 파라메터의 어레이로 다시 채운다.
   *
   * @param arr
   */
  public void setAllWishList(JSONArray arr) {
    // Realm Database **********************************************************************
    // Obtain a Realm instance
    Realm realm = Realm.getInstance(mContext);

    // remove all
    realm.beginTransaction();
    realm.allObjects(WishObject.class).clear();
    for (int i = 0; i < arr.length(); i++) {
      try {
        JSONObject jo = arr.getJSONObject(i);
        JSONObject asset = jo.getJSONObject("asset");
        String assetId = asset.getString("assetId");
        RealmResults<WishObject> results =
            mRealm.where(WishObject.class).equalTo("sAssetId", assetId).findAll();
        if (results.size() > 0) {
          // skip
        } else {
          // 객체를 생성하거나 데이터를 수정하는 작업을 수행한다.
          WishObject wish = realm.createObject(WishObject.class); // Create a new object
          wish.setsAssetId(assetId);
          wish.setsPhoneNumber(jo.getString("phoneNumber"));
          wish.setsUserId(jo.getString("userId"));
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
    // 트랜잭션 종료
    realm.commitTransaction();
    // Realm Database **********************************************************************
  }
Ejemplo n.º 9
0
 /** 카테고리(메인) */
 public void addMainCategory(
     MainCategoryObject obj1, MainCategoryObject obj2, MainCategoryObject obj3) {
   // Realm Database **********************************************************************
   // Obtain a Realm instance
   Realm realm = Realm.getInstance(mContext);
   realm.beginTransaction();
   realm.allObjects(MainCategoryObject.class).clear();
   MainCategoryObject newObj1 =
       realm.createObject(MainCategoryObject.class); // Create a new object
   newObj1.setsSortNo(obj1.getsSortNo());
   newObj1.setsCategoryId(obj1.getsCategoryId());
   newObj1.setsCategoryType(obj1.getsCategoryType());
   newObj1.setsCategoryTitle(obj1.getsCategoryTitle());
   MainCategoryObject newObj2 =
       realm.createObject(MainCategoryObject.class); // Create a new object
   newObj2.setsSortNo(obj2.getsSortNo());
   newObj2.setsCategoryId(obj2.getsCategoryId());
   newObj2.setsCategoryType(obj2.getsCategoryType());
   newObj2.setsCategoryTitle(obj2.getsCategoryTitle());
   MainCategoryObject newObj3 =
       realm.createObject(MainCategoryObject.class); // Create a new object
   newObj3.setsSortNo(obj3.getsSortNo());
   newObj3.setsCategoryId(obj3.getsCategoryId());
   newObj3.setsCategoryType(obj3.getsCategoryType());
   newObj3.setsCategoryTitle(obj3.getsCategoryTitle());
   realm.commitTransaction();
   // Realm Database **********************************************************************
 }
Ejemplo n.º 10
0
  // 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();
    }
  }
Ejemplo n.º 11
0
  @Override
  protected void onHandleIntent(Intent intent) {
    Log.e(TAG, "gettting donation requests");

    TbsService service = ServiceManager.getInstance();
    try {
      Call<List<DonateApproval>> call = service.getDonationRequests();
      Response<List<DonateApproval>> response = call.execute();

      if (response.code() == HttpURLConnection.HTTP_OK) {
        List<DonateApproval> donateApprovals = response.body();

        Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        realm.where(DonateApproval.class).findAll().clear();
        realm.copyToRealmOrUpdate(donateApprovals);
        realm.commitTransaction();
        realm.close();

        notifySuccess(ACTION, "Successful");
      } else {
        String error = response.errorBody().string();
        Log.e(TAG, "Error: " + error);
        notifyFailure(ACTION, "Failed");
      }

    } catch (Exception e) {
      Log.e(TAG, e.getMessage(), e);
      notifyFailure(ACTION, "Request error");
    }
  }
Ejemplo n.º 12
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();
  }
Ejemplo n.º 13
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();
    }
  }
Ejemplo n.º 14
0
  /**
   * *********************************************************************************************
   * VOD시청
   */
  public void addWatchVod(Date watchDate, String assetId, String title) {
    // Realm Database **********************************************************************
    // Obtain a Realm instance
    Realm realm = Realm.getInstance(mContext);
    RealmResults<WatchVodObject> results = realm.where(WatchVodObject.class).findAll();
    long iSeq = 0;
    if (results == null) {
      //
    } else {
      if (results.size() == 0) {
        iSeq = 0;
      } else {
        iSeq = realm.where(WatchVodObject.class).maximumInt("iSeq") + 1;
      }
    }

    WatchVodObject obj = new WatchVodObject();
    obj.setiSeq((int) iSeq);
    obj.setdDate(watchDate);
    obj.setsAssetId(assetId);
    obj.setsTitle(title);
    realm.beginTransaction();
    WatchVodObject obj2 = realm.copyToRealm(obj);
    realm.commitTransaction();
    // Realm Database **********************************************************************
  }
Ejemplo n.º 15
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);
    }
  }
 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();
 }
  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();
  }
Ejemplo n.º 18
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();
 }
  @Override
  protected void doBatchCrudRun(int count) throws Exception {
    final List<SimpleEntityNotNull> list = new ArrayList<>();
    for (int i = 0; i < count; i++) {
      list.add(SimpleEntityNotNullHelper.createEntity((long) i));
    }

    startClock();
    realm.beginTransaction();
    realm.insert(list);
    realm.commitTransaction();
    stopClock(Benchmark.Type.BATCH_CREATE);

    startClock();
    realm.beginTransaction();
    realm.insertOrUpdate(list);
    realm.commitTransaction();
    stopClock(Benchmark.Type.BATCH_UPDATE);

    startClock();
    RealmResults<SimpleEntityNotNull> reloaded = realm.where(SimpleEntityNotNull.class).findAll();
    stopClock(Benchmark.Type.BATCH_READ);

    // as Realm is not actually loading data, just referencing it,
    // at least make sure we access every property to force it being loaded
    startClock();
    for (int i = 0; i < reloaded.size(); i++) {
      SimpleEntityNotNull entity = reloaded.get(i);
      entity.getId();
      entity.getSimpleBoolean();
      entity.getSimpleByte();
      entity.getSimpleShort();
      entity.getSimpleInt();
      entity.getSimpleLong();
      entity.getSimpleFloat();
      entity.getSimpleDouble();
      entity.getSimpleString();
      entity.getSimpleByteArray();
    }
    stopClock(Benchmark.Type.BATCH_ACCESS);

    startClock();
    deleteAll();
    stopClock(Benchmark.Type.BATCH_DELETE);
  }
Ejemplo n.º 20
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;
 }
Ejemplo n.º 21
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();
  }
Ejemplo n.º 22
0
  public void markComplete(int position) {

    if (position < mResults.size()) {

      mRealm.beginTransaction();
      mResults.get(position).setCompleted(true);
      mRealm.commitTransaction();
      notifyItemChanged(position);
    }
  }
Ejemplo n.º 23
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();
     }
 }
  @Override
  public void call(final Subscriber<? super T> subscriber) {
    final Realm realm = Realm.getInstance(context);
    thread = Thread.currentThread();
    subscriber.add(
        Subscriptions.create(
            new Action0() {
              @Override
              public void call() {
                if (thread != null && !thread.isInterrupted()) {
                  thread.interrupt();
                }
              }
            }));

    boolean interrupted = false;
    boolean withError = false;

    T object = null;
    try {
      realm.beginTransaction();
      object = get(realm);
      interrupted = thread.isInterrupted();
      if (object != null && !interrupted) {
        realm.commitTransaction();
      } else {
        realm.cancelTransaction();
      }
    } catch (RuntimeException e) {
      realm.cancelTransaction();
      subscriber.onError(new RealmException("Error during transaction.", e));
      withError = true;
    } catch (Error e) {
      realm.cancelTransaction();
      subscriber.onError(e);
      withError = true;
    }
    if (!interrupted && !withError) {
      subscriber.onNext(object);
    }

    try {
      realm.close();
    } catch (RealmException ex) {
      subscriber.onError(ex);
      withError = true;
    }
    thread = null;
    if (!withError) {
      subscriber.onCompleted();
    }
    if (interrupted) {
      Thread.currentThread().interrupt();
    }
  }
Ejemplo n.º 25
0
  /**
   * @param programId "S321387639"
   * @param seriesId ""
   * @param programTitle "국악무대"
   * @param programBroadcastingStartTime 2015-11-10 16:02:00"
   *     <p>mPref.addWatchTvAlarm("S321387639", "", "국악무대1", "2015-11-10 18:50:00");
   *     mPref.addWatchTvAlarm("S321387640", "", "국악무대2", "2015-11-10 18:51:00");
   *     mPref.addWatchTvAlarm("S321387641", "", "국악무대3", "2015-11-10 18:52:00");
   *     mPref.addWatchTvAlarm("S321387642", "", "국악무대4", "2015-11-10 18:53:00");
   *     mPref.addWatchTvAlarm("S321387643", "", "국악무대5", "2015-11-10 18:54:00");
   */
  public void addWatchTvReserveAlarm(
      String programId, String seriesId, String programTitle, String programBroadcastingStartTime) {

    // Realm Database **********************************************************************
    // Obtain a Realm instance
    Realm realm = Realm.getInstance(mContext);

    // remove all
    realm.beginTransaction();
    WatchTvObject obj = realm.createObject(WatchTvObject.class); // Create a new object
    long iSeq = realm.where(WatchTvObject.class).maximumInt("iSeq") + 1;
    obj.setiSeq((int) iSeq);
    obj.setsScheduleSeq("");
    obj.setsBroadcastingDate("");
    obj.setsProgramId(programId);
    obj.setsSeriesId(seriesId);
    obj.setsProgramTitle(programTitle);
    obj.setsProgramContent("");
    obj.setsProgramBroadcastingStartTime(programBroadcastingStartTime);
    obj.setsProgramBroadcastingEndTime("");
    obj.setsProgramHD("");
    obj.setsProgramGrade("");
    obj.setsProgramPVR("");
    // 트랜잭션 종료
    realm.commitTransaction();
    // Realm Database **********************************************************************

    Date startDate = null;
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
      startDate = formatter.parse(programBroadcastingStartTime);
    } catch (ParseException e) {
      e.printStackTrace();
    }
    calendar.setTime(startDate);

    Intent intent = new Intent(mContext, WatchTvAlarmBroadcastReceiver.class);
    intent.putExtra("programId", programId);
    intent.putExtra("seriesId", seriesId);
    intent.putExtra("programTitle", programTitle);
    intent.putExtra("programBroadcastingStartTime", programBroadcastingStartTime);
    intent.putExtra("iSeq", String.valueOf(iSeq));

    //        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, (int)iSeq, intent,
    // PendingIntent.FLAG_NO_CREATE);
    PendingIntent pendingIntent =
        PendingIntent.getBroadcast(mContext, (int) iSeq, intent, PendingIntent.FLAG_ONE_SHOT);
    //        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, (int)iSeq, intent,
    // PendingIntent.FLAG_UPDATE_CURRENT );

    AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    //        alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
  }
  private void indexedStringEntityQueriesRun(int count) {
    // create entities
    List<IndexedStringEntity> entities = new ArrayList<>(count);
    String[] fixedRandomStrings = StringGenerator.createFixedRandomStrings(count);
    for (int i = 0; i < count; i++) {
      IndexedStringEntity entity = new IndexedStringEntity();
      entity.setId((long) i);
      entity.setIndexedString(fixedRandomStrings[i]);
      entities.add(entity);
    }
    log("Built entities.");

    // insert entities
    realm.beginTransaction();
    realm.copyToRealm(entities);
    realm.commitTransaction();
    log("Inserted entities.");

    // query for entities by indexed string at random
    int[] randomIndices = StringGenerator.getFixedRandomIndices(getQueryCount(), count - 1);

    startClock();
    for (int i = 0; i < getQueryCount(); i++) {
      int nextIndex = randomIndices[i];
      RealmQuery<IndexedStringEntity> query = realm.where(IndexedStringEntity.class);
      query.equalTo("indexedString", fixedRandomStrings[nextIndex]);
      RealmResults<IndexedStringEntity> result = query.findAll();
      for (int j = 0, resultSize = result.size(); j < resultSize; j++) {
        // actually get each entity so its object is reconstructed, same with properties
        IndexedStringEntity entity = result.get(j);
        entity.getId();
        entity.getIndexedString();
      }
    }
    stopClock(Benchmark.Type.QUERY_INDEXED);

    // delete all entities
    realm.beginTransaction();
    realm.delete(IndexedStringEntity.class);
    realm.commitTransaction();
    log("Deleted all entities.");
  }
 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();
 }
Ejemplo n.º 28
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();
 }
  private void cacheData(LocalCacheDataPOJO newCacheData) {
    realm.beginTransaction();

    LocalCacheData realmCacheData = getRealmCacheData();
    if (realmCacheData == null) {
      realmCacheData = realm.createObject(LocalCacheData.class);
    }
    populateCacheData(realmCacheData, newCacheData);

    realm.commitTransaction();
  }
Ejemplo n.º 30
0
 public void removeAllWatchVod() {
   // Realm Database **********************************************************************
   // Obtain a Realm instance
   Realm realm = Realm.getInstance(mContext);
   realm.beginTransaction();
   RealmResults<WatchVodObject> results = mRealm.where(WatchVodObject.class).findAll();
   if (results.size() > 0) {
     results.clear();
   }
   realm.commitTransaction();
   // Realm Database **********************************************************************
 }