Android共享首选项 - 重置

时间:2015-03-19 00:00:05

标签: android sharedpreferences

我有一个Activity和Placeholder片段。我试图在EditText框中加载一个字符串值,并在按下Save按钮后保存它。但是在我在屏幕之间来回切换之后,应该显示该文本的EditText不会显示它。相反,它显示文本" android.widget.EditText {5282c35c VFED..CL.F ...... 217,2-717,51#7f08005d app:id / nameInfo"。我不知道这是什么意思。任何帮助将不胜感激。要么我如何修复,要么我可以使用什么来保存字符串值。

public class MyInformation extends Activity {

public static SharedPreferences.Editor editor;
public static final String PREFS_NAME = "MyPrefsFile";
public static SharedPreferences settings;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.personal_info_main);

    settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
    editor = settings.edit();

    getFragmentManager().beginTransaction()
            .replace(R.id.container, PlaceholderFragment.newInstance())
            .commit();
}

public static class PlaceholderFragment extends Fragment {

    public static PlaceholderFragment newInstance() {
        Bundle args = new Bundle();
        PlaceholderFragment fragment = new PlaceholderFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_my_information, container, false);

        EditText name = (EditText) rootView.findViewById(R.id.nameInfo);

        name.setText(settings.getString("key_name", null));

        Button save = (Button) rootView.findViewById(R.id.saveButton);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity().getApplicationContext(),
                        "Personal Information Saved",
                        Toast.LENGTH_LONG).show();
                EditText name = (EditText) rootView.findViewById(R.id.nameInfo);
                String nameAsString = name.toString();
                editor.putString("key_name", nameAsString);
                editor.commit();
            }
        });
        return rootView;
    }
}

}

1 个答案:

答案 0 :(得分:0)

更改此行

           String nameAsString = name.toString();

          String nameAsString = name.getText().toString();