realm-java icon indicating copy to clipboard operation
realm-java copied to clipboard

ThrowingException 2, rowIndex is less than 0, when there are actually items inside Realm

Open KaeMs opened this issue 9 years ago • 25 comments

Goal

A chat app using realm directly as a dataset.

Expected Results

A fully working chat app with Realm as its dataset

Actual Results

A half working chat app with Realm as its dataset. By half working I mean, it works well in sending and receiving chat, but when a chat room contains more than 1 item, all of the items are gone from view, though still there in the dataset inside the adapter.

Steps & Code to Reproduce

Once I have 2 or more items in adapter, the problem occurs

Code Sample

This is how I setup the adapter :

private RealmList<MessageItem> mDataset;
public ChatRoomAsUserAdapter(Context context) {
    this.context = context;
    this.userId = Utilities.getUserInformation(context, SharedPreferencesList.userIDString);
    this.mDataset = new RealmList<>();
}

...

MIApplication.realm.beginTransaction();
// Getting chat inside the specific room id
ChatRoomWrapper chatFriendRealmResult = MIApplication.realm.where(ChatRoomWrapper.class)
        .equalTo("room_id", suppliedRoomId).findFirst();

if (chatFriendRealmResult != null){
    mDataset = chatFriendRealmResult.message;
} else {
    // If not found, create new Object with the roomId then insert it into RealmDb
    ChatRoomWrapper chatRoomWrapper = new ChatRoomWrapper();
    chatRoomWrapper.room_id = suppliedRoomId;
    chatRoomWrapper.message = new RealmList<>();
    MIApplication.realm.copyToRealmOrUpdate(chatRoomWrapper);
    mDataset = chatRoomWrapper.message;
}
MIApplication.realm.commitTransaction();

This is how I add item into the adapter :

MIApplication.realm.beginTransaction();
ChatRoomWrapper chatFriendRealmResult = MIApplication.realm.where(ChatRoomWrapper.class)
        .equalTo("room_id", adapterRoomId).findFirst();
chatFriendRealmResult.message.add(0, messageItem);
MIApplication.realm.copyToRealmOrUpdate(chatFriendRealmResult);
//                mDataset = chatFriendRealmResult.message;
MIApplication.realm.commitTransaction();
notifyItemInserted(0);

And the error I got :

E/REALM_JNI: jni: ThrowingException 2, rowIndex is less than 0., .
E/REALM_JNI: Exception has been thrown: rowIndex is less than 0.

Version of Realm and tooling

Realm version(s): 3.1.2

Realm sync feature enabled: no (I guess? I don't know what this is....)

Android Studio version: 2.3.1

Which Android version and device: Asus Zenfone C - KitKat 4.4.2 & Samsung J7 (2016) - Marshmallow 6.0.1

KaeMs avatar Apr 20 '17 02:04 KaeMs

Can you show the full backtrace?

beeender avatar Apr 20 '17 05:04 beeender

notifyItemInserted(0);

why not use RealmChangeListener, maybe even RealmRecyclerViewAdapter?

Zhuinden avatar Apr 20 '17 06:04 Zhuinden

@beeender Here's the full backtrace, it's basically telling the same thing over and over

04-20 14:43:32.721 29610-29610/com.ast.dev E/REALM_JNI: jni: ThrowingException 2, rowIndex is less than 0., .
04-20 14:43:32.721 29610-29610/com.ast.dev E/REALM_JNI: Exception has been thrown: rowIndex is less than 0.
04-20 14:43:32.721 29610-29610/com.ast.dev E/NPALLayoutManager: meet an IOOBE in RecyclerView
04-20 14:43:32.781 29610-29610/com.ast.dev E/REALM_JNI: jni: ThrowingException 2, rowIndex is less than 0., .
04-20 14:43:32.781 29610-29610/com.ast.dev E/REALM_JNI: Exception has been thrown: rowIndex is less than 0.
04-20 14:43:32.781 29610-29610/com.ast.dev E/NPALLayoutManager: meet an IOOBE in RecyclerView
04-20 14:43:33.151 29610-29610/com.ast.dev E/REALM_JNI: jni: ThrowingException 2, rowIndex is less than 0., .
04-20 14:43:33.151 29610-29610/com.ast.dev E/REALM_JNI: Exception has been thrown: rowIndex is less than 0.
04-20 14:43:33.151 29610-29610/com.ast.dev E/NPALLayoutManager: meet an IOOBE in RecyclerView

That part with NPALayoutManager is because of a try catch block in a Custom LLM class

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        try {
            super.onLayoutChildren(recycler, state);
        } catch (IndexOutOfBoundsException e) {
            Log.e("NPALLayoutManager", "meet an IOOBE in RecyclerView");
        }
    }

