如何在 Fragment 中使用 SharedPreferences 保存数据

Posted

技术标签:

【中文标题】如何在 Fragment 中使用 SharedPreferences 保存数据【英文标题】:How to save data by using SharedPreferences in a Fragment 【发布时间】:2018-02-13 13:17:44 【问题描述】:
    我在永久保存数据时遇到问题。应该很简单,我正在将数据发送到另一个 Fragment 并且效果很好,但是,我不知道如何保存数据。 我尝试了一些东西,但我想知道你是否可以帮助我。

在我的代码中,我通过按下按钮将数据发送到另一个片段。

    所以这是代码:

    包 com.example.mskydraw.notetech;

    import android.content.Context;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Gallery;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import java.io.FileOutputStream;
    
    import static android.content.Context.MODE_PRIVATE;
    

/** * 一个简单的 @link Fragment 子类。 */ 公共类 Cofo 扩展 Fragment

final static String SHARED_NAME_STRING="sharedp";
final static String USER_NAME_STRING="user";




public Cofo() 
    // Required empty public constructor


EditText newTxt;
Button newBtn;
SharedPreferences sharedPreferences;
Context c = getActivity();

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) 
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_cofo, container, false);
    // finding my bouton and text on layout
    newTxt = (EditText)view.findViewById(R.id.Txt);
    newBtn = (Button)view.findViewById(R.id.Btn);



    sharedPreferences=this.c.getSharedPreferences(SHARED_NAME_STRING,Context.MODE_PRIVATE);
    String userNameString=sharedPreferences.getString(USER_NAME_STRING, "");

    newTxt.setText(userNameString);

    // whenever I click on the bouton
    newBtn.setOnClickListener(new View.OnClickListener()
        @Override
        public void onClick(View v)


            //This code allows you to jump into another fragment
            // Call the fragment to where I want to jump
            Main_content newmain = new Main_content();

            //Here we are going to learn to how to save data
            String Message = newTxt.getText().toString();
            String file_name = "Hello_file";
            // Create an object output string


            //here we are sending data to another fragment
            //You have declare bundle
            Bundle bundle = new Bundle();
            // You can use bundle.putxx everything such as String...float..
            bundle.putInt("N1",5);
            //calling the fragment I'm going to send the data
            // and I'm going to send data I saved on bundle.
            newmain.setArguments(bundle);
            // The process of declaration fragment
            FragmentManager manager = getFragmentManager();
            // Jumping into main content fragment
            manager.beginTransaction().replace(R.id.fragment,newmain).commit();

            if (newTxt.getText().toString().equals("Hello"))
                Toast.makeText(Cofo.this.getActivity(), "true", Toast.LENGTH_SHORT).show();
            
            else
                Toast.makeText(Cofo.this.getActivity(), "Hi", Toast.LENGTH_SHORT).show();
            

            SharedPreferences.Editor editor=sharedPreferences.edit();



        
    );

    return view;



【问题讨论】:

您可以尝试提供Minimal, Complete, and Verifiable example 吗?这是很多代码;我们不知道什么是相关的。所有大写字母看起来都像是在对我们大喊大叫。 对此我深表歉意。我修改并试图让我的问题更容易理解。我希望它更清楚。 【参考方案1】:

如果您想使用共享首选项而不是通过捆绑发送数据,请使用以下代码:

    String stringToSave = "Save me!";

    // To save data to SP
    SharedPreferences.Editor editor = getContext().getSharedPreferences(SHARED_NAME_STRING, MODE_PRIVATE).edit();
    editor.putString(USER_NAME_STRING, stringToSave);
    editor.apply();

    // To load the data at a later time
    SharedPreferences prefs = getContext().getSharedPreferences(SHARED_NAME_STRING, MODE_PRIVATE);
    String loadedString = prefs.getString(USER_NAME_STRING, null);

此代码设置为使用片段。如果您改用 Activity,请删除 getSharedPreferences() 前面的 getContext()

【讨论】:

我开始理解您的代码,但是,我有几个问题。您在顶部声明了 3 个字符串,这些是我必须用按钮替换的键吗?如果我理解正确? 很抱歉没有使用您的变量,我已经更新了答案中的变量名称。 stringToSave 只是你可以保存的一个例子,你也可以做 editor.putInt("N1",5);就像你对你的捆绑包所做的那样。希望这是有道理的。 亲爱的安德烈亚斯,我很困扰你。我对此感到非常抱歉。但我相信我仍然需要你的帮助。我在我的另一个片段中使用了这个代码,我从包中收到的那个,这就是为什么我使用包发送到另一个片段并且它不起作用的原因。我怎样才能把我的代码发给你,看看我哪里做错了? 完全没问题。你能把代码放到 GitHub 上让我看一下吗? github.com/StackExchange/stack-blog/issues/275 这是链接,这是我的另一个片段,我从之前的片段中接收数据。我尝试了很多方法来使用你的代码,它确实编译但它不保存或任何东西。我希望你能帮我解决这个问题。

以上是关于如何在 Fragment 中使用 SharedPreferences 保存数据的主要内容,如果未能解决你的问题,请参考以下文章

如何在Fragment中使用PreferenceFragment

如何在Fragment中使用PreferenceFragment

如何在 Fragment 中使用 SharedPreferences 保存数据

如何在 Fragment 中使用 Recycler View [重复]

如何在android Fragment中显示日期选择器

如何在 Android 的 Fragment 中使用 setUserVisibleHint