-2
 I am getting error when i rotate screen 

java.lang.RuntimeException: Unable to resume activity {com.example.naveen.bakingapp/com.example.naveen.bakingapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView$LayoutManager.onRestoreInstanceState(android.os.Parcelable)' on a null object reference at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3121) at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3152) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495) at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4098) at android.app.ActivityThread.-wrap15(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1360) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5443) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView$LayoutManager.onRestoreInstanceState(android.os.Parcelable)' on a null object reference

public class MainActivity extends AppCompatActivity {
   // @BindView(R.id.recyclerview) RecyclerView recyclerView;
    ArrayList<Receipe>receipeArrayList;
    RecyclerView recyclerView;`enter code here`
    Parcelable mListInstanceState;`enter code here`
    LinearLayoutManager layoutManager;
    private static Bundle mBundleRecyclerViewState;
    private final String KEY_RECYCLER_STATE = "recycler_state";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       // ButterKnife.bind(this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        receipeArrayList=new ArrayList<>();
        recyclerView=(RecyclerView)findViewById(R.id.recyclerview);

new GetAllReceipe().execute();
    }
    public class GetAllReceipe extends AsyncTask<String,Integer,String>
    {   String response;
        ProgressDialog dialog;
        ContentValues receipeValuesArr;
        int progressStatus = 0;
        boolean running;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            running = true;
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setMessage("Loading, please wait");
            dialog.setTitle("Connecting server");
            dialog.show();
            dialog.setCancelable(false);
            dialog.setProgress(progressStatus);
            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    running = false;
                }
            });
        }
        @Override
        protected String doInBackground(String... params) {
            URL url ;
            HttpURLConnection connection ;
            try {
                url = new URL("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json");
                connection = (HttpURLConnection) url.openConnection();
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder buffer = new StringBuilder();
                String temp;
                while ((temp=br.readLine())!=null)
                {
                    buffer.append(temp);
                }
                response=buffer.toString();

                int i = 5;
                while (running & progressStatus < 5) {
                    try {
                        progressStatus++;
                        publishProgress(progressStatus);
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (i-- == 0) {
                        running = false;
                    }
                    publishProgress(i);

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return response;
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            dialog.setProgress(progressStatus);
        }
        @Override
        protected void onPostExecute(String response) {
            //Log.i("result",response.toString());
            if (dialog!=null&&dialog.isShowing()){dialog.dismiss();}
            try {
               // JSONObject jsonObject=new JSONObject(response);
                JSONArray jsonArray=new JSONArray(response);
                for (int i=0;i<jsonArray.length();i++)
                {
                    JSONObject object=jsonArray.getJSONObject(i);
                    receipeValuesArr = new ContentValues();
                    Receipe receipe=new Receipe();
                    receipe.setReceipe_name(object.getString("name"));
                    receipe.setId(object.getInt("id"));
                    receipeArrayList.add(receipe);
                    receipeValuesArr.put(ReceipeContract.ReceipeEntry.COLUMN_RECEIPE_ID,object.getInt("id"));
                    receipeValuesArr.put(ReceipeContract.ReceipeEntry.COLUMN_RECEIPE_NAME, object.getString("name"));
                    getContentResolver().insert(ReceipeContract.ReceipeEntry.CONTENT_URI,receipeValuesArr);
                }
               //final RecyclerView.LayoutManager lmanager=new LinearLayoutManager(MainActivity.this,LinearLayoutManager.VERTICAL,true);
                layoutManager = new LinearLayoutManager(MainActivity.this);

                layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

                recyclerView.setLayoutManager(layoutManager);
                recyclerView.setAdapter(new ReceipeAdapter(receipeArrayList,MainActivity.this));
                recyclerView.setItemAnimator(new DefaultItemAnimator());

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

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putParcelable("list_state",layoutManager.onSaveInstanceState());

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

if (savedInstanceState!=null)
{
    mListInstanceState = savedInstanceState.getParcelable("list_state");

}

   /*
        assert mListInstanceState != null;
        //System.out.println(recyclerView.getLayoutManager().toString());
        if (recyclerView.getLayoutManager()!=null){
            recyclerView.getLayoutManager().onRestoreInstanceState(mListInstanceState);

        }
            else {
            System.out.println("layoutmanager is  null");
        }*/
    }
   /* @Override
    protected void onResume() {
        super.onResume();

        if (mListInstanceState != null) {
            layoutManager.onRestoreInstanceState(mListInstanceState);
        }
    }*/


    @Override
    protected void onPause()
    {
        super.onPause();

        // save RecyclerView state
        mBundleRecyclerViewState = new Bundle();
        Parcelable listState = recyclerView.getLayoutManager().onSaveInstanceState();
        mBundleRecyclerViewState.putParcelable(KEY_RECYCLER_STATE, listState);
    }

    @Override
    protected void onResume()
    {
        super.onResume();

        // restore RecyclerView state
        if (mBundleRecyclerViewState != null) {
            Parcelable listState = mBundleRecyclerViewState.getParcelable(KEY_RECYCLER_STATE);
            recyclerView.getLayoutManager().onRestoreInstanceState(listState);
        }
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

1 Answers1

1

Its happening, because after rotation your view is null, and you try to call method on this nullable view.

1) Safety code. (not recommended because you fix only crash, but not a problem)

Try change this:

if (mBundleRecyclerViewState != null) {
            Parcelable listState = mBundleRecyclerViewState.getParcelable(KEY_RECYCLER_STATE);
            recyclerView.getLayoutManager().onRestoreInstanceState(listState);
        }

To this (safety code):

    if (mBundleRecyclerViewState != null && recyclerView != null) {
        Parcelable listState = mBundleRecyclerViewState.getParcelable(KEY_RECYCLER_STATE);
        if (recyclerView.getLayoutManager() != null) {
            recyclerView.getLayoutManager().onRestoreInstanceState(listState);
        }
    }

2) Save and restore variable after rotating Android: Save variables and settings on rotation

Or in this case you may to add this code in activity:

@Override
  protected void onResume() {
    super.onResume();
    recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
  }
walkmn
  • 2,322
  • 22
  • 29
  • error is fixed but on changing screen orientation recyclerview state is not preserving – r chiranjeevi Jul 06 '17 at 06:34
  • use `onRestoreInstanceState` `onSaveInstanceState` methods for save and restore recyclerview state: https://stackoverflow.com/questions/32121761/android-save-variables-and-settings-on-rotation – walkmn Jul 07 '17 at 13:38