学android已经有大概一周时间了吧 ,总感觉自己基础不怎么好,只能通过一点一点积累着敲来巩固平常的知识,有的时候就先不封装的敲一遍,再封装上,有些语句真的记不住,虽然知道他是什么意思,于是乎就反复的敲着,加油吧!少年,下面进入正题吧
DBConn.java类 主要是将raw写入到DDMS里的data/data/xxx包/下,代码如下:
package com.tp.soft.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import com.example.dbcity.R;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;public classDBConn {private static String DB_NAME = "test.db";private static String PACKAGE = "com.example.dbcity";private static String PATH = "/data" +Environment.getDataDirectory().getPath()+File.separator+PACKAGE;privateContext context;privateSQLiteDatabase database;publicDBConn(Context context){this.context =context;
}public staticfinal DBConn getInstance(Context context){
DBConn conn= newDBConn(context);returnconn;
}publicSQLiteDatabase getDb(){
database= openDB(PATH + File.separator +DB_NAME);returndatabase;
}publicSQLiteDatabase openDB(String dbFile){try{if(!isExitFile(dbFile)){
InputStreamis =context.getResources().openRawResource(R.raw.test);
FileOutputStream fos= newFileOutputStream(dbFile);byte[] buffer = new byte[1024];int len = -1;while((len = is.read(buffer)) != -1){
fos.write(buffer,0, len);
}is.close();
fos.close();
}
database= SQLiteDatabase.openOrCreateDatabase(dbFile, null);returndatabase;
}catch(Exception e) {
e.printStackTrace();return null;
}
}publicboolean isExitFile(String path){
File file= newFile(path);returnfile.exists();
}
}
DBManage.java主要是对数据库的封装,目前只做了个查询,待后期完善吧,代码如下:
package com.tp.soft.util;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;public classDBManage {privateSQLiteDatabase db;publicDBManage(Context context) {
DBConn conn=DBConn.getInstance(context);
db=conn.getDb();
}public ListqueryData(String sql, String[] selectionArgs, String property){
Cursor cursor= null;
List list = new ArrayList();try{
cursor=db.rawQuery(sql, selectionArgs);while(cursor.moveToNext()){
String str=cursor.getString(cursor.getColumnIndex(property));
list.add(str);
}
}catch(Exception e) {
e.printStackTrace();
}finally{if(null !=cursor){
cursor.close();
}
}returnlist;
}
}
主入口就是一个下拉列表的显示,然后就是调用sqlite数据库了,部分代码如下:
proSelect =(Spinner) findViewById(R.id.proSelect);
DBManage dbManage= new DBManage(this);
List proList = dbManage.queryData("select * from au_user", null, "username");
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_gallery_item, proList);
proSelect.setAdapter(arrayAdapter);
总结一句话,其实代码敲多了 才去想怎么敲,而不是一点都没敲就去想如何将语句敲到最好 我觉得这个是不可能的,菜鸟自学路程。。。