java.lang.NullPointerException:尝试在空对象引用上调用虚方法 'void android.widget.Switch.setChecked(boolean)'

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Switch.setChecked(boolean)' on a null object reference

我创建了一个片段 activity,我想使用 SharedPreferences 保存切换按钮状态,但是当我尝试打开这个片段时 activity 应用程序崩溃 java.lang.NullPointerException指行 "switchbutton.setChecked(preferences.getBoolean("Name", false));"。我找到了很多解决这个问题的方法,但其中 none 对我有帮助。当我尝试评论这一行时,应用程序崩溃参考行 "switchbutton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()"。你能建议任何解决方案吗?谢谢。

public class NotificationsFragment extends Fragment{

private static final String KEY_CHECKBOX = "KEY_CHECKBOX";

Switch switchbutton;
SharedPreferences preferences;
SharedPreferences.Editor editor;

public NotificationsFragment() {
    // Required empty public constructor
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.notifications_fragment, container, true);

    Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
    ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
    toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
    ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Notifications");

    ListView listView = (ListView) view.findViewById(R.id.list_view);
    ListView listView1 = (ListView) view.findViewById(R.id.list_view1);
    View horizontalLine = (View) view.findViewById(R.id.horizontal_line);

    switchbutton = (Switch) view.findViewById(R.id.switcherComp);
    preferences = getActivity().getSharedPreferences( "com.euvo.apps.notifications",MODE_PRIVATE);
    switchbutton.setChecked(preferences.getBoolean("Name", false));


    switchbutton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            if(isChecked){
                editor = (SharedPreferences.Editor) getActivity().getSharedPreferences("com.euvo.apps.notifications", MODE_PRIVATE).edit();
                editor.putBoolean("Name", true);
                editor.commit();
            }
            else{
                editor = (SharedPreferences.Editor) getActivity().getSharedPreferences("com.euvo.apps.notifications", MODE_PRIVATE).edit();
                editor.putBoolean("Name", false);
                editor.commit();
            }
        }
    });

    ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();
    ArrayList<HashMap<String, String>> arrayList1 = new ArrayList<>();
    HashMap<String, String> map;
    HashMap<String, String> map1;

    map1 = new HashMap<>();
    map1.put("Main", "Start");
    arrayList1.add(map1);

    SimpleAdapter adapter = new SimpleAdapter(this.getActivity(), 
    arrayList1, R.layout.list_item,
            new String[]{"Main"},
            new int[]{R.id.nameView});
    listView.setAdapter(adapter);
    SimpleAdapter adapter1 = new SimpleAdapter(this.getActivity(), 
    arrayList, android.R.layout.simple_list_item_2,
            new String[]{"Name", "Kurs"},
            new int[]{android.R.id.text1, android.R.id.text2});
    listView1.setAdapter(adapter1);

    return view;
}

    public void onSaveInstanceState (Bundle outState){
    }
}

片段XML代码在这里:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context="schedulebeta.perseus.com.fix_1.MainActivity"
    android:background="@color/colordarkWhite">
<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/appBar">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay"
        app:layout_scrollFlags="scroll|enterAlways|snap"/>
</android.support.design.widget.AppBarLayout>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingTop="50dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp">
    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="20dp">
    </ListView>
    <View
        android:id="@+id/horizontal_line"
        android:layout_width="wrap_content"
        android:background="@drawable/line"
        android:layout_height="1dp" />
    <ListView
        android:id="@+id/list_view1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>

`

在此处列出带有“切换”按钮的项目 XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="15dp">

<TextView
    android:id="@+id/nameView"
    android:layout_marginStart="5dp"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:textColor="@color/colorBlacklight"
    android:textSize="22sp"/>
<Switch
    android:id="@+id/switcherComp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/MySwitch" />

您的片段 XML 不包含开关元素。您必须在列表视图适配器 getView() 方法中初始化视图。

您应该在适配器 class 中初始化 Switch,它用于将列表项设置到 ListView 中。

ListAdapter listAdapter = new ListAdapter(your_list_array);
your_listview.setAdapter(listAdapter);

Please refer this document