Android基础(二)数据存储1.SharedPreferences存储

SharedPreferences经常用来储存一些默认欢迎语,用户登录名和密码等简单信息,一般用于存储量小的信息
exampleHelper.java

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by 6lang on 2018/10/6.
 */

public class exampleHelper {
    SharedPreferences sp;
    SharedPreferences.Editor editor;
    Context context;
    public exampleHelper(Context c,String name)
    {
        context=c;
        sp=context.getSharedPreferences(name,0);
        editor=sp.edit();
    }
    public void putValue(String key,String value)
    {
        editor=sp.edit();
        editor.putString(key,value);
        editor.commit();
    }
    public String getValue(String key)
    {
        return sp.getString(key,null);
    }
}

1getSharedPreferences(文件名称,操作模式) .得到SharedPreferences对象,0表示默认模式
2.editor=sp.edit(); 获取一个Edit对象,所有对数据的操作都需要经过Edit
3.editor.commit(); 提交是必须的
MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    public final static String COLUMN_NAME="name";
    public final static String COLUMN_MOBILE="mobile";
    exampleHelper sp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sp=new exampleHelper(this,"contact");
        //设置储存的信息
        sp.putValue(COLUMN_NAME,"Mr Wang");
        sp.putValue(COLUMN_MOBILE,"13223346556");
        String name=sp.getValue(COLUMN_NAME);
        String mobile=sp.getValue(COLUMN_MOBILE);
        TextView tv=new TextView(this);
        tv.setText("NAME:"+name+"\n"+"MOBILE:"+mobile);
        setContentView(tv);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37282683/article/details/82950239
今日推荐