2016-04-14 28 views
0

發送sharedpreference 此的數據是用於通信接口無法從內部片段中的sharedPrference中檢索數據?

@Override 
public void saveBMI(String d, String r, String f_r) { 
    sharedPreferences=getSharedPreferences("userBMI",Context.MODE_PRIVATE); 
    editor=sharedPreferences.edit(); 
    editor.putString("CheckDate",d); 
    editor.putString("BmiResult",r); 
    editor.putString("BmiWeight",f_r); 
    editor.commit(); 
} 

該方法我使用用於從共享的偏好將數據發送到另一片段

@Override 
public void showBMI() { 
    if(sharedPreferences.contains("CheckDate")) 
    { 
     c_d=sharedPreferences.getString("CheckDate",""); 
    } 
    if(sharedPreferences.contains("BmiResult")) 
    { 
     bmi_res=sharedPreferences.getString("BmiResult",""); 
    } 
    if(sharedPreferences.contains("BmiWeight")) 
    { 
     bmi_w=sharedPreferences.getString("BmiWeight",""); 
    } 

//here i want to send the data to another fragment ...??? 



} 
+0

呼叫碼)方法... –

+0

哪個代碼拋出情人 – Manish

+0

共享偏好應該經由單獨的對象進行訪問。如果您每次創建新對象,則不會從共享首選項獲取數據。 –

回答

0

共享偏好的一點是,可以從任何地方訪問它,因此在其他片段中只需獲取所需的數據。

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); 
prefs.getString("CheckDate",""); 

如果你的問題是如何從一個片段發送數據到另一個我建議創建一個片段和傳遞參數時存在使用newInstance方法。

public static GenericAreaFragment newInstance(String color, String title, String areaId, boolean isArea) { 
    GenericAreaFragment frag = new GenericAreaFragment(); 
    Bundle args = new Bundle(); 
    args.putString(COLOR, color); 
    args.putString(TITLE, title); 
    args.putString(AREA_ID, areaId); 
    args.putBoolean(ISAREA, isArea); 
    frag.setArguments(args); 
    return frag; 
} 

然後你就可以用得到的參數:

getArguments().getBoolean(ISAREA); // or getString, etc 

的多個解釋是Android文檔在如何通過活動和交流的片段一起。在的onResume(

http://developer.android.com/intl/es/reference/android/app/Fragment.html