图片和对应文本保存在assets中,项目一启动写到sqlite中,可以讲初始化数据写在util中,启动时候判断下,如果加载成功过了,第二次可以不用加载,这里为了方便写在一起
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.Buffer;
import java.util.Currency;
import java.util.Random;
import com.kane.crazyneedkane.utils.Globals;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
@SuppressLint("UseValueOf")
public class SqliteConnection extends SQLiteOpenHelper{
private Context ctx;
public SqliteConnection(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
public SqliteConnection(Context context
) {
super(context, Globals.DBNAME, null, Globals.DB_VERSION);
this.ctx=context;
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql="CREATE TABLE "+Globals.TBNAME+"(" +
"id integer primary key autoincrement," +
"image_name text," +
"answer text," +
"answer_type text," +
"select_text text" +
")";
db.execSQL(sql);
initData(db);
}
public void initData(SQLiteDatabase conn) {
//读取assets文本,并向数据库中插入数据
AssetManager manager=ctx.getAssets();
Log.i("--------", "开始读取文件");
try {
//读取所有文件夹下的所有文件名
String[] allFiles=manager.list("question_answer_text");
Log.i("---------","开始添加数据到数据库");
for (int i = 0; i < allFiles.length; i++) {
InputStream is=manager.open("question_answer_text/"+allFiles[i]);
BufferedReader reader=new BufferedReader(new InputStreamReader(is,"GBK"));
//逐行读入
String line=null;
int index=0;
String answer=null;
String img_name=null;
String answerType=null;
String selectText=null;
while ((line=reader.readLine())!=null) {
if (index==0) {
//第一行是答案
answer=line;
}
else if(index==1){
answerType=line;
}
else {
selectText=line;
}
index++;
}
//文件的类型可能不同,还加入疯狂猜歌部分歌曲,如果是歌曲,就应该放音乐
if (answerType.equals("歌曲")) {
img_name=allFiles[i].substring(0,allFiles[i].lastIndexOf("."))+".mp3";
}
else {
img_name=allFiles[i].substring(0,allFiles[i].lastIndexOf("."))+".png";
}
//因为偷懒没写selecttext,我们要随机评出选择的文字
if(selectText==null){
//选择StringBuffer。虽然builder速度最快,在单线程下安全,多线程的话考虑buffer,第一次初始化数据在子线程中
StringBuffer buffer=new StringBuffer();
buffer.append(answer);
//循环随机生成文字
while (buffer.length()<24) {
//随机生成一个汉字
buffer.append(createStr());
}
selectText=buffer.toString();
}
insertData(conn,answer,img_name, answerType,selectText);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@SuppressLint("UseValueOf")
/**
* 随机生成一个汉字
* @return
* @throws UnsupportedEncodingException
*/
public String createStr() throws UnsupportedEncodingException {
String str = null;
int hightPos, lowPos; // 定义高低位
Random random = new Random();
hightPos = (176 + Math.abs(random.nextInt(39)));// 获取高位值
lowPos = (161 + Math.abs(random.nextInt(93)));// 获取低位值
byte[] b = new byte[2];
b[0] = (new Integer(hightPos).byteValue());
b[1] = (new Integer(lowPos).byteValue());
str = new String(b, "GBk");// 转成中文
return str;
}
public void insertData(SQLiteDatabase conn,String answer,String img_name,String answerType,String selectText) {
String sql="INSERT INTO "+Globals.TBNAME+"(image_name,answer,answer_type,select_text)" +
" VALUES(?,?,?,?)";
conn.execSQL(sql, new Object[]{img_name,answer,answerType,selectText});
}
/**
* 进行版本比较判断是否更新
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql="DROP TABLE "+Globals.TBNAME;
db.execSQL(sql);
sql="CREATE TABLE "+Globals.TBNAME+"(" +
"id integer primary key autoincrement," +
"image_path text," +
"answer text," +
"answer_type text," +
"select_text text" +
")";
db.execSQL(sql);
}
}
对数据的操作
package com.kane.crazyneedkane.utils;
import java.util.Map;
import java.util.Random;
import com.kane.crazyneedkane.vo.StageData;
import android.database.Cursor;
public class CrazyDAOUtils {
/**
* id自增是从1开始的,我们可以直接拿id做题号
* @return
*/
public static int getCount() {
Cursor c=Globals.dbc.getReadableDatabase().rawQuery("SELECT COUNT(*) FROM "+
Globals.TBNAME,null);
c.moveToFirst();
return c.getInt(0);
}
public static void deleteAll() {
String sql="DELETE FROM "+Globals.TBNAME;
Globals.dbc.getWritableDatabase().execSQL(sql);
}
public static StageData findStageById (int id) {
String sql="SELECT * FROM "+Globals.TBNAME+" WHERE id=?";
Cursor c=Globals.dbc.getReadableDatabase().rawQuery(sql,new String[] {id+""});
c.moveToFirst();
StageData data=new StageData();
data.setId(id);
data.setImg_name(c.getString(1));
data.setAnswer(c.getString(2));
data.setAnswer_type(c.getString(3));
data.setSelect_text(c.getString(4));
return data;
}
/**
* 打乱可选文本
* @param input
*/
public static String shuffText(String input) {
StringBuffer buffer=new StringBuffer();
StringBuffer result=new StringBuffer();
buffer.append(input);
//循环从文本中随机取值
Random r=new Random();
while (result.length()<24) {
int value=r.nextInt(buffer.length());
//取得字加入新的buffer中
result.append(buffer.charAt(value));
//同时对原来的buffer进行删除
buffer.deleteCharAt(value);
}
return result.toString();
}
}
图片工具类,bitmap切图片(不是所猜的图片)
package com.kane.crazyneedkane.utils;
import java.io.IOException;
import com.kane.crazyneedkane.R;
import android.app.Activity;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
public class ImageUitls {
public static Bitmap getHeader_bar() {
return header_bar;
}
public static void setHeader_bar(Bitmap header_bar) {
ImageUitls.header_bar = header_bar;
}
public static Bitmap getTop_start() {
return top_start;
}
public static void setTop_start(Bitmap top_start) {
ImageUitls.top_start = top_start;
}
public static Bitmap getAnswer_type() {
return answer_type;
}
public static void setAnswer_type(Bitmap answer_type) {
ImageUitls.answer_type = answer_type;
}
public static Bitmap getCoin_bg() {
return coin_bg;
}
public static void setCoin_bg(Bitmap coin_bg) {
ImageUitls.coin_bg = coin_bg;
}
public static Bitmap[] getDeleteErrorText() {
return deleteErrorText;
}
public static void setDeleteErrorText(Bitmap[] deleteErrorText) {
ImageUitls.deleteErrorText = deleteErrorText;
}
public static Bitmap[] getProptTrueText() {
return proptTrueText;
}
public static void setProptTrueText(Bitmap[] proptTrueText) {
ImageUitls.proptTrueText = proptTrueText;
}
public static Bitmap[] getBackBtn() {
return backBtn;
}
public static void setBackBtn(Bitmap[] backBtn) {
ImageUitls.backBtn = backBtn;
}
public static Bitmap[] getNextBtn() {
return nextBtn;
}
public static void setNextBtn(Bitmap[] nextBtn) {
ImageUitls.nextBtn = nextBtn;
}
public static Bitmap uiMain;
public static Bitmap header_bar;
public static Bitmap top_start;
public static Bitmap answer_type;
public static Bitmap coin_bg;
public static Bitmap answerBg;
private static Bitmap select_textBg;
public static Bitmap getSelect_textBg() {
return select_textBg;
}
public static void setSelect_textBg(Bitmap select_textBg) {
ImageUitls.select_textBg = select_textBg;
}
public static Bitmap getAnswerChangeBg() {
return answerChangeBg;
}
public static void setAnswerChangeBg(Bitmap answerChangeBg) {
ImageUitls.answerChangeBg = answerChangeBg;
}
public static Bitmap getAnswerBg() {
return answerBg;
}
public static void setAnswerBg(Bitmap answerBg) {
ImageUitls.answerBg = answerBg;
}
public static Bitmap[] deleteErrorText = new Bitmap[2];
public static Bitmap[] proptTrueText = new Bitmap[2];
public static Bitmap[] backBtn = new Bitmap[2];
public static Bitmap[] nextBtn = new Bitmap[2];
// 规范过大小的图片
private static Bitmap answerChangeBg;
@SuppressWarnings("static-access")
public static void init(Resources res, AssetManager manager)
throws IOException {
// 也可以从drawable读取,总体照片比较大,一般放在assets
// uiMain=new
// BitmapFactory().decodeResource(Activity.getResources,R.drawable.ui_main);
uiMain = new BitmapFactory().decodeStream(manager.open("ui_main.png"));
// 坐标应该是美工提供
header_bar = splitBitmap(uiMain, 975, 893, 640, 96);
// 题数背景
top_start = splitBitmap(uiMain, 1020, 1939, 108, 108);
// 题目类型的背景
answer_type = splitBitmap(uiMain, 1675, 787, 310, 58);
coin_bg = splitBitmap(uiMain, 1602, 219, 44, 33);
// 选择文字背景
select_textBg = splitBitmap(uiMain, 975, 338, 74, 76);
// 去掉错误答案
deleteErrorText[0] = splitBitmap(uiMain, 1503, 990, 92, 123);
deleteErrorText[1] = splitBitmap(uiMain, 1948, 926, 92, 123);
// 提示文字
proptTrueText[0] = splitBitmap(uiMain, 1579, 1371, 92, 123);
proptTrueText[1] = splitBitmap(uiMain, 1579, 1247, 92, 123);
// 返回按钮
backBtn[0] = splitBitmap(uiMain, 98, 1972, 96, 72);
backBtn[1] = splitBitmap(uiMain, 1, 1972, 96, 72);
// 截取“下一题”
nextBtn[0] = splitBitmap(uiMain, 975, 131, 308, 129);
nextBtn[1] = splitBitmap(uiMain, 975, 1, 308, 129);
// 答案背景
answerBg = splitBitmap(uiMain, 1602, 155, 66, 63);
//缩放
float a=Globals.SCREEN_WIDTH/8.0f-4;
answerChangeBg=changeBitmapSize(answerBg , a, a);
}
/**
* 截取图片中某一部分,生成新图片的方法
*
* @param src
* 源图片
* @param startX
* 截取的左上角点的横坐标
* @param startY
* 纵坐标
* @param width
* 截取后的图片的宽度
* @param height
* 高度
* @return
*/
public static Bitmap splitBitmap(Bitmap main, int x, int y, int width,
int height) {
return Bitmap.createBitmap(main, x, y, width, height);
}
/**
*
* @param src
* @param toWidth缩放后的宽度
* @param toHeight缩放后的高度
* @return
*/
public static Bitmap changeBitmapSize(Bitmap src,float toWidth,float toHeight) {
Matrix m=new Matrix();
m.postScale(toWidth/src.getWidth(), toHeight/src.getHeight());
Bitmap result=Bitmap.createBitmap(src,0,0,src.getWidth(),src.getHeight(),m,false);
return result;
}
}
音频工具类,按键音,疯狂猜歌准备歌曲
到睡觉点了,明天补充