2016-01-13 44 views
-2

我想使用共享首選項。Android - SharedPrefs在片段中使用

我創建了一個類但─

package com.bscheme.linkkin.utils; 

import android.content.Context; 
import android.content.SharedPreferences; 
import com.bscheme.linkkin.R; 

public class SharedDataSaveLoad { 

    public static void save(Context context, String key, String value) { 
     SharedPreferences sharedPreferences = context.getSharedPreferences(context.getResources().getString(R.string.preference_file_key),Context.MODE_PRIVATE); 
     SharedPreferences.Editor editor = sharedPreferences.edit(); 
     editor.putString(key, value); 
     editor.commit(); 
    } 
    public static void save(Context context,String key, int value) { 
     SharedPreferences sharedPreferences = context.getSharedPreferences(context.getResources().getString(R.string.preference_file_key),Context.MODE_PRIVATE); 
     SharedPreferences.Editor editor = sharedPreferences.edit(); 
     editor.putInt(key, value); 
     editor.commit(); 
    } 

    public static String load(Context context, String key) { 
     SharedPreferences sharedPreferences = context.getSharedPreferences(context.getResources().getString(R.string.preference_file_key), Context.MODE_PRIVATE); 
     return sharedPreferences.getString(key, ""); 
    } 
    public static int loadInteger(Context context,String key) { 
     SharedPreferences sharedPreferences = context.getSharedPreferences(context.getResources().getString(R.string.preference_file_key), Context.MODE_PRIVATE); 
     return sharedPreferences.getInt(key, 0); 
    } 

    public static void remove(Context context,String key){ 
     SharedPreferences sharedPreferences = context.getSharedPreferences(context.getResources().getString(R.string.preference_file_key),Context.MODE_PRIVATE); 
     SharedPreferences.Editor editor = sharedPreferences.edit(); 
     editor.remove(key); 
     editor.commit(); 
    } 


} 

而且我有一個片段called- KindomFragment.java

而且在使用輔助類SharedDataSaveLoad.class KindomFragment.java這樣 -

SharedDataSaveLoad.save(
         KindomFragment.this, 
         getResources().getString(R.string.shared_pref_key_kingdom_last_updated), 
         String.valueOf(System.currentTimeMillis()) 
         ); 

而我得到這個 -

enter image description here

任何人都可以請幫助?

在此先感謝幫助:)。

+2

片段沒有上下文... – Selvin

回答

4

您需要發佈Context爲第PARAM

SharedDataSaveLoad.save(
             getActivity(), 
             getResources().getString(R.string.shared_pref_key_kingdom_last_updated), 
             String.valueOf(System.currentTimeMillis()) 
            ); 
+0

謝謝,這是工作:) –