zoukankan      html  css  js  c++  java
  • Android中利用SharedPreferences保存信息

    package com.example.sharepreferen;
    
    import android.content.Context;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor;
    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    public class MainActivity extends ActionBarActivity implements OnClickListener{
    	
    	private Button btnSave;
    	private EditText etContent;
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		
    		btnSave = (Button)findViewById(R.id.btn_save);
    		etContent = (EditText)findViewById(R.id.et_content);
    		
    		//得到SharedPreferences取值
    		SharedPreferences preferences = this.getSharedPreferences("config", Context.MODE_PRIVATE);
    		String content = preferences.getString("content", "");
    		if (!content.trim().equals("")) {
    			etContent.setText(content);
    		}
    		btnSave.setOnClickListener(this);
    	}
    
    	@Override
    	public void onClick(View v) {
    		switch (v.getId()) {
    		case R.id.btn_save:
    			save(etContent.getText().toString());
    			break;
    		default:
    			break;
    		}
    		
    	}
    	
    	public void save(String content) {
    		//获得SharedPreferences 并进行编辑
    		SharedPreferences preferences = this.getSharedPreferences("config", Context.MODE_PRIVATE);
    		Editor editor = preferences.edit();
    		editor.putString("content", content);
    		//记住一定要提交
    		editor.commit();
    		Toast.makeText(this, "保存成功", 0).show();
    	}
    
    
    }
    

      

    手机中的一些设置信息都是保存在其中的。

  • 相关阅读:
    python生成试题库和界面 (python generate test database and layout)
    python生成数据库(python generate database)
    Go语言基础之流程控制
    Go语言基础之运算符
    Go语言基础之变量和常量
    VS Code配置Go语言开发环境
    Linux安装教程|详细
    安装Go语言及搭建Go语言开发环境
    Go语言
    Django2.0路由匹配path的用法
  • 原文地址:https://www.cnblogs.com/E-star/p/3855115.html
Copyright © 2011-2022 走看看