【Android开发学习07】存储简单数据的利器--Preferences
16lz
2021-01-23
一.基础知识:
Preferences是一种轻量级的数据库存储机制,主要用于记录游戏中的得分,应用程序上次登录的时间等。
二.编程实现:
1. 界面编辑(res\layout\main.xml):
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" ><TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="25dip" android:id="@+id/TextView01" /><!-- 添加TextView --></LinearLayout>
2. 代码编辑( \src\wyf\zcl\MyActivity.java):
package wyf.zcl;import java.util.Date;//引入相关包import android.app.Activity;//引入相关包import android.content.Context;//引入相关包import android.content.SharedPreferences;//引入相关包import android.os.Bundle;//引入相关包import android.widget.TextView;//引入相关包import android.widget.Toast;//引入相关包public class MyActivity extends Activity { /** Called when the activity is first created. */private TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SharedPreferences sp=this.getSharedPreferences("sharePre", Context.MODE_PRIVATE); //返回一个SharedPreferences实例,第一个参数是Preferences名字,第二个参数是使用默认的操作 String lastLogin=sp.getString(//从SharedPreferences中读取上次访问的时间 "ll",//键值 null//默认值 ); if(lastLogin==null){ lastLogin="欢迎您,您是第一次访问本Preferences"; }else{ lastLogin="欢迎回来,您上次于"+lastLogin+"登录"; } //向SharedPreferences中写回本次访问时间 SharedPreferences.Editor editor=sp.edit(); editor.putString("ll", new Date().toLocaleString());//向editor中放入现在的时间 editor.commit();//提交editor tv=(TextView)this.findViewById(R.id.TextView01); tv.setText(lastLogin); }}
3.运行效果:
更多相关文章
- android 各版本发布时间
- Android休眠设置时间设置和实现永不锁屏
- 手机玩转局域网利器dsploit(csploit)
- Android基本组件之文本框与编辑框组件(自用)
- Android学习07-----事件处理(3)监听日期与时间的改变_焦点事件_
- Android的隐私保护利器
- 【转】Android内核开发:如何统计系统的启动时间
- 为android的HttpClient添加请求超时时间
- Android中的网络时间同步 !!!!!!!!