0

In my app I have two pages, one page shows the paerson information and another page shows the news information. I am using Realm database for local storage. I have used some mock data of persons and news, which will appear at the starting of the app. Now the problem is when I run my app, at first I click on person button and it is showing the person information, but if I click News button it is completely blank. nothing is shown on the window. Alterntively after uninstalling the app if I click news button at first, the news information is showing, but after clicking the person button, the person page is completely blank. The problem both pages are not updated simultaneously. I do not what would be the problem in this case.

I am giving my code in short

PersonPage Activity is

public class PersonPage extends AppCompatActivity implements PersonAdapter.PersonListListener{

private RecyclerView recyclerView;
private PersonAdapter adapter;
private Realm personRealm;
private RealmResults<PersonModel> personResult;

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

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

    setUpRecycler();

    if (!Prefs.with(this).getPreLoad()) {
        setRealmData();
    }
    showAllPersons();

}

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

private void setAdapter(RealmResults<PersonModel> results) {

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

    recyclerView.setHasFixedSize(true);
    final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(layoutManager);
}

private void setRealmData(){

    List<PersonModel> colleague = 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("Comapny2");
    model.setTitle("Title1");
    person.add(model);

    for (PersonModel realmModel : person) {
            // Persist the colleague data
        colleagueRealm.beginTransaction();
        colleagueRealm.copyToRealm(realmModel);
        colleagueRealm.commitTransaction();
    }

    Prefs.with(this).setPreLoad(true);
}

@Override
protected void onDestroy() {
    if (personRealm!= null)
        personRealm.close();
    super.onDestroy();
   }
}

My NewsPage Activity is

  public class NewsPage extends AppCompatActivity implements NewsAdapter.NewsChangeListener {

    private RecyclerView recyclerView;
    private NewsAdapter adapter;
    private Realm newsRealm;
    private RealmResults<NewsModel> newsResult;


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

        newsRealm = Realm.getDefaultInstance();
        recyclerView = (RecyclerView) findViewById(R.id.news_recycler);

        setUpRecycler();

        if (!Prefs.with(this).getPreLoad()) {
            setRealmData();
        }
        showAllNews();


    }
    private void showAllNews() {
        newsResult = newsRealm.where(NewsModel.class).findAll();
        setAdapter(newsResult);
        adapter.notifyDataSetChanged();
    }

    private void setAdapter(RealmResults<NewsModel> results) {
        adapter = new NewsAdapter(this, newsRealm.where(NewsModel.class).findAllSortedAsync("id"),this);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    private void setUpRecycler() {

        recyclerView.setHasFixedSize(true);   
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
    }

    private void setRealmData() {

        List<NewsModel> newsItem = new ArrayList<>();

        NewsModel model = new NewsModel();
        model.setId(1+System.currentTimeMillis());
        model.setImage(R.drawable.image1);
        model.setTitle("Title1");
        model.setDate("01.02.2017");
        model.setDetail("Deatils1");
        newsItem.add(model);

        model = new NewsModel();
        model.setId(2+System.currentTimeMillis());
        model.setImage(R.drawable.image2);
        model.setTitle("Title2");
        model.setDate("24.05.2017");
        model.setDetail("Deatils2");
        newsItem.add(model);


        for (NewsModel realmModel : newsItem) {
            // Persist the news data
            newsRealm.beginTransaction();
            newsRealm.insertOrUpdate(realmModel);
            newsRealm.commitTransaction();
        }

        Prefs.with(this).setPreLoad(true);
    }


    @Override
    protected void onDestroy() {
        if (newsRealm!= null)
            newsRealm.close();
        super.onDestroy();
     }
   }
2
  • @EpicPanda is this question looks duplicate to the previous one Commented Aug 8, 2017 at 10:32
  • I answered this question on that question. You just didn't change Prefs to initialData() even though the answer said so in the edit, see stackoverflow.com/a/45509763/2413303 Commented Aug 8, 2017 at 10:33

2 Answers 2

0

The problem here seems to be this statement.

if (!Prefs.with(this).getPreLoad()) {
        setRealmData();
    }

Every time you load your Persons list you are setting getPreLoad to true;

Prefs.with(this).setPreLoad(true);

When you load the News list it wont load the model from database because it will always get this statement Prefs.with(this).getPreLoad() as false.

EDIT:

you can use different identifiers for Person and News. In your Prefs class create a seperate identifier for both and set them in their respective classes:

In your Prefs class add these methods:

public static void setPreLoadPerson(boolean shouldLoad) {

    sharedPreferences.edit().putBoolean("loadperson", shouldLoad);
}

public static void setPreLoadNews(boolean shouldLoad) {

    sharedPreferences.edit().putBoolean("loadNews", shouldLoad);
}

public static boolean getPreLoadPerson() {
    return sharedPreferences.getBoolean("loadperson", false);
}
public static boolean getPreLoadNews() {
    return sharedPreferences.getBoolean("loadNews", false);
}

Then in your respective classes get and set it according to you need.

PS : i wrote this code without any compiler so you might get some typo.

Sign up to request clarification or add additional context in comments.

6 Comments

But if I remove this line, The data continues to looping. How can I make check that the data is loaded fror news and Person here
i edited my asnwer. You can try this aproach.
@M.Waqes But how can I declare two different identifier in same calss in this case. Because I need to create constructor in this case like public Prefs(Context context) { sharedPreferences = context.getApplicationContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); }
Thank you. it is working now. I have accepted your answer. But I have another question. may be not related to this question. Could you plaese explain me how can updated data inside setRealmData() method. I use this data as a mock database. I would like get all notification if I add some new data here or delete any data
I am sorry i am not that much familiar with Realm but from what i know you could use something like this :realm.io/docs/java/latest/api/io/realm/RealmChangeListener.html
|
0
if (!Prefs.with(this).getPreLoad()) {
    setRealmData();
}

This code should be replaced by using RealmConfiguration.Builder's initialData(Realm.Transaction) method.

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

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

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


        for (MyColleagueModel 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 CustomApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this);
        Realm.setDefaultConfiguration(new RealmConfiguration.Builder()
                      .deleteIfMigrationNeeded()
                      .initialData(new InitialData())
                      .build());
    }
}

13 Comments

how can I write it in my code.
Shall I create two different class for news and person like this. this class contain the person information. but what would be the case for news. then how can I declare base application
Just replace Prefs.with().preload with initialData. What you need to write to db as initial data is what you'd add "on preload".
Yes. That is working for my colleague. But I also want to set data for news.in that case I need to create another class with initial data then how can I declare .initialData(new InitialData())
|