extends:http://blog.csdn.net/lihenair/article/details/21232887

项目需要将预先处理的db文件加载到数据库中,然后读取其中的信息并显示

加载数据库的代码参考了http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

效果如下:

1. 将asset中的db文件复制到database数据库中

public class DBHelper extends SQLiteOpenHelper {  

    private static final String LOG_TAG = "DataHelper";  

    private SQLiteDatabase mDataBase;
private final Context mContext; private static final String DATABASE_PATH = "/data/data/PACKAGE_NAME/databases/";
private static final String DATABASE_NAME = "xx.db";
private static final int DATABASE_VERSION = 1; public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.mContext = context;
} public DBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
this.mContext = context;
} /**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void createDataBase() throws IOException { boolean dbExist = checkDataBase(); Log.d(LOG_TAG, "dbExist: " + dbExist); if (dbExist) {
// do nothing - database already exist
} else {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase(); try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
} } /**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
Log.d(LOG_TAG, "checkDataBase");
SQLiteDatabase checkDB = null; try {
String myPath = DATABASE_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
} if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
} /**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
Log.d(LOG_TAG, "copyDataBase");
// Open your local db as the input stream
InputStream myInput = mContext.getAssets().open(DATABASE_NAME); // Path to the just created empty db
String outFileName = DATABASE_PATH + DATABASE_NAME; // Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName); // transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
} // Close the streams
myOutput.flush();
myOutput.close();
myInput.close(); } public void openDataBase() throws SQLException {
Log.d(LOG_TAG, "openDataBase");
// Open the database
String myPath = DATABASE_PATH + DATABASE_NAME;
mDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY); } @Override
public synchronized void close() {
if (mDataBase != null)
mDataBase.close();
super.close(); } @Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
} @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
} }
 

调用的代码如下:

DataBaseHelper myDbHelper = new DataBaseHelper();
myDbHelper = new DataBaseHelper(this); try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
 

2. 显示数据库中的内容

 
public class CityGPS extends Activity {  

private static final String TAG = CityGPS.class.getSimpleName();  

private EditText mCityEdit;
private TextView mNameText;
private TextView mLattText;
private TextView mLongText;
private Button mButton;
private ListView mList;
private SimpleCursorAdapter mAdapter;
private Cursor cursor = null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); DBHelper mDbHelper = new DBHelper(this); try {
mDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
} try {
mDbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
} mCityEdit = (EditText) findViewById(R.id.city);
mNameText = (TextView) findViewById(R.id.name);
mLattText = (TextView) findViewById(R.id.lat);
mLongText = (TextView) findViewById(R.id.lon); String sql = "SELECT * FROM citygps";
cursor = mDbHelper.getReadableDatabase().rawQuery(sql, null); String[] strings = { "city", "lat", "lon" };
int[] ids = { R.id.name, R.id.lat, R.id.lon };
mAdapter = new SimpleCursorAdapter(this, R.layout.item, cursor,
strings, ids, 0);
mList = (ListView) findViewById(R.id.list);
mList.setAdapter(mAdapter);
mButton = (Button) findViewById(R.id.btn);
mButton.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
String city = mCityEdit.getText().toString(); if (TextUtils.isEmpty(city) == true) {
Toast.makeText(CityGPS.this, "plz input city",
Toast.LENGTH_SHORT).show();
return;
} String[] projection = { CityGPSTable.CITY,
CityGPSTable.LATITUDE, CityGPSTable.LONGITUDE };
String selection = CityGPSTable.CITY + " = " + "\"" + city + "\"";
Cursor cursor = getContentResolver().query(
CityGPSContentProvider.CONTENT_URI, projection, selection,
null, null); if (cursor != null) {
cursor.moveToFirst();
Float lat = cursor.getFloat(cursor.getColumnIndex(CityGPSTable.LATITUDE));
Float lon = cursor.getFloat(cursor.getColumnIndex(CityGPSTable.LONGITUDE)); Log.d(TAG, "lat: " + lat + " lon: " + lon); mNameText.setText(city);
mLattText.setText(lat.toString());
mLongText.setText(lon.toString());
}
}
});
}
}
 

main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".CityGPS" > <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" > <EditText
android:id="@+id/city"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="text" /> <Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/search" />
</LinearLayout> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" > <TextView
android:id="@+id/name"
style="@android:style/TextAppearance.Holo.Medium"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="@string/city" /> <TextView
android:id="@+id/lat"
style="@android:style/TextAppearance.Holo.Medium"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="@string/lat" /> <TextView
android:id="@+id/lon"
style="@android:style/TextAppearance.Holo.Medium"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="@string/lon" />
</LinearLayout> <View
android:layout_width="match_parent"
android:layout_height="3dp"
android:background="@android:color/holo_red_dark"
android:visibility="visible" /> <ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" /> </LinearLayout>
 

item.xml,每行都带分割线

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" > <TextView
style="@android:style/TextAppearance.Holo.Medium"
android:id="@+id/name"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="@string/city" /> <View
android:layout_width="1px"
android:layout_height="match_parent"
android:background="#B8B8B8"
android:visibility="visible" /> <TextView
style="@android:style/TextAppearance.Holo.Medium"
android:id="@+id/lat"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="@string/lat" /> <View
android:layout_width="1px"
android:layout_height="match_parent"
android:background="#B8B8B8"
android:visibility="visible" /> <TextView
style="@android:style/TextAppearance.Holo.Medium"
android:id="@+id/lon"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="@string/lon" /> </LinearLayout>
 
 

Android加载asset的db的更多相关文章

  1. Android加载/处理超大图片神器!SubsamplingScaleImageView(subsampling-scale-image-view)【系列1】

    Android加载/处理超大图片神器!SubsamplingScaleImageView(subsampling-scale-image-view)[系列1] Android在加载或者处理超大巨型图片 ...

  2. Android加载网络图片报android.os.NetworkOnMainThreadException异常

    Android加载网络图片大致可以分为两种,低版本的和高版本的.低版本比如4.0一下或者更低版本的API直接利用Http就能实现了: 1.main.xml <?xml version=" ...

  3. android加载大量图片内存溢出的三种方法

    android加载大量图片内存溢出的三种解决办法 方法一:  在从网络或本地加载图片的时候,只加载缩略图. /** * 按照路径加载图片 * @param path 图片资源的存放路径 * @para ...

  4. android加载gif图片

    Android加载GIF图片的两种方式 方式一:使用第三开源框架直接在布局文件中加载gif 1.在工程的build.gradle中添加如下 buildscript { repositories { m ...

  5. 漂亮的Android加载中动画:AVLoadingIndicatorView

    AVLoadingIndicatorView 包含一组漂亮的Android加载中动画. IOS版本:here. 示例 Download Apk 用法 步骤1 Add dependencies in b ...

  6. 8. Android加载流程(打包与启动)

    移动安全的学习离不开对Android加载流程的分析,包括Android虚拟机,Android打包,启动流程等... 这篇文章  就对Android的一些基本加载进行学习. Android虚拟机 And ...

  7. React-Native 之 GD (二十)removeClippedSubviews / modal放置的顺序 / Android 加载git图\动图 / 去除 Android 中输入框的下划线 / navigationBar

    1.removeClippedSubviews 用于提升大列表的滚动性能.需要给行容器添加样式overflow:’hidden’.(Android已默认添加此样式)此属性默认开启 这个属性是因为在早期 ...

  8. android加载字体内存泄漏的处理方法

    在开发android app的开发过程中,会使用到外部的一些字体.外部字体在加载的时候,容易造成内存泄漏. 比如: Typeface tf=Typeface.createFromAsset(getAs ...

  9. android 加载网络图片

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...

随机推荐

  1. Oracle高级查询之CONNECT BY

    为了方便大家学习和测试,所有的例子都是在Oracle自带用户Scott下建立的. Oracle中的select语句可以用start with ... connect by prior ...子句实现递 ...

  2. 基于maven使用IDEA创建多模块项目

    原文地址:http://blog.csdn.net/williamhappy/article/details/54376855 鉴于最近学习一个分布式项目的开发,讲一下关于使用IntelliJ IDE ...

  3. SQL随机生成6位数字

    SELECT RIGHT(100000000 + CONVERT(bigint, ABS(CHECKSUM(NEWID()))), 6)

  4. NAS 创建大文件

      不是很懂,但是管用.先记录下来. http://www.111cn.net/sys/linux/55537.htm

  5. CorelDRAW中六种复制对象的方法详解

    复制可保证对象的大小一致,复制也是所有操作中最基本的操作.CorelDRAW软件中支持多种复制对象的操作,本教程将详解CorelDRAW中六种复制对象的方法. 方法一 选择复制对象,点击编辑→复制,再 ...

  6. php扩展yaf 按照配置

    Yaf,全称 Yet Another Framework,是一个C语言编写的PHP框架,是一个用PHP扩展形式提供的PHP开发框架, 相比于一般的PHP框架, 它更快. 它提供了Bootstrap, ...

  7. mysql中,创建表的时候指定if not exists参数的作用?

    需求说明: 在创建表的时候,如果指定if not exists语句,有什么作用,在此做个实验,并且官方手册, 理解下这个参数的作用. 操作过程: 1.创建测试表test01 mysql> cre ...

  8. javascript生成m位随机数

    根据时间生成m位随机数,最大13位随机数,并且不能保证首位不为0 function ran(m) { m = m > 13 ? 13 : m; var num = new Date().getT ...

  9. Dubbo -- 系统学习 笔记 -- 示例 -- 集群容错

    Dubbo -- 系统学习 笔记 -- 目录 示例 想完整的运行起来,请参见:快速启动,这里只列出各种场景的配置方式 集群容错 在集群调用失败时,Dubbo提供了多种容错方案,缺省为failover重 ...

  10. ajax访问WebService跨域问题

    1.先看一个网站介绍,了解跨域问题    HTTP访问控制(CORS) 2.像谷歌.火狐浏览器对一些非简单请求会触发预检请求,首先使用 OPTIONS   方法发起一个预检请求到服务器,然而IE浏览器 ...