@Zhuinden the code worked long time ago and I haven't learnt more about Realm since that time. But I've tried using RealmChangeListener and at that time, I didn't know how to differentiate between single item insert and whole dataset change. I cannot always use notifyDatasetChanged(). Please do teach me if you found that my way of using Realm is wrong in the context of chat app. Hmm RealmRecyclerViewAdapter.. I haven't used it.. I am going to try it now

KaeMs avatar Apr 20 '17 07:04 KaeMs

I didn't know how to differentiate between single item insert and whole dataset change. I cannot always use notifyDatasetChanged().

Realm-Android-Adapters 2.0.0 and Realm Java 3.x supports fine-grained notifications and receiving "change sets" for RealmResults with which RealmRecyclerViewAdapter handles notifyItemRangeInserted() and co. automatically, and not notifyDataSetChanged().

Zhuinden avatar Apr 20 '17 10:04 Zhuinden

@Zhuinden Well that's interesting, yesterday I've managed to change stuff inside my adapter but haven't tried it yet. Will ask in SO for any trouble. So basically it handles it automatically? So I don't have to do realmResults.addOnChangeListener() (Forgot the method name, but I think this is it) ?

KaeMs avatar Apr 21 '17 02:04 KaeMs

yup

Zhuinden avatar Apr 21 '17 07:04 Zhuinden

Sorry for long reply, it still doesn't work.. The same error still gets thrown

04-25 10:05:43.121 22814-22814/com.ast.dev E/REALM_JNI: jni: ThrowingException 2, rowIndex is less than 0., .
04-25 10:05:43.121 22814-22814/com.ast.dev E/REALM_JNI: Exception has been thrown: rowIndex is less than 0.
04-25 10:05:43.121 22814-22814/com.ast.dev E/NPALLayoutManager: meet an IOOBE in RecyclerView

I changed a bit of the code of my constructor to :

    public ChatRoomAsUserAdapter(Context context, @Nullable RealmList<MessageItem> data) {
        super(data, true);
        this.context = context;
        this.userId = Utilities.getUserInformation(context, SharedPreferencesList.userIDString);
        this.mDataset = data;
    }

So that I can still do mDataset.someMethod()..

Is there anything else I should've done which I miss? It works basically like RecyclerViewAdapter, right?

KaeMs avatar Apr 25 '17 03:04 KaeMs

So ChatRoomAsUserAdapter is RealmRecyclerViewAdapter, right?

Do you unnecessarily call notifyItemXXX methods? Realm should handle all of them.

Zhuinden avatar Apr 25 '17 07:04 Zhuinden

Nope, I don't call it anymore, and btw for extra info, this might help.. When user first enters the activity, an API call is made, and the result is handled like this :

AppController.realm.beginTransaction();
// Create new ChatFriendWrapper and input the Room ID into it to update
// the Room ID if found
ChatRoomWrapper chatRoomWrapper = AppController.realm.where(ChatRoomWrapper.class)
        .equalTo(ChatRoomWrapperFields.ROOM_ID, roomId).findFirst();

if (chatRoomWrapper != null){
    if (api.flag.equals(Constants.flagRefresh)) {
        counter = 0;

        chatRoomWrapper.message.deleteAllFromRealm();
        chatRoomWrapper.message.addAll(api.message_item_list);
        AppController.realm.copyToRealmOrUpdate(chatRoomWrapper);
        manager.scrollToPosition(0);
    } else if (api.flag.equals(Constants.flagLoad)) {
        chatRoomWrapper.message.addAll(api.message_item_list);
        AppController.realm.copyToRealmOrUpdate(chatRoomWrapper);
    }
} else {
    ChatRoomWrapper newChatRoomWrapper = new ChatRoomWrapper();
    newChatRoomWrapper.room_id = roomId;
    newChatRoomWrapper.message.addAll(api.message_item_list);
    AppController.realm.copyToRealmOrUpdate(newChatRoomWrapper);
}
AppController.realm.commitTransaction();

