android应用面试宝典;公共基类管理公共头尾页;公共activity的参数问题;SQLite存数据;前提先将txt数据保存在项目的assets文件下;

SQLite连接操作

package com.kane.interviewcollection.dbc;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class SqliteConnection extends SQLiteOpenHelper {
private static final int DBVERSION=1;
private static final String DBNAME="question.db";

//简化构造方法,哪个类需要调用数据库,就传参进来
public SqliteConnection(Context ctx){
super(ctx,DBNAME, null,DBVERSION);
}
public SqliteConnection(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}


@Override
public void onCreate(SQLiteDatabase db) {
//安装时只建立一次,以后不执行了,主键id默认自增长,当然也可以写autoIncrement
String sql="CREATE TABLE question("+
"id  integer  primary key," +
"question text not null," +
"answer text not null" +
")";
db.execSQL(sql);
}

/**
* 当检测与前一次创建数据库版本不一样时,先删除表再创建新表才回进来
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS question");
//先删除旧表,再创建新表,必须版本号比以前高
onCreate(db);
}


}

SQLite的CRUD操作

package com.kane.interviewcollection.util;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import android.database.Cursor;


public class QuesstionDAOUtils {
public static void insert(Map<String,Object> map) {
String sql="INSERT INTO question(question,answer) VALUES(?,?>)";
Globals.dbc.getWritableDatabase().execSQL(sql,new Object[]{
map.get("question"),map.get("answer")
});
}


public static void deleteAll() {
String sql="DELETE FROM question";
Globals.dbc.getWritableDatabase().execSQL(sql);
}

public static List<Map<String,Object>> listData() {
List<Map<String,Object>> allValues=new ArrayList<Map<String,Object>>();
String sql="SELECT id,question,answer FROM question";
Cursor c=Globals.dbc.getReadableDatabase().rawQuery(sql, null);
//手动知道查询结果的初始位置
c.moveToFirst();
//没到最后就继续查询
while (!c.isAfterLast()) {
Map<String,Object> map=new HashMap<String, Object>();
map.put("id",c.getInt(0));
map.put("question",c.getInt(0)+"、"+c.getString(1));
map.put("answer", c.getString(2));
allValues.add(map);
//指向下一个
c.moveToNext();
}
c.close();//关闭cursor
return allValues;
}

public static List<Map<String,Object>> listDataPage (int pageNo,int pageSize,String keyword) {
List<Map<String,Object>> allValues=new ArrayList<Map<String,Object>>();

String sql = "SELECT id,question,answer FROM question WHERE question LIKE ? LIMIT ?,?";
Cursor c = Globals.dbc.getReadableDatabase().rawQuery(
sql,
new String[] { "%" + keyword + "%",
(pageNo - 1) * pageSize + "", String.valueOf(pageSize) });
c.moveToFirst();
while (!c.isAfterLast()) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", c.getInt(0));
map.put("question", c.getInt(0) + "、" + c.getString(1));
map.put("answer", c.getString(2));
allValues.add(map);


c.moveToNext();
}
c.close();
return allValues;

}
public static int getAllCount(String keyword) {
String sql="SELECT COUNT(*) FROM question WHERE question LIKE ?";
Cursor c=Globals.dbc.getReadableDatabase().rawQuery(sql,
new String[]{"%"+keyword+"%"} );
c.moveToFirst();
int count =c.getInt(0);
c.close();
return count;

}
}

公共初始类

package com.kane.interviewcollection.util;


import com.kane.interviewcollection.dbc.SqliteConnection;


import android.app.Activity;


public class Globals {
public static int SCREEN_WIDTH;
public static int SCERRN_HEIGHT;

public static SqliteConnection dbc;

public static void init(Activity a){
dbc=new SqliteConnection(a);//对应需要的activity类
SCERRN_HEIGHT=a.getWindowManager().getDefaultDisplay().getHeight();
SCREEN_WIDTH=a.getWindowManager().getDefaultDisplay().getWidth();
}
}

CoverActivity加载全局类(加载dbc)

package com.kane.interviewcollection;






import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;


import com.kane.interviewcollection.util.Globals;
import com.kane.interviewcollection.util.QuesstionDAOUtils;


import android.os.Bundle;
import android.R.bool;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;




public class CoverActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Globals.init(this);//只用初始化一次,界面都一样大小
setContentView(R.layout.activity_cover);
Thread thread=new Thread(){
    public void run(){
    try {
    //从sharedpreferences中读取 一个标志位,判断是否读取过题库数据,已经读过了,就加延时,没读过就读取数据
    SharedPreferences s=getSharedPreferences("quesstion_flag",MODE_PRIVATE);//只有自己的包私有调用
    boolean saveFlag=s.getBoolean("flag", false);//默认没保存过数据
    if (saveFlag) {
//已经写过数据了,睡1.5秒
    sleep(1500);
   
}
    else {
    //之前没保存过数据,或没保存好(打开一下就强关程序),需要重新加载数据
    //先删除
    QuesstionDAOUtils.deleteAll();
    //读取数据
    InputStream is=getAssets().open("quesstion.txt");
    BufferedReader reader=new BufferedReader(
    new InputStreamReader(is,"GBK"));//InputStreamReader转码
String line=null;//一行数据
StringBuilder question=new StringBuilder();//builder更适合多线程,buffer适合单线程
StringBuilder answer=new StringBuilder();
//标识当前读入的是问题还是答案
boolean questionFlag=false;
while ((line=reader.readLine())!=null) {
//判断读入什么,在txt中标示了QUESTION_START_FLAG后面跟的是问题
if ("QUESTION_START_FLAG".equals(line)) {
//下面读入问题
questionFlag=true;

}
else if("ANSWER_START_FLAG".equals(line)){
//读入答案
questionFlag=false;
}else if ("END_FLAG".equals(line)) {
// 将数据保存到数据库中
// 需要建立一个Map,保存问题与答案
Map<String, Object> map = new HashMap<String, Object>();
map.put("question",
question.substring(0,
question.length() - 2));//忽略最后的换行符‘\r\n‘
map.put("answer", answer.substring(0,
answer.length() - 2));
//添加到数据库
QuesstionDAOUtils.insert(map);


// 将问题和答案的Builder清空,以便保存新的内容.
question = new StringBuilder();
answer = new StringBuilder();
} else {
// 读入的是数据,需要加入到问题或答案中
if (questionFlag) {
question.append(line + "\r\n");
} else {
answer.append(line + "\r\n");
}
}
}
}
    Intent intent=new Intent(CoverActivity.this,MainActivity.class);
    startActivity(intent);
    //这里终结封面的activity,使得不会返回到该界面
    finish();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
   
    }
    };
    thread.start();
}





}

android应用面试宝典;公共基类管理公共头尾页;公共activity的参数问题;SQLite存数据;前提先将txt数据保存在项目的assets文件下;,布布扣,bubuko.com

android应用面试宝典;公共基类管理公共头尾页;公共activity的参数问题;SQLite存数据;前提先将txt数据保存在项目的assets文件下;

上一篇:飞鸽传书(飞秋) android 深入剖析 -- (1.如何获取好友列表)


下一篇:android中ListView的分页加载数据实现