乐学成语——数据库操作

乐学英语——数据库操作

1.将idioms.db数据库传入/data/data/package name目录下。

   
<span style="font-size:18px;"><span style="font-size:18px;">package com.edu.happyidiom.db;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.example.happyidiom.R;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;
/**
 * 
 * 实现将数据库文件从raw目录拷贝到手机里存放数据库的位置
 * @author A_Yan
 *
 */

public class DBOpenHelper {
	private final int BUFFER_SIZE=400000;//缓冲区大小
	public static final String DB_NAME="idioms.db"; //保存的数据库文件名
	public static final String PACKAGE_NAME="com.example.happyidiom";//应用的包名
	public static final String DB_PATH="/data"
	+Environment.getDataDirectory().getAbsolutePath()+"/"
	+PACKAGE_NAME+"/databases";//在手机里存放数据库的位置
	private Context context;
	public DBOpenHelper(Context context){
		this.context=context;
	}
	public SQLiteDatabase openDatabase(){
		
		try{
		File myDataPath=new File(DB_PATH);
		if(!myDataPath.exists()){
			myDataPath.mkdirs();//如果没有这个数据库则创建
		}
		String dbfile=myDataPath+"/"+DB_NAME;
		if(!(new File(dbfile).exists())){//判断数据库文件是否存在,若不存在直接导入,
			//否则直接打开数据库
			InputStream is=context.getResources().openRawResource(R.raw.idioms);
			FileOutputStream fos=new FileOutputStream(dbfile);
			byte[] buffer=new byte[BUFFER_SIZE];
			int count=0;
			while((count=is.read(buffer))>0){
				fos.write(buffer, 0,count);
			}
			fos.close();
			is.close();
		}
		SQLiteDatabase db=SQLiteDatabase.openOrCreateDatabase(dbfile, null);
		return db;
		}catch(FileNotFoundException e){
			Log.e("Database","File not found");
			e.printStackTrace();
		}
		catch(IOException e){
			Log.e("Database","IO exception");
			e.printStackTrace();
		}
		
		
		return null;
	}

}</span></span>

2.在AndriodManifest中搭建单元测试环境。

<span style="font-size:18px;"><span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.happyidiom"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <span style="background-color: rgb(255, 0, 0);"><uses-library android:name="android.test.runner"/></span>
        <activity
            android:name="com.example.happyidiom.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <span style="background-color: rgb(255, 0, 0);"><instrumentation 
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.example.happyidiom"
        ></instrumentation>
</span>
</manifest></span></span>

3.测试数据库有没有传入。(切换到DOM在/data/data/package name查看

<span style="font-size:18px;">package com.edu.happyidiom.test;

import com.edu.happyidiom.db.DBOpenHelper;

import android.test.AndroidTestCase;

public class DBOpenHelperTest extends AndroidTestCase{
	
	public void testDBCopy(){
		DBOpenHelper dBOpenHelper=new DBOpenHelper(getContext());
		dBOpenHelper.openDatabase();
	}

}</span>

4.创建实体类Animal,便于以后开发。

<span style="font-size:18px;">package com.edu.happyidiom.entity;

public class Animal {
	private int id;
	private String name;
	private String pronounce;
	private String explain;
	private String autonym;
	private String homoionym;
	private String derivation;
	private String examples;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPronounce() {
		return pronounce;
	}
	public void setPronounce(String pronounce) {
		this.pronounce = pronounce;
	}
	public String getExplain() {
		return explain;
	}
	public void setExplain(String explain) {
		this.explain = explain;
	}
	public String getAutonym() {
		return autonym;
	}
	public void setAutonym(String autonym) {
		this.autonym = autonym;
	}
	public String getHomoionym() {
		return homoionym;
	}
	public void setHomoionym(String homoionym) {
		this.homoionym = homoionym;
	}
	public String getDerivation() {
		return derivation;
	}
	public void setDerivation(String derivation) {
		this.derivation = derivation;
	}
	public String getExamples() {
		return examples;
	}
	public void setExamples(String examples) {
		this.examples = examples;
	}
	

}
</span>

5.创建AnimalDao类,对数据库进行封装。


<span style="font-size:18px;">package com.edu.happyidiom.dao;

import java.util.ArrayList;
import java.util.List;

import com.edu.happyidiom.db.DBOpenHelper;
import com.edu.happyidiom.entity.Animal;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class AnimalDao {
	private static AnimalDao animalDao;
	private SQLiteDatabase db;
	/**
	 * 将构造方法私有化
	 */
	private AnimalDao(Context context){
		DBOpenHelper dbHelper =new DBOpenHelper(context);
		db=dbHelper.openDatabase();
	}
	/**
	 * 获取AnimalDao的实例
	 */
	public synchronized static AnimalDao getInstance(Context context){
		if(animalDao==null){
			animalDao=new AnimalDao(context);
		}
		return animalDao;
	}
	/**
	 * 从数据库获取所有的动物类成语
	 */
	public List<Animal> getAllAnimals(){
		List<Animal> list=new ArrayList<Animal>();
		Cursor cursor =db.query("animal",null, null,null,null,null,null);
		if(cursor.moveToFirst()){
			do{
				Animal animal=new Animal();
				animal.setId(cursor.getInt(cursor.getColumnIndex("_id")));
				animal.setName(cursor.getString(cursor.getColumnIndex("name")));
				animal.setPronounce(cursor.getString(cursor.getColumnIndex("pronounce")));
				animal.setAutonym(cursor.getString(cursor.getColumnIndex("autonym")));
				animal.setHomoionym(cursor.getString(cursor.getColumnIndex("homoionym")));
				animal.setDerivation(cursor.getString(cursor.getColumnIndex("derivation")));
				animal.setExamples(cursor.getString(cursor.getColumnIndex("examples")));
                list.add(animal);
			}while(cursor.moveToNext());
		}
		return list;
	}

}
</span>

6.编写AnimalDaoTest测试类

<span style="font-size:18px;">package com.edu.happyidiom.test;

import java.util.List;

import com.edu.happyidiom.dao.AnimalDao;
import com.edu.happyidiom.entity.Animal;

import android.test.AndroidTestCase;

public class AnimalDaoTest extends AndroidTestCase{
	public void testGetAllAnimals(){
		AnimalDao animalDao=AnimalDao.getInstance(getContext());
		List<Animal> animals=animalDao.getAllAnimals();
		System.out.println(animals.size());
		for(Animal animal:animals){
			System.out.println(animal.getName());
		}
	}

}</span>

  7.ENDING

            至此,第一阶段的编程就结束了,改天我们再说一下第二阶段的开发。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值