尝试实现SharedPreferences时遇到困难

时间:2014-06-14 13:28:07

标签: java android sharedpreferences

我是初学者,在尝试实施SharedPreferences以保存复选框状态时遇到了一些问题。我一直在谷歌搜索答案,但没有运气。我无法理解什么,我的代码有一些问题。

SuikodenFragment.java

的上半部分
public class SuikodenFragment extends Fragment implements android.widget.CompoundButton.OnCheckedChangeListener{
private final String TAG = getClass().getSimpleName();
public static final String suikodenprefs = "SuikodenPrefs" ;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}


@Override
public  View onCreateView(LayoutInflater inflater, ViewGroup container, 
        Bundle savedInstanceState) { 
    // Inflate the layout for this fragment
    View view =  inflater.inflate(R.layout.suikoden_main_activity1, container, false);
    // you can use findViewById() using the above 'view'
    // get the listview
    expListView = (ExpandableListView) view.findViewById(R.id.suikodenList1);

    // preparing list data
    prepareListData();

    listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);

    // setting list adapter
    expListView.setAdapter(listAdapter);

    SharedPreferences settings = getSharedPreferences(suikodenprefs, 0);
    boolean isChecked = settings.getBoolean("Tick the box", false);
    setSilent(isChecked);

    return view;
}

我在getSharedPreferences上遇到错误 - 它说&#39;方法getSharedPreferences(String,int)未定义类型SuikodenFragment&#39;

进一步在我的 SuikodenFragment.java

@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
    CheckBox checkBox = (CheckBox) expListView.findViewById(R.id.checkbox_tick);
    checkBox.setOnCheckedChangeListener(this);
    if (isChecked)
        // Add the tick to the box
        Log.d(TAG, "Tick the box");
     else
        // Remove the tick in the box
        Log.d(TAG, "Untick the box");
}

@Override
public void onStop(){
   super.onStop();
// SharedPreferences sharedpreferences = getSharedPreferences(suikodenprefs, Context.MODE_PRIVATE);
   SharedPreferences settings = getSharedPreferences(suikodenprefs, 0);
   settings.edit().putBoolean("Tick the box",true).commit();
}

上面的代码是复选框和保存复选框状态的代码,我希望如此。我再次在getSharedPreferences上得到相同的错误。任何帮助都会在这里,因为我真的不了解SharedPreferences。提前谢谢!

1 个答案:

答案 0 :(得分:1)

用此代码替换您的代码

SharedPreferences settings = getActivity().getSharedPreferences(suikodenprefs, 0);
希望它会对你有所帮助!