sharedPreferences
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | 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知识) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探