Android 中使用数据库作为存储,并随机发布的Demo。

1. 用SQLiteStudio 3.1.1 建立数据库db文件和建表。

2.在as中,packages视图模式下,项目上,右键点击新建“New Resource Directory” 然后,type选择raw,这样建立raw目录,否则无效,在R.raw.时候没有提示,系统不认。

3.把已经建好的数据库,拷贝到raw目录下。

4. 在主activity的onCreate方法中,调用方法,来创建数据库,如果已经存在,跳过,如果没有新建。

5. 新建一个数据库类,用来管理拷贝。

public class DataBaseUtil {

    private Context context;
    public static String dbName = "divine.db";// 数据库的名字
    private static String DATABASE_PATH;// 数据库在手机里的路径

    public DataBaseUtil(Context context) {
        this.context = context;
        String packageName = context.getPackageName();
        DATABASE_PATH = "/data/data/" + packageName + "/databases/";
    }

    /**
     * 判断数据库是否存在
     *
     * @return false or true
     */
    public boolean checkDataBase() {
        SQLiteDatabase db = null;
        try {
            String databaseFilename = DATABASE_PATH + dbName;
            db = SQLiteDatabase.openDatabase(databaseFilename, null, SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {

        }
        if (db != null) {
            db.close();
        }
        return db != 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 = new FileOutputStream(databaseFilenames);// 得到数据库文件的写入流
        InputStream is = context.getResources().openRawResource(R.raw.zhouyi);
        byte[] buffer = new byte[8192];
        int count = 0;
        while ((count = is.read(buffer)) > 0) {
            os.write(buffer, 0, count);
            os.flush();
        }
        is.close();
        os.close();
    }

}

6. 在主activity里,这样调用

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        DataBaseUtil util = new DataBaseUtil(this);
        if (!util.checkDataBase()) {
            try {
                util.copyDataBase();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }

7. 具体查询操作,这里给出了只查询一条的方法,和查询集合的方法。查询后,游标指向第一条之前,数值为-1,只有当他移动到第一条时,才能读到数据,moveToFirst。或者用moveToNext遍历。在as的logcat控制台,可以看到生成的打印的SQL语句。

public class DivineDao {

    private static String DB_NAME = DataBaseUtil.dbName;
    private SQLiteDatabase db;

    public DivineDao(Context context) {
        String packageName = context.getPackageName();
        String DATABASE_PATH = "/data/data/" + packageName + "/databases/";
        db = SQLiteDatabase.openOrCreateDatabase(DATABASE_PATH + "/" + DB_NAME, null);
    }

    public List<Divine> getAll() {
        List<Divine> categorys = new ArrayList<Divine>();
        Cursor cursor = db.query("devine", null, null, null, null, null, null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            Divine category = new Divine();
            category.set_id(cursor.getInt(0));
            category.setGuaID(cursor.getString(1));
            category.setGua_name(cursor.getString(2));
            category.setGua_name_simple(cursor.getString(3));
            category.setYao(cursor.getInt(4));
            categorys.add(category);
            cursor.moveToNext();
        }
        cursor.close();
        return categorys;
    }


//查询一条的方法,
public String getbyguaid(String guaID) { Cursor cursor = db.query("devine",null,"guaID=?",new String[]{guaID},null,null,null,null); //两种方法都可以,cursor必须moveToFirst才好用,否则开始时指向-1位置。 //Cursor cursor = db.rawQuery("select _id,guaID,gua_name,info from devine where guaID = ?", new String[]{guaID}); if(cursor==null){ Log.e("TagXX","query no data"); return null; } cursor.moveToFirst(); String gua_name = cursor.getString(2); // String gua_name=""; // while(cursor.moveToNext()){ // gua_name=cursor.getString(cursor.getColumnIndex("gua_name")); // gua_name=cursor.getString(2); //} cursor.close(); db.close(); Log.e("TAGxx","GuanameDao: "+gua_name); return gua_name; } }

好运!

猜你喜欢

转载自www.cnblogs.com/sdgtxuyong/p/10566270.html
今日推荐