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. Mysql 大量数据导入

    今天试图用heidisql 导入一个150M的数据文件(.sql), 结果报out of memory 错误.在网上搜了很多案例,都没能解决问题.我甚至怀疑是mysql 的default的内存设置的太 ...

  2. 使用 Python 解数学方程

    SymPy是符号数学的Python库.它的目标是成为一个全功能的计算机代数系统,同时保持代码简洁.易于理解和扩展 服务器Ubuntu 1.安装Python 2.安装SymPy库 sudo pip in ...

  3. css 中的相对定位和绝对定位

    1.默认不写position的话,值为static. 2.相对定位:相对于元素自己本身的位置偏移,虽然位置偏移,但元素本身占据的空间并不释放. 3.绝对定位:相对于离它最近的,position不为st ...

  4. oracle数据库中sql%notfound的用法

    SQL%NOTFOUND 是一个布尔值.与最近的sql语句(update,insert,delete,select)发生交互,当最近的一条sql语句没有涉及任何行的时候,则返回true.否则返回fal ...

  5. feed流拉取,读扩散,究竟是啥?

    from:https://mp.weixin.qq.com/s?__biz=MjM5ODYxMDA5OQ==&mid=2651961214&idx=1&sn=5e80ad6f2 ...

  6. Mesos 入门教程

    Mesos提供了高效.跨分布式应用程序和框架的资源隔离和共享,支持Hadoop. MPI.Hypertable.Spark等. Mesos是Apache孵化器中的一个开源项目,使用ZooKeeper实 ...

  7. vuejs中使用echart图表

    首先安装echart npm i echarts -S 加下来以使用这个图表为例 在vue组件中像这样使用: <template> <div :class="classNa ...

  8. Kafka(二)-- 安装配置

    一.单机部署 1.下载kafka,可在apache官网上下载,kafka要和JDK版本对应,我使用的是JDK1.7,kafka为0.10 2.进入到 /usr/java 中,解压到 此文件夹中 tar ...

  9. [Ubuntu] APT - Advanced Packaging Tool 简明指南

    Advanced Packaging Tool,一般简称为apt,是Debian GNU/Linux distribution及其变体版本中与核心库一道处理软件的安装和卸载. Ubuntu是Debia ...

  10. C语言的f(open)函数(文件操作/读写)

    头文件:#include <stdio.h> fopen()是一个常用的函数,用来以指定的方式打开文件,其原型为:     FILE * fopen(const char * path, ...