KaeMs avatar Apr 25 '17 08:04 KaeMs

If I delete a RealmList in the Fragment, the RealmList in the Adapter, provided that it has the same RealmList, will get updated right?

I search a RealmObject (a wrapper)by ID. This Object contains ID and a RealmList. Then I assign the List into Adapter.

KaeMs avatar Apr 26 '17 03:04 KaeMs

This is a part of the error, basically the same, but now I don't catch it using the custom LinearLayoutManager

java.lang.ArrayIndexOutOfBoundsException: rowIndex is less than 0.
    at io.realm.internal.LinkView.nativeGetTargetRowIndex(Native Method)
    at io.realm.internal.LinkView.getTargetRowIndex(LinkView.java:82)
    at io.realm.RealmList.get(RealmList.java:452)
    at com.asta.dev.classes.ChatRoomAsUserAdapter.getItemViewType(ChatRoomAsUserAdapter.java:235)
    at com.asta.dev.classes.ChatRoomAsUserAdapter.onBindViewHolder(ChatRoomAsUserAdapter.java:359)
    at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6356)
    at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6389)

KaeMs avatar Apr 26 '17 06:04 KaeMs

You use managed RealmList obtained from Realm, right?

Zhuinden avatar Apr 26 '17 07:04 Zhuinden

Yup, it's the RealmList inside the ChatRoomWrapper which I got from query.findFirst().

That's a managed RealmList right?

KaeMs avatar Apr 26 '17 07:04 KaeMs

Yes, that is a managed list. But if you don't try to manually manage the notifyItem* calls, and you're using RealmRecyclerViewAdapter, then I'm not sure what's going wrong. Any chance you can create a sample project to reproduce this?

Zhuinden avatar Apr 26 '17 08:04 Zhuinden

Yes I can create a sample project, in fact I tried a new Activity with the exact same code, except for the API call, and it worked, but when I reopened it again sometimes later, it doesn't work, should I just copy paste the activity code here?

KaeMs avatar Apr 26 '17 08:04 KaeMs

Yes, use the ```java [insert code here]```

Zhuinden avatar Apr 26 '17 10:04 Zhuinden

public class TestActivity extends AppCompatActivity {

