首先要搭建litepal框架的环境,可以参考 http://blog.csdn.net/u014535666/article/details/46572155
首先是主程序入口
package cn.zs.lianliankan;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import cn.zs.service.charu;
import cn.zs.service.guanka;
import cn.zs.service.guanyuyouxi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button button1;
private Button button2;
private Button button3;
private Button button4;
public static String dbName="demo.db";//数据库的名字
private static String DATABASE_PATH="/data/data/cn.zs.lianliankan/databases/";
int alpha = 255;
int b = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1=(Button) this.findViewById(R.id.kaishiyouxi);
button2=(Button) this.findViewById(R.id.guanyuyouxi);
button3=(Button) this.findViewById(R.id.tuichuyouxi);
button4=(Button) this.findViewById(R.id.charu);
button1.setOnClickListener(new dakaiclick());
button2.setOnClickListener(new dakaiclick());
button3.setOnClickListener(new dakaiclick());
button4.setOnClickListener(new dakaiclick());
boolean dbExist = checkDataBase();
if(dbExist){
}else{//不存在就把raw里的数据库写入手机
try{
copyDataBase();
}catch(IOException e){
throw new Error("Error copying database");
}
}
new Thread(new Runnable() {
public void run() {
initApp(); //初始化程序
while (b < 2) {
try {
if (b == 0) {
Thread.sleep(20);
b = 1;
} else {
Thread.sleep(50);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
public class dakaiclick implements OnClickListener{
@Override
public void onClick(View v) {
Intent intent1=new Intent();
switch (v.getId()) {
case R.id.kaishiyouxi:
intent1.setClass(MainActivity.this, guanka.class);
startActivity(intent1);
break;
case R.id.guanyuyouxi:
intent1.setClass(MainActivity.this, guanyuyouxi.class);
startActivity(intent1);
break;
case R.id.tuichuyouxi:
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
break;
case R.id.charu:
intent1.setClass(MainActivity.this, charu.class);
startActivity(intent1);
break;
}
}
}
/**
* 判断数据库是否存在,主要将数据库随同apk一起打包
* @return false or true
*/
public boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String databaseFilename = DATABASE_PATH+dbName;
checkDB =SQLiteDatabase.openDatabase(databaseFilename, null,
SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
}
if(checkDB!=null){
checkDB.close();
}
return checkDB !=null?true:false;
}
/**
* 复制数据库到手机指定文件夹下
* @throws IOException
*/
public void copyDataBase() throws IOException{
String databaseFilenames =DATABASE_PATH+dbName;
File dir = new File(DATABASE_PATH);
if(!dir.exists())//判断文件夹是否存在,不存在就新建一个
dir.mkdir();
FileOutputStream os = null;
try{
os = new FileOutputStream(databaseFilenames);//得到数据库文件的写入流
}catch(FileNotFoundException e){
e.printStackTrace();
}
InputStream is = MainActivity.this.getResources().openRawResource(R.raw.demo);//得到数据库文件的数据流
byte[] buffer = new byte[8192];
int count = 0;
try{
while((count=is.read(buffer))>0){
os.write(buffer, 0, count);
os.flush();
}
}catch(IOException e){
}
try{
is.close();
os.close();
}catch(IOException e){
e.printStackTrace();
}
}
/**
* 初始化,这里是起始页的没有用
*/
public void initApp(){
}
}
紧接着就是游戏的代码
package cn.zs.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;
import cn.zs.adapter.myadapter;
import cn.zs.domin.Charuchengyu;
import cn.zs.domin.ChengYu;
import cn.zs.lianliankan.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class youxi extends Activity {
private int i=0;
private char [] a={};
private SQLiteDatabase db;
Charuchengyu charu;
private String abs;
private String a1;
private String a2;
private int randInt;
ArrayList< String> data;
GridView gridView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
db = Connector.getDatabase();
//生成表
List<ChengYu> cylist = DataSupport.select("szchengyu").
where("guanka = ?", "1").find(ChengYu.class);
// Toast.makeText(youxi.this, cylist.size()+"", 0).show();
StringBuffer array = new StringBuffer();
for(ChengYu c:cylist){
array.append(c.getSzchengyu());//这个很重要,不写get方法会得到地址
}
a=array.toString().toCharArray();
// Toast.makeText(getApplicationContext(), array.toString(), 1).show();
/*取出数据然后再数据库中查询*/
gridView=(GridView) findViewById(R.id.gridview);
data=new ArrayList<String>();
rand rr=new rand();
rr.r();
// for(int h=0;h<40;h++){
// Log.i("xxx", bubian[h]+"");
// }
DataSupport.deleteAll(Charuchengyu.class); //没有执行到这个方法是不会删除数据库的
}
public class rand{
public void r(){
Random rand = new Random();
boolean[] bool = new boolean[40];
final int []bubian=new int[40];
for(int j = 0; j < 40 ; j++) {//随机生成不重复的40以内的40个数
do {
randInt = rand.nextInt(40);
}while(bool[randInt]);
bool[randInt] = true;
/* HashMap<String, Object> item=new HashMap<String, Object>();这是原来使用simpleadapter所用的绑定条目的方法
item.put("name",a[randInt]);*/
data.add(""+a[randInt]);
bubian[j]=randInt;
// Log.i("sss", randInt+"");
}
// for(int h=0;h<40;h++){
// Log.i("ddd", bubian[h]+"");//判断int数组
// SimpleAdapter simpleAdapter=new SimpleAdapter(getApplicationContext(), data, R.layout.youxi, new String[]{"name"},new int[]{R.id.textview});
final myadapter ada=new myadapter(getApplicationContext(), data);
//适配器类
gridView.setAdapter(ada);
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
/*for(int h=0;h<40;h++){
Log.i("xxx", bubian[h]+"");
}*/
i++;
charu=new Charuchengyu();
charu.setZiduan1(a[bubian[arg2]]);//gridview的顺序
charu.save();
ada.Selection(arg2);//界面上的字
ada.notifyDataSetChanged();// 刷新界面
//Toast.makeText(getApplicationContext(), "你选择了" + arg2 + " 号图片", 0).show();
Toast.makeText(getApplicationContext(),a[bubian[arg2]]+"", 0).show();
if(i%4==0){//查询
List<Charuchengyu> nf = DataSupport.select("ziduan1")
.find(Charuchengyu.class);
StringBuffer sss = new StringBuffer();
for(Charuchengyu s:nf){
sss.append(s.getZiduan1());
}
abs=sss.toString();//注意顺序,主线程跑的快
//Toast.makeText(getApplicationContext(), abs, 1).show();
Log.i("abs", abs);
new Thread(new Runnable() {//开线程
@Override
public void run() {
}
}).start();//启动线程
//注意顺序,主线程跑的快,子线程慢
String x="\"";
Log.i("x", x);
String y="\"";
Log.i("y", y);
Log.i("xy", x+abs+y);
Log.i("xxyy", "\""+x+abs+y+"\"");
Log.i("xxyy", "\""+abs+"\"");
//查询
// "\""+abs+"\""
List<ChengYu> cc = DataSupport.select("jieshi","chuchu").
where("szchengyu = ?", abs).find(ChengYu.class);
StringBuffer array1 = new StringBuffer();//不定长字符串
StringBuffer array2 = new StringBuffer();
for(ChengYu c:cc){
array1.append(c.getJieshi());//这个很重要,不写get方法会得到地址
array2.append(c.getChuchu());
}
a1=array1.toString();
Log.i("1", a1);
a2=array2.toString();
Log.i("2", a2);
if(a1!=a2){//实现能查询到结果,并显示到对话框
//新建对话框
new AlertDialog.Builder(youxi.this).setMessage("解释:"+a1+"\n"+"出处:"+a2+"").setPositiveButton(
"确定",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}
).show();
}
//删除数据库的内容
DataSupport.deleteAll(Charuchengyu.class);
}
}
});
}
}
}
下面介绍适配器类
package cn.zs.adapter;
import java.util.ArrayList;
import cn.zs.lianliankan.R;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class myadapter extends BaseAdapter {
private LayoutInflater inflater;
private int selectedPosition= -1;//设为-1表示任何textview都未选中
private ArrayList<String> data=new ArrayList<String>();
public myadapter(Context context,ArrayList<String> data) {
inflater = LayoutInflater.from(context);
this.data = data;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public void Selection(int position) {
selectedPosition = position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.youxi, null);
holder.textview = (TextView) convertView
.findViewById(R.id.textview);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
if (( data.get(position)).length() > 0) {
holder.textview.setText(data.get(position));
}
if(selectedPosition==position){
holder.textview.setBackgroundResource(R.drawable.guohou);//实现点击变色
} else {
holder.textview.setBackgroundResource(R.drawable.sanguosss);
}
return convertView;
}
public class ViewHolder {
public TextView textview;
}
}
界面就是用gridview生成的,到这里成语连连看就完成了