/**
   * *********************************************************************************************
   * 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 **********************************************************************
  }
Example #2
0
  /**
   * Replaces an {@link RTag} whose name is {@code oldTagName} with an {@link RTag} whose name is
   * {@code newTagName} on any {@link RBook}s for which the given {@code markType} is set to {@code
   * true}.
   *
   * <p>Any books already tagged with {@code newTagName} but whose value for the given {@code
   * markType} isn't set to {@code true} will be changed so that it is set to {@code true} in order
   * to stay in sync.
   *
   * @param realm Instance of Realm to use.
   * @param markType The mark whose associated tag is being replaced.
   * @param oldTagName Name of the tag to replace.
   * @param newTagName Name of the replacement tag.
   */
  public static void replaceMarkTagOnBooks(
      Realm realm, MarkType markType, String oldTagName, String newTagName) {
    // At least one of the tag names can't be null.
    if (oldTagName == null && newTagName == null)
      throw new IllegalArgumentException(
          "At least one of oldTagName, newTagName must not be null.");

    // Get a list of books whose given mark type is set to true.
    RealmResults<RBook> books =
        realm.where(RBook.class).equalTo(markType.getFieldName(), true).findAll();

    // Get tags.
    RTag oldTag =
        oldTagName != null ? realm.where(RTag.class).equalTo("name", oldTagName).findFirst() : null;
    RTag newTag =
        newTagName != null ? realm.where(RTag.class).equalTo("name", newTagName).findFirst() : null;

    realm.beginTransaction();
    // Loop through the books whose given mark type is set to true.
    for (RBook book : books) {
      // First, remove the old tag (if there is one).
      if (oldTag != null) {
        book.tags.remove(oldTag);
        oldTag.taggedBooks.remove(book);
      }

      // Then, add the new tag (if there is one, and if it isn't already).
      if (newTag != null && !book.tags.contains(newTag)) {
        book.tags.add(newTag);
        newTag.taggedBooks.add(book);
      }
    }

    // If we have a new tag, update the given mark's value on books already tagged with the new tag
    // but not
    // marked accordingly so that we stay in sync.
    if (newTag != null) {
      // Get a list of such books.
      books = newTag.taggedBooks.where().equalTo(markType.getFieldName(), false).findAll();

      // Loop backwards over list and set given mark's value to true.
      for (int i = books.size() - 1; i >= 0; i--) {
        if (markType == MarkType.NEW) books.get(i).isNew = true;
        else if (markType == MarkType.UPDATED) books.get(i).isUpdated = true;
      }
    }

    realm.commitTransaction();
  }
  @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");
    }
  }
 @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();
 }
  /**
   * 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 **********************************************************************
  }
Example #6
0
  public void loadRealmData() {
    Log.d("", "path: " + realm.getPath());

    RealmQuery<User> query = realm.where(User.class);
    RealmResults<User> users = query.findAll();
    generateCsvFile(users);
  }
Example #7
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 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 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 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();
  }
  // 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();
    }
  }
  @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");
    }
  }
Example #13
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);
  }
 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;
 }
 private void setupEvolutions() {
   evolutions.clear();
   for (int i = 0; i < monster.getEvolutions().size(); i++) {
     evolutions.add(
         realm
             .where(BaseMonster.class)
             .equalTo("monsterId", monster.getEvolutions().get(i).getValue())
             .findFirst());
   }
   evolutions.add(0, realm.where(BaseMonster.class).equalTo("monsterId", 0).findFirst());
   if (evolutions.size() == 1) {
     choiceRadioGroup.getChildAt(choiceRadioGroup.getChildCount() - 2).setEnabled(false);
   } else {
     choiceRadioGroup.getChildAt(choiceRadioGroup.getChildCount() - 2).setEnabled(true);
     evolutionSpinner.setEnabled(false);
   }
 }
 @Override
 public int getItemCount() {
   if (mBeersList == null) {
     return 0;
   } else {
     return realm.where(Beer.class).lessThan("page", pageCount).findAll().size();
   }
 }
Example #17
0
  public void getFromDatabase() {
    mEntityList.clear();

    RealmResults<RealmZcool> zcoolRealmResults = mRealm.where(RealmZcool.class).findAll();
    for (int i = zcoolRealmResults.size() - 1; i >= 0; i--) {
      mEntityList.add(zcoolRealmResults.get(i).toEntity());
    }
  }
 // Used to see realm DB in a toast, but will be remove in final run
 public void realmResults(View view) {
   try {
     RealmResults<RoomsDB> results = realm.where(RoomsDB.class).findAll();
     Toast.makeText(getApplicationContext(), "" + results, Toast.LENGTH_SHORT).show();
   } catch (Exception e) {
     Log.d(TAG, "Results" + e);
   }
 }
Example #19
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();
 }
 private void type3Reverse() {
   ArrayList<BaseMonster> sorting = new ArrayList<>();
   for (int i = 0; i < monsterList.size(); i++) {
     if (monsterList.get(i).getType3() >= 0) {
       sorting.add(monsterList.get(i));
       monsterList.remove(i);
       i--;
     }
   }
   Collections.reverse(sorting);
   for (int i = 0; i < sorting.size(); i++) {
     monsterList.add(i, sorting.get(i));
   }
   if (monsterList.contains(realm.where(BaseMonster.class).equalTo("monsterId", 0).findFirst())) {
     monsterList.remove(realm.where(BaseMonster.class).equalTo("monsterId", 0).findFirst());
     monsterList.add(0, realm.where(BaseMonster.class).equalTo("monsterId", 0).findFirst());
   }
 }
 public boolean isWatchTvReserveWithProgramId(String programId) {
   RealmResults<WatchTvObject> results =
       mRealm.where(WatchTvObject.class).equalTo("sProgramId", programId).findAll();
   if (results.size() > 0) {
     return true;
   } else {
     return false;
   }
 }
 public boolean isWishAsset(String assetId) {
   RealmResults<WishObject> results =
       mRealm.where(WishObject.class).equalTo("sAssetId", assetId).findAll();
   if (results.size() > 0) {
     return true;
   } else {
     return false;
   }
 }
 public boolean isBookmarkChannelWithChannelId(String channelId) {
   RealmResults<BookmarkChannelObject> results =
       mRealm.where(BookmarkChannelObject.class).equalTo("sChannelId", channelId).findAll();
   if (results.size() > 0) {
     return true;
   } else {
     return false;
   }
 }
  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;
  }
 public Collection<DoctorLocation> findBy(String nameToSearch) {
   Collection<DoctorLocation> doctorLocationsByName;
   if (nameToSearch.trim().isEmpty()) {
     doctorLocationsByName = getAll();
   } else {
     doctorLocationsByName =
         realm.where(DoctorLocation.class).contains("name", nameToSearch, false).findAll();
   }
   return doctorLocationsByName;
 }
Example #26
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 MainCategoryObject getMainCategoryObject(int i) {
   String sSortNo = String.valueOf(i);
   RealmResults<MainCategoryObject> results =
       mRealm.where(MainCategoryObject.class).equalTo("sSortNo", sSortNo).findAll();
   if (results.size() > 0) {
     return results.get(0);
   } else {
     return null;
   }
 }
  /**
   * @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);
  }
Example #29
0
  /**
   * @param pageSize 分页大小.
   * @param page 第几页,从1开始.
   */
  public void getFromDatabase(int pageSize, int page) {
    if (page == 1) mEntityList.clear();
    RealmResults<RealmZcool> zcoolRealmResults = mRealm.where(RealmZcool.class).findAll();
    // 反序取数据,即 startPos > endPos.
    int startPos = Math.max(zcoolRealmResults.size() - 1 - (page - 1) * pageSize, 0);
    int endPos = Math.max(startPos - pageSize, 0);

    for (int i = startPos; i > endPos; i--) {
      mEntityList.add(zcoolRealmResults.get(i).toEntity());
    }
  }
 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();
 }