Where should I place the code so that the data is NOT overwritten and added several times? That is, I need to save the data to the rialm only once at the first launch, using the following code:

Realm realm = Realm.getDefaultInstance(); Task item = new Task(); item.setName("Item1"); item.setSubname("SubItem1"); item.setId(UUID.randomUUID().toString()); item.setTimestamp(System.currentTimeMillis()); realm.beginTransaction(); realm.copyToRealm(item); realm.commitTransaction(); realm.close(); 

.

    2 answers 2

     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean isFirstStart = prefs.getBoolean("first_start", true); if (isFirstStart) { // очистка БД (если юзер закроет приложение но данные до конца не вставятся) // ваш код вставки в БД prefs.edit().putBoolean("first_start", false).apply(); } 

    Yes, it would be possible to make a check on an empty database, but suddenly the data will not have time to insert everything and the user will close the application? Therefore, I am for this method, "in the forehead."

    • I can’t import import SharedPreferencesManager, also an error on the context - Julia
    • @Julia context is the context. Do you know about him? If you write code in the activity, you can pass this as it - Flippy
    • And about the import, I made a typo. The answer has changed. If again the error is then write the code yourself, you will be offered an IDE of the desired class) - Flippy

    Suppose you have a storeduser class

     StoredUser storedUser; Realm.setDefaultConfiguration(config); storedUser = Realm.getDefaultInstance().where(StoredUser.class).findFirst(); if(storedUser!=null){ //объект сохранен }else{ Realm.getDefaultInstance().executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { storedUser = realm.createObject(StoredUser.class); storedUser.someField(true); } }); }