如何通过在片段中使用SharedPreferences来保存数据[英] How to save data by using SharedPreferences in a Fragment

本文是小编为大家收集整理的关于如何通过在片段中使用SharedPreferences来保存数据的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

  1. 我在永久保存数据方面有问题.它应该很简单,我将数据发送到另一个片段,并且可以很好地工作,但是,我不知道如何保存数据.
    我尝试了一些事情,但我想知道您是否可以帮助我.

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

  1. 所以这是代码:

    软件包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扩展了片段{

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;
}

}

推荐答案

如果要使用共享的首选项而不是通过捆绑发送数据,请使用此代码:

    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);

此代码设置为与片段一起使用.如果您使用活动,请在 getSharedPreferences()的前面删除 getContext().

本文地址:https://www.itbaoku.cn/post/2091029.html

问题描述

  1. I'm having a problem with saving data permanently. It should be simple, I'm sending data to another Fragment and it works perfectly, however, I have no idea how to save data.
    I tried something, but I was wondering if you could help me out.

In my code, I'm sending a data to another Fragment by pushing a Button.

  1. So this is the code:

    package 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;
    

/** * A simple {@link Fragment} subclass. */ public class Cofo extends 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;
}

}

推荐答案

If you want to use Shared Preferences instead of sending the data through bundles, use this code:

    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);

This code is setup to work with fragments. If you use an Activity instead, remove getContext() in front of getSharedPreferences().