使用Realm的执行事务方法在每次运行的android上继续循环 [英] Execute transaction method using Realm continues to loop on each run android

查看:115
本文介绍了使用Realm的执行事务方法在每次运行的android上继续循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我正在使用Realm DB将所有数据存储在本地数据库中.我有一些初始的模拟数据,我想在应用程序的开始处显示它们.以前,我实现了begintransaction方法.但是在阅读了文档之后,我不得不执行tranasction方法.因为这种方法很容易更新我的新数据.现在的问题是,每当我单击该选项以显示recyclerview时,数据每次都在循环.例如我有3个数据.如果我返回上一页并再次转到此recyclerview页面,它将变为双倍,下次它将变为三倍,依此类推.我只想在视图中显示更新的数据.就像我添加第4个数据一样,将其显示给recyclerview.如何停止在应用程序中的每次运行中循环播放.

In my app I am using Realm DB to store all the data in local database. I have some initial mock data which I want to show at the starting of the app. Previously I implemented begintransaction method. But after reading the documentation I have implented execute tranasction method. Beacuse this method is updating my new data easily. Now the problem is, whenever I click the option to show the recyclerview, the data is looping each time. for example I have 3 data. If I go back to previous page and again go to this recyclerview page, it becomes double, next time it becomes tripple and so on. I want to show only the updated data into the view. Like if I add 4th data iwant to show this to recyclerview. How can I stop looping on each run in my app.

这是我的代码

人员页面

public class InitialData implements Realm.Transaction {
@Override
public void execute(Realm realm) {
    List<PersoneModel> person = new ArrayList<>();
    PersonModel model = new PersonModel();
    model.setId(1 + System.currentTimeMillis());
    model.setName("Name1");
    model.setCompany("Comapny1");
    model.setTitle("Title1");
    person.add(model);

    model = new PersonModel();
    model.setId(2 + System.currentTimeMillis());
    model.setName("Name2");
    model.setCompany("Company2");
    model.setTitle("Title2");
    person.add(model);

    model = new PersonModel();
    model.setId(2 + System.currentTimeMillis());
    model.setName("Name2");
    model.setCompany("Company2");
    model.setTitle("Title2");
    person.add(model);

    model = new PersonModel();
    model.setId(3 + System.currentTimeMillis());
    model.setName("Name3");
    model.setCompany("Comapny3");
    model.setTitle("Title3");
    person.add(model);

    for (PersonModel realmModel : colleague) {
        realm.insertOrUpdate(realmModel);
    }
}

@Override
public boolean equals(Object obj) {
    return obj != null && obj instanceof InitialData;
}

@Override
public int hashCode() {
    return InitialData.class.hashCode();
}

}

新闻页面初始数据

    public class InitialDataNews implements Realm.Transaction {
    @Override
    public void execute(Realm realm) {
    List<NewsModel> newsItem = new ArrayList<>();
    NewsModel model = new NewsModel();

    model.setId(1+System.currentTimeMillis());
    model.setImage(R.drawable.image1);
    model.setTitle("title1");
    model.setDate("12.07.2017");
    model.setDetail("deascription");
    newsItem.add(model);


    model = new NewsModel();
    model.setId(3+System.currentTimeMillis());
    model.setImage(R.drawable.image3);
    model.setTitle("title2");
    model.setDate("05.05.2017");
    model.setDetail("description");
    newsItem.add(model);

    model = new NewsModel();
    model.setId(4+System.currentTimeMillis());
    model.setImage(R.drawable.image4);
    model.setTitle("title3");
    model.setDate("13.04.2017");
    model.setDetail("description3");
    newsItem.add(model);


    .....


    for (NewsModel realmModel : newsItem) {
    realm.insertOrUpdate(realmModel);
    }
}
@Override
public boolean equals(Object obj) {
    return obj != null && obj instanceof InitialData;
}

@Override
public int hashCode() {
    return InitialData.class.hashCode();
  }

}

基本应用

 @Override
