Search code examples
androidandroid-recyclerviewposition

onSaveInstanceState on a null object reference


I self haven't experienced this crash but some users does get it, when I check the Firebase Crashlytics.

So I have a Recyclerview and this small piece of code does save the position.

LinearLayoutManager layoutManager;
Parcelable state;
    @Override
    protected void onPause() {
        super.onPause();
        state = layoutManager.onSaveInstanceState();
    }
    public void jsonrequest() {

        request = new JsonArrayRequest(JSON_URL, response -> {
            JSONObject jsonObject;
            lstUserCard.clear();
            for (int i = 0; i < response.length(); i++) {
                try {
                    jsonObject = response.getJSONObject(i);
                    UserCard userCard = new UserCard();
                    userCard.setfName(jsonObject.getString("fname"));
                    userCard.setDescription(jsonObject.getString("description"));
                    lstUserCard.add(userCard);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


            RecyclerViewAdapter myadapter = new RecyclerViewAdapter(this, lstUserCard) ;
            layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setAdapter(myadapter);
            layoutManager.onRestoreInstanceState(state);
        }, error -> {
            return;
        });


        requestQueue = Volley.newRequestQueue(DashBoardActivity.this);
        requestQueue.add(request);
    }

which just works fine for me but it does crash for some users.

the error in the Firebase:

Attempt to invoke virtual method 'android.os.Parcelable androidx.recyclerview.widget.LinearLayoutManager.onSaveInstanceState()' on a null object reference com.app.myapp.DashBoardActivity.onPause

And the error line is:

state = layoutManager.onSaveInstanceState();

The method jsonrequest, is called in onResume(), there is nothing inside the onCreate.

Do I have to put some code in the onCreate? would like to see some advice. Thanks in advance.


Solution

  • By the time onPause() is called your layoutManager is not initialized yet, because you only initialize it in the Response.Listener you pass to JsonArrayRequest. So you get the exception if you quickly navigate away from your Activity.

    You can solve it by initializing it with a default value or doing a null check. Also I recommend reading up about saving state in Android, because your approach is not working.