一.基础知识:

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开发学习07】存储简单数据的利器--Preferences_第1张图片


【Android开发学习07】存储简单数据的利器--Preferences_第2张图片







更多相关文章

  1. android 各版本发布时间
  2. Android休眠设置时间设置和实现永不锁屏
  3. 手机玩转局域网利器dsploit(csploit)
  4. Android基本组件之文本框与编辑框组件(自用)
  5. Android学习07-----事件处理(3)监听日期与时间的改变_焦点事件_
  6. Android的隐私保护利器
  7. 【转】Android内核开发:如何统计系统的启动时间
  8. 为android的HttpClient添加请求超时时间
  9. Android中的网络时间同步 !!!!!!!!

随机推荐

  1. android系统属性读写操作SystemPropertie
  2. 【JAVA】给大家推荐一道有意思的java测试
  3. ButterKnife--View注入框架
  4. Android添加一个新的按键Key
  5. android 网络定位失败 location为null的
  6. Android简单笔记本解析
  7. 反编译Android(安卓)apk文件
  8. Gradle build 报错:Received status code
  9. 如何编译Android内核
  10. android界面无标题和全屏效果实现方式