public void onCreate() {
    super.onCreate();
    // The Realm file will be located in Context.getFilesDir() with name "default.realm"
    //Here we setup the realm configuration.
    //Setting a default configuration in custom Application class, will ensure that it is available in the rest of the code.
    Realm.init(this);
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder()
        .deleteRealmIfMigrationNeeded()
        .initialData(CompositeInitialData.of(new InitialDataNews(), new InitialData()).build());
    Realm.setDefaultConfiguration(realmConfiguration);
  }

添加更改监听器

public class PersonPage extends AppCompatActivity implements PersonAdapter.PersonListListener{

private RecyclerView recyclerView;
private PersonAdapter adapter;
private Realm PersonRealm;
private RealmResults<PersoneModel> personResult;

private RealmChangeListener realmListener;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mycolleagues_layout);


    personRealm = Realm.getDefaultInstance();
    recyclerView = (RecyclerView) findViewById(R.id.colleagues_recycler);

    realmListener=new RealmChangeListener() {
        @Override
        public void onChange(Object o) {
            showAllPersons();
        }};
    colleagueRealm.addChangeListener(realmListener);

    setUpRecycler();
    }

 private void showAllPersons() {
    realmResult = personRealm.where(PersonModel.class).findAllAsync();
    setAdapter(realmResult);
    adapter.notifyDataSetChanged();
}

private void setAdapter(RealmResults<PersonModel> results) {

    adapter = new PersonAdapter(this, personRealm.where(PersonModel.class).findAllSortedAsync("id"),this);
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();
}

推荐答案

这是因为在onCreate()中,您运行basicCRUD(personRealm);会添加新的人物模型

That's because in onCreate(), you run basicCRUD(personRealm); which adds new person models

            PersonModel model = new PersonModel();
            model.setId(1 + System.currentTimeMillis());
            model.setName("Name1");
            model.setCompany("Comapny1");
            model.setTitle("Title1");
            person.add(model);

将id设置为1 + System.currentTimeMillis()时,它将是一个具有不同主键的新对象,并将其插入.如果只是12等,则会将它们更新为同一对象.

As you set id as 1 + System.currentTimeMillis(), it will be a new object with a different primary key, and it gets inserted. If it were just 1, 2 and so on then it'd update them as the same object.

非常感谢,Realm提供了RealmConfiguration.Builder() 上的rel ="nofollow noreferrer"> initialData(Realm.Transaction)方法,该方法仅允许您在首次创建数据库时或在deleteRealmIfMigrationNeeded()之后删除数据时为数据库创建初始数据.

Thankfully, Realm provides the initialData(Realm.Transaction) method on the RealmConfiguration.Builder() which allows you to create the initial data for the database only when the database is first created, or if the data is deleted after deleteRealmIfMigrationNeeded().

public class InitialData implements Realm.Transaction {
    @Override
    public void execute(Realm realm) {
        List<PersonModel> person = new ArrayList<>();
        PersonModel model = new PersonModel();
        model.setId(1 + System.currentTimeMillis());
        model.setName("Name1");
        model.setCompany("Comapny1");
        model.setTitle("Title1");
        person.add(model);

        model = new PersonModel();
        model.setId(2 + System.currentTimeMillis());
        model.setName("Name2");
        model.setCompany("Company2");
        model.setTitle("Title2");
        person.add(model);

        model = new PersonModel();
        model.setId(3 + System.currentTimeMillis());
        model.setName("Name3");
        model.setCompany("Company23");
        model.setTitle("Title3");
        person.add(model);

        model = new PersonModel();
        model.setId(4 + System.currentTimeMillis());
        model.setName("Name4");
        model.setCompany("Comapny4");
        model.setTitle("Title4");
        person.add(model);

        for (PersonModel realmModel : person) {
            realm.insertOrUpdate(realmModel);
        }
    }

    @Override
    public boolean equals(Object object) {
        return object != null && object instanceof InitialData;
    }

    @Override
    public int hashCode() {
        return InitialData.class.hashCode();
    }
}

还有

Realm.init(this);
Realm.setDefaultConfiguration(new RealmConfiguration.Builder()
                                    .deleteRealmIfMigrationNeeded()
                                    .initialData(new InitialData())
                                    .build());

