Android加载asset的db

时间:2022-03-29 21:27:49

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

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

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

效果如下:

Android加载asset的db

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>