Thillai K Thillai K - 1 month ago 13
Android Question

How to pass data from realm results to an array list?

I have executed a realm transaction and have passed a json array for my data model.

public void execute(Realm realm){
for (int i = 0; i<menuListArray.length(); i++ ){
try{
JSONObject jObject = menuListArray.getJSONObject(i);
user.setMenuTitle(jObject.getString("title"));
realm.copyToRealm(user);
Intent intent = new Intent(getApplication(), ProfileLandingActivity.class);
startActivity(intent);
finish();
} catch (Exception e){
e.printStackTrace();
}
}
}


I have executed the following query to fetch the object

public RealmResults<User> getUserMenu() {
return realm.where(User.class).distinct("menuTitle");
}


I am using the realm result
getUserMenu()
in another activity:

RealmResults<User> users = RealmController.initialize(this).getUserMenu();


Now if I execute
users.first()
I can only fetch the first data from JSON and if I execute
users.last()
I can only fetch the last data from JSON. But I have to fetch all the data from realm result users. How shall I fetch all the data from JSON? I have to pass those data into an array list.

Pardon me if any of my statement in question haven't met the developer language as I am trying to become one.

Answer

You have to use Intent outside of for loop as below...

public void execute(Realm realm){
        for (int i = 0; i<menuListArray.length(); i++ ){
            try{
                JSONObject jObject = menuListArray.getJSONObject(i);
                user.setMenuTitle(jObject.getString("title"));
                realm.copyToRealm(user);
            } catch (Exception e){
                e.printStackTrace();
            }
        }
        Intent intent = new Intent(getApplication(), ProfileLandingActivity.class);
        startActivity(intent);
        finish();
    }

and you can get all title using this code

for (User userData : users ) {
            String title = userData.getMenuTitle();
        }