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. Single Pattern(单例模式)

    单例模式是一种常用的软件设计模式.通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源.如果希望在系统中某个类的实例只能存在一个,单例模式是最好的 ...

  2. 使用Matplotlib画图系列(一)

    实现一个最简单的plot函数调用: import matplotlib.pyplot as plt y=pp.DS.Transac_open # 设置y轴数据,以数组形式提供 x=len(y) # 设 ...

  3. Android内存泄漏检測与MAT使用

    公司相关项目须要进行内存优化.所以整理了一些分析内存泄漏的知识以及工作分析过程. 本文中不会刻意的编写一个内存泄漏的程序,然后利用工具去分析它.而是通过介绍相关概念,来分析怎样寻找内存泄漏.并附上自己 ...

  4. 本地Chrome测试JS代码报错:XMLHttpRequest cannot load

    这种file跨域问题在火狐下是不存在的 解决Chrome下file跨域问题: 在Chrome应用程序下,右键属性,目标处添加"--allow-file-access-from-files&q ...

  5. WebService之JDK中wsimport命令

    1.编写WebService类,使用@WebService注解 package test; import javax.jws.WebService; @WebService public class ...

  6. 一句话木马:ASPX篇

    aspx木马收集: <%@ Page Language="Jscript"%><%eval(Request.Item["chopper"],& ...

  7. Libjingle库 综述

    国内现在很多语音聊天工具都是基于TURN方式实现的,包括YY.AK等等,这种方式对于服务器的性能要求很高,而且在用户量增大的时候,服务器压力也会越来越大,用户的语音质量也会受到很大影响.而基于P2P方 ...

  8. Sharepoint文档的CAML分页及相关筛选记录

    写这篇文章的初衷是因为其他的业务系统要调用sharepoint的文档库信息,使其他的系统也可以获取sharepoint文档库的信息列表.在这个过程中尝试过用linq to sharepoint来获取文 ...

  9. [ZZ]c++ cout 格式化输出浮点数、整数及格式化方法

    C语言里可以用printf(),%f来实现浮点数的格式化输出,用cout呢...?下面的方法是在网上找到的,如果各位有别的办法谢谢留下... iomanip.h是I/O流控制头文件,就像C里面的格式化 ...

  10. Elasticsearch 配置同义词

    配置近义词 近义词组件已经是elasticsearch自带的了,所以不需要额外安装插件,但是想要让近义词和IK一起使用,就需要配置自己的分析器了. 首先创建近义词文档 在config目录下 mkdir ...