当前位置: 代码迷 >> Android >> 逛戏中简单数据存储
  详细解决方案

逛戏中简单数据存储

热度:47   发布时间:2016-04-27 22:04:09.0
游戏中简单数据存储

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

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);    }}

 

  相关解决方案