2012-03-07 3 views
-2

공유 환경 설정을 사용하여 활동 중 하나에 데이터를 저장했습니다. 이제 다른 활동에서 데이터를 사용하고 싶습니다. 어떻게해야합니까?android의 다른 클래스에서 공유 환경 설정 데이터를 사용하는 방법은 무엇입니까?

+0

당신이 얻을 수있는 환경을 어디서나 전체 응용 프로그램에서 – vipin

+3

이 질문을하기 전에 검색을 시도 했습니까? – Deva

+0

아니요, 시도해보십시오. – MidhunVP

답변

3

PREFS_NAME는 공유 환경 설정에 저장된 값입니다.

public static final String PREFS_NAME = "MyPrefsFile";  

// Restore preferences 
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 
    boolean silent = settings.getBoolean("silentMode", false) 

Restoring preferences

편집에서 : 1 줄 일 이잖아 모든 클래스에서 값을 호출 할 수 있습니다 OOPS.You의 세터 게터의 method.Perfect 사용을 즉, 모든 클래스 중 하나를 사용하려면

일반 클래스 이름을 ReturningClass로 만듭니다. 당신은 당신의 sharedPreference.Then 그냥 sharedPreference 만들기 클래스 context.from 통과

int usersharedpreference=ReturningClass.getMyIntPref(mContext); 
+0

흠 ... 널 포인터 예외가 발생합니다 ... 왜? –

8

을이 method.Just 전화를 설정 한 후에

public class ReturningClass { 

private static String MY_STRING_PREF = "mystringpref"; 

private static String MY_INT_PREF = "shareduserid"; 

public static SharedPreferences getPrefs(Context context) { 


    return context.getSharedPreferences("UserNameAcrossApplication", context.MODE_PRIVATE); 

} 

public static String getMyStringPref(Context context) { 

    return getPrefs(context).getString(MY_STRING_PREF, "default"); 
} 

public static int getMyIntPref(Context context) { 

    return getPrefs(context).getInt(MY_INT_PREF, 0); 
} 

public static void setMyStringPref(Context context, String value) { 
    // perform validation etc.. 
    getPrefs(context).edit().putString(MY_STRING_PREF, value).commit(); 
} 

public static void setMyIntPref(Context context, int value) { 
    // perform validation etc.. 
    getPrefs(context).edit().putInt(MY_INT_PREF, value).commit(); 
} 

ReturningClass.setMyIntPref(mContext,22); 

를 호출하여 값을 설정 공유 데이터를 추가 할 위치입니다. 같은 코드의 작은 예 :

SharedPreferences prefs = this.getSharedPreferences("CONSTANT_FILE_NAME", 
       Context.MODE_PRIVATE); 

SharedPreferences.Editor editor = prefs.edit(); 
       editor.putBoolean("isPaid", true); 
       editor.commit(); 

그리고 공유 데이터가이 코드를 사용 검색 : 개발자 사이트에서이 읽기

SharedPreferences prefs = this.getSharedPreferences("CONSTANT_FILE_NAME", 
        Context.MODE_PRIVATE); 
prefs.getBoolean("isPaid",false); 

을 : click here

+0

어떤 이유인지 나는 널 ... 왜? –

0
//decleration 
SharedPreferences saveWord; 

//onCreate 
saveWord=PreferenceManager.getDefaultSharedPreferences(ActivityName.this); 
String word=saveWord.getBoolean(PREFS_NAME, false); 
+0

... 질문은 ** 다른 ** 클래스에서 액세스하는 것에 관한 것입니다 ... 동일하지 않습니다. –

관련 문제