但是在读写外置数据库时,使用到的是SQLiteDatabase.openOrCreateDatabase(file, factory)方法,第一个参数指的就是数据库文件,第二个参数通常传入null即可。直接上个简单的代码:
public class CustomSQLTools { //数据库存储路径 private String filePath; private SQLiteDatabase database; public SQLiteDatabase openDatabase(Context context) { File jhPath = new File(filePath); //查看数据库文件是否存在 if (jhPath.exists()) { //存在则直接返回打开的数据库 return SQLiteDatabase.openOrCreateDatabase(jhPath, null); } else { Toast.makeText(context, "数据库文件不存在", Toast.LENGTH_SHORT).show(); return null; } }}在Activity中使用:
public class TestDbActivity extends BaseAct { private TextView test_db; @Override public void setRootView() { setContentView(R.layout.activity_test); test_db = (TextView) findViewById(R.id.test_db); test_db.setOnClickListener(this); } @Override public void widgetClick(View v) { if (v.getId() == R.id.test_db) { //点击直接根据条件查询数据库数据 initSqlAndQuery("1000001739", date); }); } } private void initSqlAndQuery(String queryId, String queryDate) { List<TestDataBean> queryResultList = new ArrayList<>(); CustomSQLTools s = new CustomSQLTools(); SQLiteDatabase database = s.openDatabase(getApplicationContext()); String sql = "select * from VITAL_DATA_BEAN where deviceId = ? and date like?"; Cursor cursor = database.rawQuery(sql, new String[]{queryId, queryDate + "%"}); while (cursor.moveToNext()) { TestDataBeanbean = new TestDataBean(); int deviceId = cursor.getInt(cursor.getColumnIndex("deviceId")); String date = cursor.getString(cursor.getColumnIndex("date")); String rpm = cursor.getString(cursor.getColumnIndex("rpm")); String movementFast = cursor.getString(cursor.getColumnIndex("movementFast")); //设置对应实体数据,从而获取到我们需要的数据 bean.setDeviceId(deviceId); bean.setDate(date); bean.setRpm(rpm); bean.setMovementFast(movementFast); queryResultList.add(bean); } cursor.close(); database.close(); }}