android 数据存储之SharedPerferences

package com.example.phonedemo;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout.LayoutParams;
import android.widget.LinearLayout;

public class SharePreferenceDemo extends Activity {
    private LayoutParams wrap = new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT);
    private LayoutParams match = new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT);

    private LinearLayout layout = null;

    private EditText name = null;
    private EditText school = null;
    private EditText age = null;
    private Button but = null;
    private SharedPreferences sf = null;
    private SharedPreferences.Editor edit = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.sf = super.getSharedPreferences("PhoneDemo", MODE_PRIVATE);
        this.edit = this.sf.edit();
        this.layout = new LinearLayout(this);
        this.layout.setOrientation(LinearLayout.VERTICAL);

        this.name = new EditText(this);
        this.name.setText(getValue("name"));
        this.layout.addView(this.name, wrap);

        this.school = new EditText(this);
        this.school.setText(getValue("school"));
        this.layout.addView(this.school, wrap);

        this.age = new EditText(this);
        this.age.setText(getValue("age"));
        this.layout.addView(this.age, wrap);

        this.but = new Button(this);
        this.but.setText("save");
        this.but.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                System.out.println("name: "
                        + SharePreferenceDemo.this.name.getText().toString());
                SharePreferenceDemo.this.edit.putString("name",
                        SharePreferenceDemo.this.name.getText().toString());
                SharePreferenceDemo.this.edit.putString("school",
                        SharePreferenceDemo.this.school.getText().toString());
                SharePreferenceDemo.this.edit.putString("age",
                        SharePreferenceDemo.this.age.getText().toString());
                SharePreferenceDemo.this.edit.commit();
            }
        });
        this.layout.addView(this.but, wrap);

        super.addContentView(this.layout, match);
    }

    public String getValue(String string) {
        if (string == "name" || string == "school" || string == "age") {
            return sf.getString(string, string);
        }
        return "null";
    }

}
原文地址:https://www.cnblogs.com/waddell/p/3394697.html