【问题标题】:java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Switch.setChecked(boolean)' on a null object reference [duplicate]java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void android.widget.Switch.setChecked(boolean)”[重复]
【发布时间】:2018-05-02 12:37:20
【问题描述】:

我创建了一个片段活动,我想使用 SharedPreferences 保存切换按钮状态,但是当我尝试打开这个片段活动时,应用程序因 java.lang.NullPointerException 而崩溃,指的是“switchbutton.setChecked(preferences. getBoolean("名称", 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" />

【问题讨论】:

    标签: android nullpointerexception sharedpreferences android-sharedpreferences


    【解决方案1】:

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

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

    Please refer this document

    【讨论】:

    • 非常感谢您提供此参考资料,这对我很有帮助。我很感激。
    【解决方案2】:

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

    【讨论】:

    • 已经包含了,我忘了加这个代码,不好意思
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多