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

时间:2018-05-02 12:37:20

标签: android nullpointerexception sharedpreferences android-sharedpreferences

我已经创建了一个片段活动,我想用SharedPreferences保存Switch按钮状态,但是当我尝试打开这个片段活动时,应用程序崩溃了java.lang.NullPointerException,引用了line" switchbutton .setChecked(preferences.getBoolean(" Name",false));"。我找到了很多这个问题的解决方案,但没有一个能帮助我。当我尝试评论此行时,应用程序崩溃,引用行" 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" />

2 个答案:

答案 0 :(得分:0)

您的片段XML不包含switch元素。您必须在listview的适配器的getView()方法中启动视图。

答案 1 :(得分:0)

您必须初始化切换到适配器类,用于将列表项设置为ListView。

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

Please refer this document