2016-07-16 85 views
0

我試圖在我的第一個活動和駐紮在第二個活動上的片段之間使用共享偏好。該代碼顯示了我迄今爲止所做的工作,但我在獲取上下文時遇到了問題。我也認爲我在做什麼不會工作,所以只需要一些快速的幫助。感謝使用片段和活動之間的共享偏好

嘗試一個空對象上調用虛擬方法android.content.Context android.content.Context.getApplicationContext()' 參考

READ PREFS

sharedPreferences = getSharedPreferences("alexcz", MODE_PRIVATE); 
String drawableString = sharedPreferences.getString("PARTICLE_TYPE", "null") 

WRITE PREF

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.fragment_particle_type, container, false); 

     white_blur = (ImageButton)view.findViewById(R.id.white_blur); 
     green_blur = (ImageButton)view.findViewById(R.id.green_blur); 
     orange_blur = (ImageButton)view.findViewById(R.id.orange_blur); 
     pink_blur = (ImageButton)view.findViewById(R.id.pink_blur); 
     yellow_blur = (ImageButton)view.findViewById(R.id.yellow_blur); 
     blue_blur = (ImageButton)view.findViewById(R.id.blue_blur); 

     main main = new main(); 
     Context context = main.getApplicationContext(); 

     sharedPref = context.getSharedPreferences("alexcz", main.MODE_PRIVATE); 
     editor = sharedPref.edit(); 

editor.putString("PARTICLE_TYPE", "white_blur"); 

     setOnClickListeners(); 
     return view; 
    } 
+0

你實際上並不是在任何地方寫字。你不使用'編輯器'。 – Vucko

回答

3

千萬不要這樣做:main main = new main();。相反:

Context context = getActivity().getApplicationContext(); 

如果你想訪問applicationContext裏面的片段。當你用一個構造函數初始化Android活動時,一切都會搞砸,只是不要這樣做。請參閱this question

0

只需更換這些線路:

main main = new main(); 
Context context = main.getApplicationContext(); 
sharedPref = context.getSharedPreferences("alexcz", main.MODE_PRIVATE); 

有:

sharedPref = getActivity().getSharedPreferences("alexcz", getActivity().MODE_PRIVATE); 
editor = sharedPref.edit(); 

getActivity().MODE_PRIVATE將顯示通過instance訪問static成員警告。