【问题标题】:not able to retrieve data from sharedPrference in intra fragment?无法从内部片段中的 sharedPreference 中检索数据?
【发布时间】:2016-04-14 13:29:28
【问题描述】:

发送sharedpreference的数据 这是通讯接口

@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 ...???



}

【问题讨论】:

  • onResume()方法中调用代码...
  • 哪个代码@Exception Lover
  • 共享首选项应该通过单例对象访问。如果您每次都创建新对象,那么您将无法从共享首选项中获取数据。
  • 这段代码 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",""); }

标签: android android-fragments android-sharedpreferences


【解决方案1】:

共享首选项的要点是您可以从任何地方访问它,因此在另一个片段中只需获取您想要的数据。

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 文档中,以及如何通过活动和片段进行通信。

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

【讨论】:

    猜你喜欢
    • 2019-02-20
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多