java - Android中如何将字符串从Fragment传输到Activity

标签 java android android-fragments android-activity sharedpreferences

我正在尝试完成将字符串值从 fragment 传输到下面的 Activity 。传输的结果说传输到activity时该值是空的。如果您需要更多信息,请告诉我。

fragment :

//put selected chapter title in memory

String selectedChapter = chapters[position];

SharedPreferences pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putString("selectedChapter", selectedChapter);
edt.commit();

//launch activity
Intent intent = new Intent(getActivity(), ChapterDetailActivity.class);
startActivity(intent);

Activity :

   //retrieve selected chapter filename from previous view

    SharedPreferences pref = ChapterDetailActivity.this.getPreferences(0);
    String filename = pref.getString("selectedChapter", "empty");

    Log.e("File: ", filename);

最佳答案

我喜欢创建一个帮助程序类来保存首选项。这将使用文件名而不是使用上下文来访问它们。这意味着您的所有首选项都存储在一个位置,并且您可以创建常量来保存 key 。

当传递像“selectedChapter”这样的字符串文字时,编译器无法检查我们是否拼写错误该值。通过创建常量,编译器将能够检查该键是否存在。

public class PreferencesHelper {

    private SharedPreferences prefs;

    private static final String FILE_NAME = "com.yourpackage.yourapp.prefs";

    public static final String KEY_CHAPTER = "chapter";

    public PreferencesHelper(Context context) {
        prefs = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    }


    /**
     * Save the specified value to the shared preferences
     * 
     * @param key
     *            The key of the value you wish to load
     * @param value
     *            The value to store
     */
    public void save(String key, String value) {
        prefs.edit().putString(key, value).commit();
    }


    /**
     * Load the specified value from the shared preferences
     * 
     * @param key
     *            The key of the value you wish to load
     * @param defValue
     *            The default value to be returned if no value is found
     */
    public int loadString(String key, String defValue) {
        return prefs.getString(key);
    }

}

然后,您的 Activity 可以像这样访问它:

PreferencesHelper prefs= new PreferencesHelper(this);

你的 fragment 如下:

PreferencesHelper prefs = new PreferencesHelper(getActivity());

并访问数据:

// Save
prefs.save(PreferencesHelper.KEY_CHAPTER, chapter);

// Load
prefs.load(PreferencesHelper.KEY_CHAPTER, null)  

关于java - Android中如何将字符串从Fragment传输到Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23859666/

相关文章:

java - IntelliJ Jar 错误 : Invalid signature file digest for Manifest main attributes

Java 数组列表错误

java - AndroidAnnotations 不适用于继承类

android - 如何将YouTube播放列表粘贴到ListView-Android?

android - Facebook 登录按钮阻止整个 Android Activity

android - fragment 中的 onCreateOptionsMenu() 不替换 ActionBar 菜单

java - 自动将 Clojure 源代码转换为 Java 源代码的最佳方法

java - EJB 身份验证和授权

android - 如何在 SoapObject 中转换字符串对象

android - "Can' 的处理程序或 runOnUiThread 解决方案 t 在未调用 Looper.prepare() 的线程内创建处理程序“