尝试调用虚拟方法RecyclerView $ LayoutManager.onRestoreInstanceState(android.os.Parcelable)'在空对象引用

时间:2017-07-05 15:12:42

标签: java android nullpointerexception

 I am getting error when i rotate screen 

java.lang.RuntimeException:无法恢复活动{com.example.naveen.bakingapp / com.example.naveen.bakingapp.MainActivity}:java.lang.NullPointerException:尝试调用虚方法' void android .support.v7.widget.RecyclerView $ LayoutManager.onRestoreInstanceState(android.os.Parcelable)'在null对象引用上                                                                                   在android.app.ActivityThread.performResumeActivity(ActivityThread.java:3121)                                                                                   在android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3152)                                                                                   在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495)                                                                                   在android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4098)                                                                                   在android.app.ActivityThread.-wrap15(ActivityThread.java)                                                                                   在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1360)                                                                                   在android.os.Handler.dispatchMessage(Handler.java:102)                                                                                   在android.os.Looper.loop(Looper.java:148)                                                                                   在android.app.ActivityThread.main(ActivityThread.java:5443)                                                                                   at java.lang.reflect.Method.invoke(Native Method)                                                                                   在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:728)                                                                                   在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)                                                                                引起:java.lang.NullPointerException:尝试调用虚方法' void android.support.v7.widget.RecyclerView $ LayoutManager.onRestoreInstanceState(android.os.Parcelable)'在空对象引用上

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);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

它正在发生,因为旋转后你的视图为null,你试图在这个可空的视图上调用方法。

1)安全代码。(不推荐,因为您只修复了崩溃,但没有问题)

尝试更改此内容:

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

对此(安全代码):

@Override
  protected void onResume() {
    super.onResume();
    recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
  }

2)旋转后保存并恢复变量 Android: Save variables and settings on rotation

或者在这种情况下,您可以在活动中添加此代码:

{{1}}