使用导航抽屉旋转屏幕时出现空指针异常

时间:2016-01-12 15:01:42

标签: android rotation

我创建了一个简单的导航抽屉,在纵向模式下工作正常。

nav drawer

然而,当我旋转屏幕时,我得到一个空指针异常。我的理解是不存储导航抽屉内的RecyclerView的值,因此我的custorm适配器是空的。所以我需要以某种方式存储它们。我应该用onSavedInstanceState方法吗?我不知道怎么回事。我觉得这部分很复杂。

这是我的代码。

public class NavigationDrawerFragment extends Fragment {
private RecyclerView recyclerView;
private View containerView;
public static final String PREF_FILE_NAME = "testpref";
public boolean mUserLearnedDrawer;
public boolean mFromSavedInstanceState;
private static final String KEY = "user_learned_drawer";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private TheoAdapter adapter;
public NavigationDrawerFragment() {
    // Required empty public constructor
}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(),KEY,"falser"));
    if(savedInstanceState != null){
        mFromSavedInstanceState = true;
    }


}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
   View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);

    recyclerView = (RecyclerView)layout.findViewById(R.id.drawerList);
    adapter = new TheoAdapter(getActivity(),getData());
    recyclerView.setAdapter(adapter);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    return layout;
}
public static List<Information> getData(){
    List<Information> data = new ArrayList<>();
    int [] icons = {R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher};
    String [] titles = {"Vivz","Anky","Theo","Youtube","Stargate SG1","Stargate Atlantis"};

    for(int i=0;i<titles.length;i++){
        Information information = new Information();
        information.iconId = icons[i];
        information.title = titles[i];
        data.add(information);
    }
    return data;
}





public void setUp(int fragmentId, DrawerLayout drawerLayout, Toolbar toolBar) {
    containerView = getActivity().findViewById(fragmentId);
    mDrawerLayout = drawerLayout;
    mDrawerToggle = new ActionBarDrawerToggle(getActivity(),drawerLayout,toolBar,R.string.drawer_open,R.string.drawer_close){

        @Override
        public void onDrawerOpened(View drawerView) {super.onDrawerOpened(drawerView);
           if(!mUserLearnedDrawer){
               mUserLearnedDrawer = true;
               savedToPreferences(getActivity(),KEY,mUserLearnedDrawer+ "");
           }

            getActivity().invalidateOptionsMenu();
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            getActivity().invalidateOptionsMenu();
        }
    };
    if(!mUserLearnedDrawer && !mFromSavedInstanceState){
        mDrawerLayout.openDrawer(containerView);
    }
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    mDrawerLayout.post(new Runnable() {
        @Override
        public void run() {
            mDrawerToggle.syncState();
        }
    });
}

public static void savedToPreferences(Context context, String preferenceName, String preferenceValue){
    SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME,Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(preferenceName,preferenceValue);
    editor.apply();
}

public static String readFromPreferences(Context context, String preferenceName, String defaultValue){
    SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME,Context.MODE_PRIVATE);
    return sharedPreferences.getString(preferenceName,defaultValue);
}
}

我在这一行得到空指针。

 recyclerView.setAdapter(adapter);

我的适配器是

 public class TheoAdapter extends     
 RecyclerView.Adapter<TheoAdapter.MyViewHolder> {

private LayoutInflater layoutInflater;
List<Information> data = Collections.emptyList();

public TheoAdapter(Context context,List<Information> data){
   layoutInflater = LayoutInflater.from(context);
    this.data = data;
}
@Override
public TheoAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = layoutInflater.inflate(R.layout.custom_row,parent,false);

    MyViewHolder holder = new MyViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(TheoAdapter.MyViewHolder holder, int position) {
    Information current = data.get(position);
    holder.textView.setText(current.title);
    holder.imageView.setImageResource(current.iconId);
}
 @Override
public int getItemCount() {
  return data.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView textView;
    ImageView imageView;
    public MyViewHolder(View itemView) {

        super(itemView);

        textView = (TextView)itemView.findViewById(R.id.textView);
        imageView = (ImageView)itemView.findViewById(R.id.imageView);
    }
}
}

最后,MainActivity是。

public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar)findViewById(R.id.app_bar);

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);

    drawerFragment.setUp(R.id.fragment_navigation_drawer,(DrawerLayout)findViewById(R.id.drawer_layout),toolbar);
}
}

任何想法,

由于

更新

logcat是

 java.lang.RuntimeException: Unable to start activity ComponentInfo{testing.theo.materialdesigntest/testing.theo.materialdesigntest.MainActivity}: android.view.InflateException: Binary XML file line #32: Error inflating class fragment
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                 at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947)
                                                 at android.app.ActivityThread.access$900(ActivityThread.java:151)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:135)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                              Caused by: android.view.InflateException: Binary XML file line #32: Error inflating class fragment
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
                                                 at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
                                                 at testing.theo.materialdesigntest.MainActivity.onCreate(MainActivity.java:17)
                                                 at android.app.Activity.performCreate(Activity.java:5990)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                                                 at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947) 
                                                 at android.app.ActivityThread.access$900(ActivityThread.java:151) 
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309) 
                                                 at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                 at android.os.Looper.loop(Looper.java:135) 
                                                 at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                 at java.lang.reflect.Method.invoke(Native Method) 
                                                 at java.lang.reflect.Method.invoke(Method.java:372) 
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
                                              Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
                                                 at testing.theo.materialdesigntest.NavigationDrawerFragment.onCreateView(NavigationDrawerFragment.java:60)
                                                 at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
                                                 at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1036)
                                                 at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1226)
                                                 at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2310)
                                                 at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:111)
                                                 at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:314)
                                                 at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
                                                 at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) 
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:504) 
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:414) 
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:365) 
                                                 at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256) 
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109) 
                                                 at testing.theo.materialdesigntest.MainActivity.onCreate(MainActivity.java:17) 
                                                 at android.app.Activity.performCreate(Activity.java:5990) 
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) 
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278) 
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                                                 at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947) 
                                                 at android.app.ActivityThread.access$900(ActivityThread.java:151) 
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309) 
                                                 at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                 at android.os.Looper.loop(Looper.java:135) 
                                                 at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                 at java.lang.reflect.Method.invoke(Native Method) 
                                                 at java.lang.reflect.Method.invoke(Method.java:372) 
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

1 个答案:

答案 0 :(得分:1)

在方向改变后,每次都会重新创建活动。因为它必须为新方向充气适当的布局。 您是否在不同的屏幕方向上使用不同的布局?似乎R.id.drawerList在横向布局中不存在,因此findViewById(R.id.drawerList)将返回null。