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. js堆栈与队列简单记忆

    在面向对象的程序设计里,一般都提供了实现队列(queue)和堆栈(stack)的方法,而对于JS来说,我们可以实现数组的相关操作,来实现队列和堆栈的功能,看下面的相关介绍. 一 看一下它们的性质,这种 ...

  3. 8 map的用法

    what's map go里面的map和python字典差不多. 类似其他语言中的哈希表或者字典,以key-value的形式存储的数据 key必须是支持==或者!=比较运算的类型,不可以是函数.map ...

  4. 我的Oracle控制台创建数据库的工具

    Oracle windows 11.2.0.4 在控制台cmd下的创建工具,不依赖于服务和监听 工具及下载:Oracle控制台工具 注意:其中的 “seeddatabase.gbk.7z”文件为从Or ...

  5. 【转】ZooKeeper详细介绍和使用第一节

    一.分布式协调技术 在给大家介绍ZooKeeper之前先来给大家介绍一种技术——分布式协调技术.那么什么是分布式协调技术?那么我来告诉大家,其实分布式协调技术 主要用来解决分布式环境当中多个进程之间的 ...

  6. Grunt--Less

    摘要: 之前介绍了自动构建工具Grunt,其中有一个模块是"grunt-contrib-less",下面是配置Grunt自动编译less文件. 安装: Grunt是基于node,功 ...

  7. 【转】WCF OpenTimeout, CloseTimeout, SendTimeout, ReceiveTimeout

    关于这四个属性,在MSDN中的解释有点敷衍了事.Open/Close/Receive/Send本是HTTP/TCP/SOCKET的概念,Read/Write Operation则是Web Servic ...

  8. nuget包循环引用问题

    1.项目中有类库YesWay.Nlog.RabbitMQ,依赖项如下YesWay.Nlog.RabbitMQ=>YesWay.Service.Discovery=>YesWay.Log 2 ...

  9. ice服务初探

    http://masterkey.iteye.com/blog/182975 http://blog.csdn.net/moxiaomomo/article/details/6773979 http: ...

  10. spine-unity3D 学习笔记

    http://zh.esotericsoftware.com/spine-using-runtimes //skeletonData SkeletonAnimation skeletonAnimati ...