2015-08-31 51 views
2
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編輯= SharedPreferences被引用。 edit();

Error:non static method 'edit' cannot be referenced in static context

回答

2

嘗試

SharedPreferences.Editor editor=sharedPreferences.edit(); 

,而不是

SharedPreferences.Editor editor=SharedPreferences.edit(); 

你不能直接SharedPreferences.edit();

您必須創建SharedPreferences的對象,並且您已創建了哪個是sharedPreferences,因此請使用它調用edit()方法。

我希望它有幫助!

+0

非常感謝!是啊,我看到了那個錯誤... –

+1

@AsadKhan如果它可以幫助你接受答案 – Rajesh

1

Error:non static method 'edit' cannot be referenced in static context

裝置edit是非靜態方法,所以需要創建SharedPreferences類的對象訪問方法。

在當前的代碼sharedPreferences是可用於從SharedPreferences類訪問非靜態方法對象:

SharedPreferences.Editor editor=sharedPreferences.edit(); 
0
SharedPreferences.Editor editor = (SharedPreferences.Editor) PreferenceManager.getDefaultSharedPreferences(context); 

可以使用像這樣。

相關問題