您的位置:首页 > 移动开发 > Android开发

Android学习笔记(10)-开始做一个数独游戏[中]

2008-02-27 13:30 316 查看
继续,今天讨论的是记录文件的读写。因为原来在Brew平台上实现的数独将题库是一个二进制文件,所以在Android就直接拿那个文件来用了。

计划实现两个函数,先是LoadTiList(),加载题库,先装题库文件放在资源里,然后从资源里加载它作为一个DataInputStream即可。代码也没几行,如下:


public static boolean LoadTiList(MainActivity me)




...{


DataInputStream in = null;


try




...{


in = new DataInputStream(me.getResources().openRawResource(R.raw.ti));




byte[] bufC4=new byte[4];


byte[] bufC81=new byte[81];




//总个数


in.read(bufC4,0,4);


int len=((int)bufC4[3]<<24)+((int)bufC4[2]<<16)+((int)bufC4[1]<<8)+(int)bufC4[0];




for(int i=0;i<len;i++)




...{


Question ti = new Question();




//代码


in.read(bufC4,0,4);


ti.code=(long) (((long)bufC4[3]<<24)+((long)bufC4[2]<<16)+((long)bufC4[1]<<8)+(long)bufC4[0]);


//时间


in.read(bufC4,0,4);


SharedPreferences sp = me.getPreferences(Context.MODE_WORLD_READABLE);


ti.time=sp.getLong(Long.toString(ti.code), 0);


//数据


in.read(bufC81,0,81);


for(int j=0;j<81;j++)ti.data[j]=bufC81[j];


me.tiList.add(ti);


}


in.close();


}




catch(Exception ex)...{


return false;


}




finally...{




try...{in.close();}catch(Exception e)...{}


}


return true;


}

这里最麻烦的是因为java里没有unsigned类型,所以会溢出,比较郁闷,这个没有解决,只能是生成题库文件里注意一下了,不能与brew平台共用那个题库文件了。

二是保存记录,在brew平台我直接用一个文件搞定,读写它,但是android不能这样了,因为ti.dat是从资源中加载的,所以只能是静态的,不可修改,那记录只能放入preferences中了,代码如下:


public static boolean SaveTiList(MainActivity me)




...{


try




...{


SharedPreferences sp=me.getPreferences(Context.MODE_WORLD_WRITEABLE);


Question ti = me.gridView.ti;


sp.edit().putLong(Long.toString(ti.code),ti.time);


sp.edit().commit();




}




catch(Exception ex)...{


return false;


}


return true;


}

SharePreferences可以按key-value来保存记录,所以key用题目的code,则value就是解它所用的时间了。

Android不能直接访问app目录下的文件,所以不能够象brew那样将数据文件放在程序目录下供它读写,而在
Activity中提供的两个函数 openFileOutput和openFileInput,虽可用来读写文件,但是总是不太方便。

另外,用SQLite其实也不方便,因为手机中弄这些东西,事实上用处不大。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