从另一个班级打电话时初始化

问题描述 投票:0回答:1
public class Tab1 extends Fragment {  

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

        clear()

        return rootView;
    }    

    public void clear() {

        SharedPreferences sharedPreferences = getActivity().getPreferences(0);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.commit();
    }
}

如果我想从另一个类中调用方法clear()而不是它自己的Tab1,我需要初始化它才能正常工作,因为此时我从另一个类调用时在java.lang.NullPointerException: Attempt to invoke virtual method上获得SharedPreferences sharedPreferences = getActivity().getPreferences(0);

java android
1个回答
0
投票

它可能是没有创建Activity

试试这个

protected Activity mActivity;


public void onAttach(Context context) {
    super.onAttach(context);
    this.mActivity = (Activity)context;
}

然后在你的代码中使用。

public void clear() {
    SharedPreferences sharedPreferences = mActivity.getPreferences(0);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear();
    editor.commit();
}
© www.soinside.com 2019 - 2024. All rights reserved.