    private ChatAdapter chatAdapter;
    RecyclerView recyclerView;
    private int tmpCount = 1;
    private String userId;
    String roomId = "0";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_message_room);
        userId = Utilities.getUserInformation(this, SharedPreferencesList.userIDString);
        roomId = "1";

        recyclerView = (RecyclerView) findViewById(R.id.fragment_message_room_recyclerView);
        setupChatRoom(roomId);

        LinearLayoutManager manager = new NPALinearLayoutManager(this,
                LinearLayoutManager.VERTICAL,
                true);

        //set Position item Recycle View
        manager.setStackFromEnd(true);
        recyclerView.setLayoutManager(manager);
        recyclerView.getItemAnimator().setChangeDuration(0);

        RelativeLayout pickImageWrapper = (RelativeLayout) findViewById(R.id.textbox_photoPickWrapper);
        pickImageWrapper.setVisibility(View.VISIBLE);
        ImageView pickImage = (ImageView) findViewById(R.id.textbox_photoPick);
        final MultiAutoCompleteTextView editTextMAC = (MultiAutoCompleteTextView) findViewById(R.id.textbox_editTextMAC);
        RelativeLayout editTextSendWrapper = (RelativeLayout) findViewById(R.id.textbox_editTextSendImgWrapper);
        editTextSendWrapper.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String commentContentText = String.valueOf(editTextMAC.getText());
                if (!commentContentText.trim().equals("")) {
                    /*editTextSendWrapper.setEnabled(false);
                    editTextSendImg.setVisibility(View.GONE);
                    editTextProgressBar.setVisibility(View.VISIBLE);*/
                    editTextMAC.setText("");
                    recyclerView.scrollToPosition(0);

                    MessageItem messageItem = new MessageItem();
                    messageItem.msg_uploaded_file = null;
                    messageItem.msg_id = tmpCount;
                    messageItem.tmp_id = tmpCount;
                    messageItem.msg_author_id = Integer.valueOf(userId);
                    messageItem.msg_author_name = Utilities.getUserInformation(TestActivity.this, SharedPreferencesList.userFNameString) + "";
                    messageItem.msg_author_alias = Utilities.getUserInformation(TestActivity.this, SharedPreferencesList.userAliasString);
                    messageItem.msg_author_avatar = Utilities.getUserInformation(TestActivity.this, SharedPreferencesList.userAvatarString);
                    String gender = Utilities.getUserInformation(TestActivity.this, SharedPreferencesList.userGender);
                    if (gender != null){
                        messageItem.msg_author_type = gender;
                    } else {
                        messageItem.msg_author_type = "";
                    }
                    messageItem.msg_message = EmojiParser.parseToAliases(commentContentText);
                    messageItem.msg_image_path = "";
                    Calendar calendar = Calendar.getInstance();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MMM/yy", Locale.getDefault());
                    messageItem.msg_date = dateFormat.format(calendar.getTime());
                    SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
                    messageItem.msg_time = timeFormat.format(calendar.getTime());
                    messageItem.msg_is_self_bool = true;
//                    messageItem.msg_is_file = 0;
                    messageItem.msg_uploaded_file = null;
                    messageItem.sent = false;
                    chatAdapter.addSingleMessage(messageItem);
                }
            }
        });
    }

    void setupChatRoom(String suppliedRoomId){
        if (!suppliedRoomId.equals("0")){
                AppController.realm.beginTransaction();
                // Getting chat inside the specific room id
                ChatRoomWrapper chatFriendRealmResult = AppController.realm.where(ChatRoomWrapper.class)
                        .equalTo(ChatRoomWrapperFields.ROOM_ID, suppliedRoomId).findFirst();

                if (chatFriendRealmResult != null){
                    chatAdapter = new ChatAdapter(this, chatFriendRealmResult.message);
                    AppController.realm.commitTransaction();
                } else {
                    // If not found, create new Object with the roomId then insert it into RealmDb
                    ChatRoomWrapper chatRoomWrapper = new ChatRoomWrapper();
                    chatRoomWrapper.room_id = suppliedRoomId;
                    chatRoomWrapper.message = new RealmList<>();
                    AppController.realm.copyToRealmOrUpdate(chatRoomWrapper);
                    AppController.realm.commitTransaction();

//                    AppController.realm.beginTransaction();
                    // Getting chat inside the specific room id
                    ChatRoomWrapper newlyCreatedChat = AppController.realm.where(ChatRoomWrapper.class)
                            .equalTo(ChatRoomWrapperFields.ROOM_ID, suppliedRoomId).findFirst();
                    chatAdapter = new ChatAdapter(this, newlyCreatedChat.message);
                    int a = 1;
                }

                recyclerView.setAdapter(chatAdapter);
        } else {
            try {
                AppController.realm.beginTransaction();
                // Just a precaution if there's any chat from the supplied Room ID
                ChatRoomWrapper chatFriendRealmResult = AppController.realm.where(ChatRoomWrapper.class)
                        .equalTo("room_id", suppliedRoomId).findFirst();

                if (chatFriendRealmResult != null){
                    chatFriendRealmResult.deleteFromRealm();
                }

                // Creating new chat from supplied Room ID
                ChatRoomWrapper chatRoomWrapper = new ChatRoomWrapper();
                chatRoomWrapper.room_id = suppliedRoomId;
                chatRoomWrapper.message = new RealmList<>();
                chatAdapter = new ChatAdapter(this, chatRoomWrapper.message);
                AppController.realm.copyToRealmOrUpdate(chatRoomWrapper);
                AppController.realm.commitTransaction();
                recyclerView.setAdapter(chatAdapter);
            } catch (Exception e){
                AppController.realm.cancelTransaction();
                Toast.makeText(this, "Fail", Toast.LENGTH_SHORT).show();
            }
        }
    }

    class ChatAdapter extends RealmRecyclerViewAdapter<MessageItem, RecyclerView.ViewHolder> {
        private final int OTHER_CHAT = 11;
        private final int OTHER_FILE = 12;
        private final int SELF_CHAT = 1;
        private final int SELF_FILE = 2;
        private final int VIEW_PROG = 0;
        // Adapter Info
        private RealmList<MessageItem> mDataset;
        private Context context;

        public ChatAdapter(Context context, @Nullable RealmList<MessageItem> data) {
            super(data, true);
            this.context = context;
            this.mDataset = data;
        }

        public void addSingleMessage(MessageItem messageItem){
            if (!roomId.equals("0")){
                try
                {
                    AppController.realm.beginTransaction();
                    ChatRoomWrapper chatFriendRealmResult = AppController.realm.where(ChatRoomWrapper.class)
                            .equalTo("room_id", roomId).findFirst();

                    if (chatFriendRealmResult != null){
                        chatFriendRealmResult.getMessage().add(messageItem);
                    } else {
                        ChatRoomWrapper chatRoomWrapper = new ChatRoomWrapper();
                        chatRoomWrapper.room_id = roomId;
                        chatRoomWrapper.message = new RealmList<>();
                        chatRoomWrapper.message.add(messageItem);
                        AppController.realm.copyToRealmOrUpdate(chatRoomWrapper);
                        this.mDataset = chatRoomWrapper.message;
                    }
//                mDataset = chatFriendRealmResult.message;
                    AppController.realm.commitTransaction();
                } catch (NullPointerException e){
                    AppController.realm.cancelTransaction();
                    Toast.makeText(context, "Message sending failure", Toast.LENGTH_SHORT).show();
                }
            } else {
                mDataset.add(0, messageItem);
            }
        }

        @Override
        public int getItemViewType(int position) {
            if (mDataset.get(position).isMsg_is_self_bool()) {
                if (mDataset.get(position).getMsg_uploaded_file() == null ||
                        mDataset.get(position).getMsg_uploaded_file().equals("default")) {
                    return SELF_CHAT;
                } else {
                    return SELF_FILE;
                }
            } else if (!mDataset.get(position).isMsg_is_self_bool()) {
                if (mDataset.get(position).getMsg_uploaded_file() == null ||
                        mDataset.get(position).getMsg_uploaded_file().equals("default")) {
                    return OTHER_CHAT;
                } else {
                    return OTHER_FILE;
                }
            } else {
                return VIEW_PROG;
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder vh;

            if (viewType == SELF_CHAT) {
                View v = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.fragment_message_self_text, parent, false);
                vh = new ChatSelfTxtViewHolder(v);
            } else if (viewType == SELF_FILE) {
                View v = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.fragment_message_self_file, parent, false);
                vh = new ChatSelfFileViewHolder(v);
            } else if (viewType == OTHER_CHAT) {
                View v = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.fragment_message_other_text, parent, false);
                vh = new ChatOtherTxtViewHolder(v);
            } else if (viewType == OTHER_FILE) {
                View v = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.fragment_message_other_file, parent, false);
                vh = new ChatOtherFileViewHolder(v);
            } else {
                View v = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.inscroll_loading_notxt, parent, false);
                vh = new LoadNoTxtViewHolder(v);
            }
            return vh;
        }
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ...
        }

KaeMs avatar Apr 26 '17 11:04 KaeMs

mDataset should be completely removed and you should use getData() and updateData() method of RealmRecyclerViewAdapter

Zhuinden avatar Apr 26 '17 12:04 Zhuinden

Hmm so everytime I need to do mDataset.add(0, messageItem); I have to query the existing data, get it updated, then execute updateData()?

KaeMs avatar Apr 27 '17 02:04 KaeMs

Oh and what I'm doing is also basically the same as getData() but I keep the reference of the realmList inside the adapter without using the method from RealmRecyclerAdapter? Because the error is still there when I refactored everything into using getData() and updateData()

KaeMs avatar Apr 27 '17 03:04 KaeMs