要仅在一个初始数据"中提供多个初始数据"(当您提供1个事务时),就可以依靠composite design pattern在一个初始数据中提供多个初始数据,就像这样

To provide multiple "initial datas" in only one "initial data" (as you provide 1 transaction), you can rely on the composite design pattern to provide multiple initial datas in just one initial data, like so

public final class InitialDataPersons implements Realm.Transaction {
    @Override
    public void execute(Realm realm) {
        List<PersonModel> person = new ArrayList<>();
        PersonModel model = new PersonModel();
        model.setId(1 + System.currentTimeMillis());
        model.setName("Name1");
        model.setCompany("Comapny1");
        model.setTitle("Title1");
        person.add(model);

        model = new PersonModel();
        model.setId(2 + System.currentTimeMillis());
        model.setName("Name2");
        model.setCompany("Company2");
        model.setTitle("Title2");
        person.add(model);

        model = new PersonModel();
        model.setId(3 + System.currentTimeMillis());
        model.setName("Name3");
        model.setCompany("Company23");
        model.setTitle("Title3");
        person.add(model);

        model = new PersonModel();
        model.setId(4 + System.currentTimeMillis());
        model.setName("Name4");
        model.setCompany("Comapny4");
        model.setTitle("Title4");
        person.add(model);

        for (PersonModel realmModel : person) {
            realm.insertOrUpdate(realmModel);
        }
    }

    @Override
    public boolean equals(Object object) {
        return object != null && object instanceof InitialDataPersons;
    }

    @Override
    public int hashCode() {
        return InitialDataPersons.class.hashCode();
    }
}

public final class InitialDataNews implements Realm.Transaction {
    @Override
    public void execute(Realm realm) {
        List<NewsModel> newsItem = new ArrayList<>();
        NewsModel model = new NewsModel();

        model.setId(1+System.currentTimeMillis());
        model.setImage(R.drawable.image1);
        model.setTitle("title1");
        model.setDate("12.07.2017");
        model.setDetail("deascription");
        newsItem.add(model);

        model = new NewsModel();
        model.setId(3+System.currentTimeMillis());
        model.setImage(R.drawable.image3);
        model.setTitle("title2");
        model.setDate("05.05.2017");
        model.setDetail("description");
        newsItem.add(model);

        model = new NewsModel();
        model.setId(4+System.currentTimeMillis());
        model.setImage(R.drawable.image4);
        model.setTitle("title3");
        model.setDate("13.04.2017");
        model.setDetail("description3");
        newsItem.add(model);

        .....

        for (NewsModel realmModel : newsItem) {
            realm.insertOrUpdate(realmModel);
        }
    }

    @Override
    public boolean equals(Object obj) {
        return obj != null && obj instanceof InitialDataNews;
    }

    @Override
    public int hashCode() {
        return InitialDataNews.class.hashCode();
    }
}

public final class CompositeInitialData implements Realm.Transaction {
    private final Realm.Transaction[] transactions;

    private CompositeInitialData(Realm.Transaction... transactions) { // `of` is prettier
        this.transactions = transactions;
    }

    public static CompositeInitialData of(Realm.Transaction... transactions) {
        return new CompositeInitialData(transactions);
    }

    @Override
    public void execute(Realm realm) {
        for(Realm.Transaction transaction : transactions) {
            transaction.execute(realm);
        }
    }

    @Override
    public boolean equals(Object obj) {
        return obj != null && obj instanceof CompositeInitialData; // you might want autogenerated equals instead
    }

    @Override
    public int hashCode() {
        return CompositeInitialData.class.hashCode(); // you might want autogenerated hashCode instead
    }
}

您可以通过这种方式提供

This way you can provide

Realm.init(this);
Realm.setDefaultConfiguration(new RealmConfiguration.Builder()
             .deleteIfMigrationNeeded()
             .initialData(CompositeInitialData.of(new InitialDataNews(), new InitialDataPersons()))
             .build());

这篇关于使用Realm的执行事务方法在每次运行的android上继续循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