错误:无法在静态上下文中引用非静态方法“edit”

时间:2015-08-31 07:16:05

标签: android

public class NavigationDrawerFragment extends Fragment {

    public static final String PREF_FILE_NAME="testpref";
    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerLayout mDrawerLyout;

    private boolean mUserLearnedDrawer;
    private boolean mFromSavedInstanceState;
    public NavigationDrawerFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
}


public void setUp(DrawerLayout drawerLayout,Toolbar toolbar) {
    mDrawerLyout=drawerLayout;
    mDrawerToggle=new ActionBarDrawerToggle(getActivity(),drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
        }
    };
    mDrawerLyout.setDrawerListener(mDrawerToggle);

}
 public void saveToPreferences(Context context, String preferenceName, String preferenceValue)
 {
    SharedPreferences sharedPreferences =  context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor=SharedPreferences.edit();
    editor.putString(preferenceName, preferenceValue);
    editor.commit();
}

}

所以我在线上有错误, SharedPreferences.Editor editor = SharedPreferences。 edit();

  

错误:非静态方法'edit'无法在静态上下文中引用

3 个答案:

答案 0 :(得分:3)

尝试

SharedPreferences.Editor editor=sharedPreferences.edit();

而不是

SharedPreferences.Editor editor=SharedPreferences.edit();

您无法直接SharedPreferences.edit();

您必须创建SharedPreferences的对象,并且您创建的对象为sharedPreferences,因此请使用它来调用edit()方法。

我希望它有所帮助!

答案 1 :(得分:1)

  

错误:非静态方法'编辑'无法在静态上下文中引用

表示edit是非静态方法,因此需要为访问方法创建SharedPreferences类的对象。

在当前代码sharedPreferences中,对象可用于从SharedPreferences类访问非静态方法:

SharedPreferences.Editor editor=sharedPreferences.edit();

答案 2 :(得分:0)

SharedPreferences.Editor editor = (SharedPreferences.Editor) PreferenceManager.getDefaultSharedPreferences(context);

你可以这样使用它。