存储简单数据——Preferences

一.Preferences简介

      1.Preferences是一种轻量级的数据存储机制,可存储一些简单的数据,例如:boolean,int,float,long,string等数据。以键值对的形式存储在应用程序的Preferences目录中,该目录位于(data\data\包名\shared_prefs\)中。

     2.游戏中的得分,应用程序记录的上次登录时间等,都可使用Preferences。


二.实现一个显示应用程序上次登录时间的例子

1.main.xml文件

<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="25dip" />

</LinearLayout>
</span>

2.MainActivity.java类

<span style="font-size:18px;">package com.example.preferences;

import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView tv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 返回一个SharedPreferences实例,第一个参数是SharedPreferences的名字,第二个参数是使用默认的操作
		SharedPreferences sp = this.getSharedPreferences("sharPre",
				Context.MODE_PRIVATE);
		String lastLogin = sp.getString("ll", null); // 从SharedPreferences中读取上次访问时间
		if (lastLogin == null) {
			lastLogin = "欢迎您,您是第一次访问本Preferences";
		} else {
			lastLogin = "欢迎回来,您上次于" + lastLogin + "登录";
		}
		SharedPreferences.Editor editor = sp.edit(); // 向SharedPreferences中写本次访问时间
		editor.putString("ll", new Date().toLocaleString()); // 向editor中放入现在的时间
		editor.commit(); // 提交 editor
		tv = (TextView) this.findViewById(R.id.TextView01);
		tv.setText(lastLogin);
	}
}
</span>

显示效果:

1.程序首次运行效果



2.程序非首次运行效果



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

走路诗人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值