简体   繁体   中英

for-loop doesn't work in android try-catch block

I am making database of my school's building and classroom with Realm. But, 'for-loop' in try-catch doesn't work:

public void startCheckRealm() {
    // Writing DataBase with Realm
    try {
        Log.d("Realm", "Init");
        InitializeAPI.init_BuildingRoom(getActivity().getApplicationContext());
        Log.d("Realm", "Complete");
    } catch(Exception e) {
        e.printStackTrace();
    }

    // Trying to check the Database whether it is right or wrong
    try {
        Log.d("Realm Test", "2nd Try Catch");

        Realm.init(getActivity().getApplicationContext());
        Realm realm = Realm.getDefaultInstance();

        RealmResults<BuildingList> buildingLists = realm.where(BuildingList.class).findAllSorted("buildingCode");

        int totalNumber = 0;

        for(int i = 0; i < buildingLists.size(); i++) {
            Log.d("For", "index = " + i);
            RealmResults<RoomList> rooms = buildingLists.get(i).getRoomList().sort("roomCode");

            String BuildingName = buildingLists.get(i).getBuildingName();
            String BuildingCode = buildingLists.get(i).getBuildingCode();

            for(int idx = 0; idx < rooms.size(); idx++) {
                totalNumber++;
                String RoomCode = rooms.get(idx).getRoomCode();
                String RoomName = rooms.get(idx).getRoomName();

                Log.d("Realm Test", "Number :: " + String.valueOf(totalNumber) + "   BuildingCode :: " + BuildingCode + "\t\t BuildingName :: " + BuildingName + "\t\t RoomCode :: " + RoomCode + "\t\t RoomName :: " + RoomName);
            }
        }
        Log.d("Realm Test", "2nd Try Catch Complete + " + String.valueOf(totalNumber));
    } catch(RealmException e) {
        e.printStackTrace();
    }
}

In the first try-catch, the method, which does making database, is complete without Exception. I was curious whether this database is right or wrong.

So, in 2nd try-catch, I was trying to check realm files with queries.

The problem is "for-loop" doesn't work in 2nd try-catch. Below snippet is my logcat.

D/Realm: Init
I/System.out: bdList getLength :: 52
I/System.out: roomList getLength :: 2376
D/Realm: Complete
D/Realm Test: 2nd Try Catch
D/Realm Test: 2nd Try Catch Complete + 0

I want to check my realm data with Log but, doesn't work as you can see.

If there is no problem, the logcat shows lots of my building and room lists and ends with "D/Realm Test: 2nd Try Catch Complete + 2376".

Could you explain the reason why it doesn't work? I cannot understand the reason why it doesn't work even though there is no Exception.

While in your use-case this doesn't pose a problem, when you're iterating a RealmResults inside a transaction, the results are live in every version <= 0.88.3 and >= 3.0.0.

So in that case,

    RealmResults<BuildingList> buildingLists = realm.where(BuildingList.class).findAllSorted("buildingCode");
    for(int i = 0; i < buildingLists.size(); i++) {
        BuildingList buildingList = buildingLists.get(i); // <-- !!!

will fail (it will skip every second item!)

So you should use iterators instead (3.0.0+! on <= 0.88.3 you'd do reverse iteration)

    RealmResults<BuildingList> buildingLists = realm.where(BuildingList.class).findAllSorted("buildingCode");
    for(BuildingList buildingList : buildingLists) { // <-- !!!

The reason why this works is because iterators by default create a new snapshot collection (3.0.0+), and iterating by index on a snapshot also works

OrderedRealmCollection<BuildingList> snapshot = buildingLists.createSnapshot();
for(int i = 0; i < ...

Simple: there is no exception thrown; and you only have your print statements inside the loop.

Thus the one and only conclusion: at that point in time when your for loops are executed, the corresponding list is empty . Therefore the loop body is not entered; nothing gets printed. And that has nothing to do with the fact that this loop is within a try-catch block.

That is all there is to this. So, the direct answer is: print the list size directly in front of the loop to avoid such surprises.

(of course, the interesting part is to understand what happens to the list which seems to be non-empty earlier on - but in order to debug that, you would have to add more of your code).

Two inputs: 1.Haven't used realm but looks like the syntax for getting sorted entriesis a bit different Official documentation

2.If the above point is wrong than from your code it looks like buildingList size is zero. Have you tried checking the size?

Let me know the results.

Try logging your catch block. Chances are the rest of the code including the loop didn't complete because your app was caught with the Exception.

You should debug buildingLists.size(); before for loop

Log.d("Building List Size ", buildingLists.size()+""); 

In that case you can find the value of buildingLists.size();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM