如何使用SharedPreference保存和显示字符串?

时间:2015-07-07 17:22:10

标签: android sharedpreferences

我有以下代码,但应用程序在打开之前关闭。 我有一个EditText,一个Button和一个TextView。 单击Button应将String从EditText保存到SharedPreference,SharedPreference String应显示在TextView中。我在这里做错了什么。

package com.jainchiranjeev.arduinoremote.newcomponents;

import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

    EditText edittext;
    Button confirm;
    TextView text;

    public static final String Name = "MyPrefs";
    SharedPreferences.Editor editor = getSharedPreferences(Name, MODE_WORLD_WRITEABLE).edit();

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

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor.putString("name", String.valueOf(edittext.getText()));
                editor.commit();
            }
        });

        SharedPreferences prefs = getSharedPreferences(Name, MODE_WORLD_READABLE);
        String restoredText = prefs.getString("name","Your name appears here");
        text.setText(restoredText);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

2 个答案:

答案 0 :(得分:1)

获取onCreateMethod中的共享首选项,并且不要将编辑器初始化为类的字段。

SharedPreferences.Editor editor = context.getSharedPreferences(
            PREFERENCES_NAME, Context.MODE_MULTI_PROCESS | Context.MODE_PRIVATE).edit();
    editor.putString(setting, value);
    editor.apply();

也参加这次训练 http://developer.android.com/training/basics/data-storage/shared-preferences.html

答案 1 :(得分:1)

初始化类后初始化您的prefs。你需要上下文。另外,对编辑器和编写器使用相同的prefs:

SharedPreferences prefs = getSharedPreferences(Name, Context.MODE_PRIVATE);
//to write:
prefs.edit().putString("key", "value_to_save").apply();
//to read
String read = prefs.getString("key", "value_default");