游戏中简单数据存储

在游戏开发中,有时要设置持久的简单数据存储。

Preferences主要是使用简单,但是功能不是很强大,一般适合用于保存一些简单的用户设置的参数,是一种轻量级的存储机制。Preferences仅可以用来存储几种简单类型的数据,如:boolean、int、floate、long、或者String。这些数据以键值对的形式存储在应用程序私有的Preferences目录下的xml文件中。

可以使用 SharedPreferences sp=this.getSharedPreferences("feiruo",Context.MODE_PRIVATE);
或者
SharedPreferences sp=PreferencesManager.getDefaultSharedPreferences(Context);
package com.mycompany.myapp;

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.content.*;
import java.util.*;

public class MainActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //获取SharedPreferences引用,存储名为feiruo.xml,读写模式为private
//
SharedPreferences sp=PreferencesManager.getDefaultSharedPreferences(this);
        SharedPreferences sp=this.getSharedPreferences("feiruo",Context.MODE_PRIVATE);
        String lasttime=sp.getString("time",null);
        if(lasttime==null){
            lasttime="你好,欢迎第一次光临";
        }else{
            lasttime="你好,上次登录时间为:"+lasttime;
        }
        SharedPreferences.Editor ed=sp.edit();
        ed.putString("time",new Date().toLocaleString());
        ed.commit();//提交修改;
        TextView tv=(TextView)this.findViewById(R.id.mainTextView);
        tv.setText(lasttime);
    }
}

 

posted @ 2015-11-28 13:21  非若  阅读(990)  评论(0编辑  收藏  举报