sqlite与android交互 (封装)
学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 class DBConn { 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; private Context context; private SQLiteDatabase database; public DBConn(Context context){ this.context = context; } public static final DBConn getInstance(Context context){ DBConn conn = new DBConn(context); return conn; } public SQLiteDatabase getDb(){ database = openDB(PATH + File.separator + DB_NAME); return database; } public SQLiteDatabase openDB(String dbFile){ try{ if(!isExitFile(dbFile)){ InputStream is = context.getResources().openRawResource(R.raw.test); FileOutputStream fos = new FileOutputStream(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); return database; }catch (Exception e) { e.printStackTrace(); return null; } } public boolean isExitFile(String path){ File file = new File(path); return file.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 class DBManage { private SQLiteDatabase db; public DBManage(Context context) { DBConn conn = DBConn.getInstance(context); db = conn.getDb(); } public List<String> queryData(String sql, String[] selectionArgs, String property){ Cursor cursor = null; List<String> list = new ArrayList<String>(); 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(); } } return list; } }
主入口就是一个下拉列表的显示,然后就是调用sqlite数据库了,部分代码如下:
proSelect = (Spinner) findViewById(R.id.proSelect); DBManage dbManage = new DBManage(this); List<String> proList = dbManage.queryData("select * from au_user", null, "username"); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_gallery_item, proList); proSelect.setAdapter(arrayAdapter);
总结一句话,其实代码敲多了 才去想怎么敲,而不是一点都没敲就去想如何将语句敲到最好 我觉得这个是不可能的,菜鸟自学路程。。。