zoukankan      html  css  js  c++  java
  • sharedPreferences

    sharedpreferences (共享参数):也是保存数据的一种方法,通常用于持久化数据(定期更新保存数据)类似ajax的定时刷新。
    
    示例代码(主要来源于黑马教程)如下:
    
    import java.util.Timer;
    import java.util.TimerTask;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor;
    import android.util.Log;
    import android.view.Menu;
    import android.widget.EditText;
    
    public class MainActivity extends Activity {
    	protected static final String TAG = "MainActivity";
    	private EditText et_title;
    	private EditText et_content;
    	private Timer timer;
    	private TimerTask task;
    	private SharedPreferences sp;
    
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		et_title = (EditText) findViewById(R.id.et_title);
    		et_content = (EditText) findViewById(R.id.et_content);
    
    		//得到系统的参数的保持器,类似于new文件对象,把内容保存在info.xml文件中
    		sp = this.getSharedPreferences("info", MODE_PRIVATE);
    
    		String title = sp.getString("title", "");
    		String content = sp.getString("content", "");
    		et_content.setText(content);
    		et_title.setText(title);
    
    		timer = new Timer();
    		task = new TimerTask() {
    
    			@Override
    			public void run() {
    				Log.i(TAG,"定期保存数据");
    
    				String title = et_title.getText().toString().trim();
    				String content = et_content.getText().toString().trim();
    				//得到参数文件的编辑器.
    				Editor editor = sp.edit(); //类似得到输出流.
    
    				//通过xml文件来存储数据
    				editor.putString("title", title);
    				editor.putString("content", content);
    
    				//editor.putInt("intnumber", 333);
    				//editor.putBoolean("booleanresuklt", false);
    
    				editor.commit();//把数据提交到参数文件里面. 类似数据库的事务(commit,rollback)
    			}
    		};
    		timer.schedule(task, 2000, 5000);//每个5s执行一次任务
    	}
    
    }
    
    总结sharedpreferences的使用方法:
    
      1)通过上下文环境(this)获取参数的保持器--> this.getSharedPreferences("info", MODE_PRIVATE);同时可以设置文件名与模式;
    
      2)通过参数保持器获得参数文件的编辑器--> Editor editor = sp.edit();类似与java中普通文件的输出流,可用于文件写操作
      (支持写各种不同类型的数据editor.putInt();editor.putString();...);
    
      3)最后通过方法 editor.commit();把写好的数据一次性提交到指定的参数文件中(xml文件);
    
      PS:此示例中,除了要学会sharedpreferences的用法外,还要学习或者加深对Timer and TimerTask 的一般用法(java知识)
    

      

  • 相关阅读:
    C#中Dictionary<TKey,TValue>排序方式
    反射之取类中类的属性、变量名称及其值
    程序测试用的IE浏览器第二次无法加载入口程序的问题及其解决方法
    使用Windows Form 制作一个简易资源管理器
    如何查看自制词典的执行效率
    cocos2dx 3.12 eclipse编辑器切换到Android Studio
    Cordova安装使用
    Activity的启动模式
    踩坑集锦——MVC权限验证
    设计模式学习之路——策略模式
  • 原文地址:https://www.cnblogs.com/allenpengyu/p/3662225.html
Copyright © 2011-2022 走看看