我需要知道在我的代码中调用db.close()的位置.我已经在onCreate()方法上添加了它,但是当我需要使用某些方法时,它说数据库未打开,然后我从onCreate()中删除了,并说未明确调用close().所以我应该在哪里关闭,它可以在类的每个方法内吗?
这是代码:
public class HoursPerDayDataHelper {private static final String DATABASE_name = "database.db";private static final int DATABASE_VERSION = 1;protected static final String table_name = "table";protected String TAG = "HoursPerDayDataHelper";private Context context;private sqliteDatabase db;OpenHelper openHelper = null;public HoursPerDayDataHelper(Context context) { this.context = context; openHelper = new OpenHelper(this.context); this.db = openHelper.getWritableDatabase(); openHelper.onCreate(db);}public voID close() { if (openHelper != null) { openHelper.close(); }}public voID deleteall() { this.db.delete(table_name, null, null);}public String selectDuration(String date) { String duration = ""; Integer value = 0; String returnment = ""; Log.i(TAG, "date do select: " + date); Cursor cursor = this.db.query(table_name, new String[] { "duration" }, "date = ? ", new String[]{ date }, null, null, null); Log.i(TAG, "cursor string " + cursor); if (cursor.movetoFirst()) { do { Log.i(TAG, "dentro do if cursor"); duration = cursor.getString(0); value += Integer.parseInt(duration); } while (cursor.movetoNext()); returnment = Integer.toString(value); }else{ Log.i(TAG, "bla bla bla"); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } return returnment;}public ArrayList<String[]> selecttopContacts() { ArrayList<String[]> List1 = new ArrayList<String[]>(); Cursor cursor = this.db.query(table_name, null, null, null, null, null, "duration desc"); if (cursor.movetoFirst()) { do { if (cursor.getString(2) != "") { String[] data = new String[4]; data[0] = cursor.getString(2); data[1] = cursor.getString(4); data[2] = cursor.getString(5); data[3] = cursor.getString(7); List1.add(data); } else { String[] data = new String[3]; data[1] = cursor.getString(4); data[2] = cursor.getString(5); data[3] = cursor.getString(7); List1.add(data); } } while (cursor.movetoNext()); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } return List1;}public static class OpenHelper extends sqliteOpenHelper { OpenHelper(Context context) { super(context, DATABASE_name, null, DATABASE_VERSION); } @OverrIDe public voID onCreate(sqliteDatabase db) { db.execsql("CREATE table IF NOT EXISTS " + table_name + "(ID INTEGER PRIMARY KEY autoINCREMENT, duration TIME, date DATE, current_time TIME)"); } @OverrIDe public voID onUpgrade(sqliteDatabase db, int oldVersion, int newVersion) { Log.w("HoursPerDay Database", "Upgrading database, this will drop tables and recreate."); db.execsql("DROP table IF EXISTS " + table_name); onCreate(db); }}}
这是我的活动:
public class HoursPerDay extends Activity{private String LOG_TAG = "HoursPerDay";private TextVIEw mDatedisplay;public String date;private int mYear;private int mMonth;private int mDay;private int newDay;private String hpdData; private HoursPerDayDataHelper hpd;OpenHelper openHelper = new OpenHelper(HoursPerDay.this);static final int DATE_DIALOG_ID = 0;protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.hours_per_day); hpd = new HoursPerDayDataHelper(this); // capture our VIEw elements mDatedisplay = (TextVIEw) findVIEwByID(R.ID.datedisplay); // get the current date final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); // display the current date (this method is below)}@OverrIDeprotected voID onDestroy() { super.onDestroy(); if (openHelper != null) { openHelper.close(); } if (hpd != null) { hpd.close(); }}// the callback received when the user "sets" the date in the dialogprivate DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public voID onDateSet(DatePicker vIEw, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; setBasicContent(); hpd.close(); }};protected Dialog onCreateDialog(int ID) { switch (ID) { case DATE_DIALOG_ID: return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay); } return null;}@OverrIDepublic boolean onCreateOptionsMenu(Menu menu){ MenuInflater inflater = getMenuInflater(); inflater.inflate(R.layout.hoursperdaymenu, menu); return true;}@OverrIDepublic boolean onoptionsItemSelected(MenuItem item){ switch(item.getItemID()){ case R.ID.filter_by_day: showDialog(DATE_DIALOG_ID); return true; case R.ID.filter_by_user: showDialog(DATE_DIALOG_ID); return true; default: return super.onoptionsItemSelected(item); }} public voID setBasicContent() { date = (mMonth + 1) + "/" + newDay + "/" + mYear; hpdData = this.hpd.selectDuration(date); mDatedisplay.setText(hpdData); hpd.close();}}
解决方法:
我认为有两种方法:
>在onPause方法中,检查是否有完成->关.问题:如果您的应用程序被应用程序杀手杀死,则数据库保持打开状态.
>每次读取/写入(方法)时,都会打开和关闭数据库.
编辑:
好的,我知道为什么会造成这种情况.我认为您误解了sqliteOpenHelper的用法.您无需调用onCreate方法.
最好的方法是创建一个DBHelper类,并在单独的调用中使用它,比如说sqlDataHandler.
您的活动看起来不错.我改变了几件事,看看是否有帮助.我将其标记为:
这就是Helper类中的所有内容:
public static class OpenHelper extends sqliteOpenHelper { private static final String DATABASE_name = "database.db"; private static final int DATABASE_VERSION = 1; protected static final String table_name = "table"; protected String TAG = "HoursPerDayDataHelper";
只需保留它的CREATE table就可以创建/调用它(如果不存在).
我已经看到如果直接传递字符串会发生错误
@OverrIDe public voID onCreate(sqliteDatabase db) { String query = "CREATE table " + table_name + "(ID INTEGER PRIMARY KEY autoINCREMENT, duration TIME, date DATE, current_time TIME)"; db.execsql(query); } }@OverrIDepublic voID onUpgrade(sqliteDatabase db, int oldVersion, int newVersion) {} OpenHelper(Context context) { super(context, DATABASE_name, null, DATABASE_VERSION); }}
要使用它:
只需调用您的DataHandler类:
OpenHelper helper = new OpenHelper(ctx);// sqliteDatabase db = helper.getReadableDatabase();sqliteDatabase db = helper.getWritableDatabase();
所有其他内容,例如删除,添加等,都应在“ DataHandler”类中完成.
只需在此处使用相同的两种方法即可获取数据库.最后,完成 *** 作后,只需在DataHandler类db.close()中进行调用.
这样,活动本身永远不会直接使用de DB.我认为更好的做法;)
希望对您有所帮助.如有其他疑问,请问:)
EDIT2:
首先,通常它应该与内部类一起工作.
但是:如果您想从另一个类中添加另一个表,它将不再起作用.这就是为什么这是从一开始就将其放在单独的类中的更好方法.它甚至可以重用(进行一些小的调整).
将我发布的代码放在您的类OpenHelper中.而已.
然后,将数据处理的东西放在一个类中:DataHandlerDB.
代码示例:
package ...;import java.util.ArrayList;import java.util.List;import androID.content.ContentValues;import androID.content.Context;import androID.database.Cursor;import androID.database.sqlite.sqliteDatabase;public class DataHandlerDB { public static voID persistAll(Context ctx, List<Module> moduleList) { DatabaseHelper helper = new DatabaseHelper(ctx); sqliteDatabase db = helper.getWritableDatabase(); ContentValues values = new ContentValues(); for (Module m : moduleList) { values.put("_ID", m.get_ID()); values.put("name", m.getModule()); db.insert("module", null, values); } db.close(); } public static List<Module> findAll(Context ctx) { List<Module> result = new ArrayList<Module>(); DatabaseHelper helper = new DatabaseHelper(ctx); sqliteDatabase db = helper.getReadableDatabase(); Cursor c = db.query(ModuleDB.table_name, new String[] { ModuleDB.ID, ModuleDB.MODulE}, null, null, null, null, null); while (c.movetoNext()) { Module m = new Module(c.getInt(0), c.getString(1)); result.add(m); } c.close(); db.close(); return result; } // Update Database entry public static voID update(Context ctx, Module m) { DatabaseHelper helper = new DatabaseHelper(ctx); sqliteDatabase db = helper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("_ID", m.get_ID()); values.put("name", m.getModule()); db.update("module", values, null, null); db.close(); } public static voID delete(Context ctx, Module m) { DatabaseHelper helper = new DatabaseHelper(ctx); sqliteDatabase db = helper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("_ID", m.get_ID()); values.put("name", m.getModule()); db.delete("module","_ID = m.get_ID()", null); db.close(); } public static voID createDB(Context ctx) { DatabaseHelper helper = new DatabaseHelper(ctx); sqliteDatabase db = helper.getWritableDatabase(); db.close(); }}
为了提高效率,方法是静态的,您无需创建对象.
像这样使用它:在您的活动中
protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // get the a writable DB, in case it's not existing it gets created. DataHandlerDB.createDB(this); // get stuff out of DB moduleList = DataHandlerDB.findAll(this); adapter = new ArrayAdapter<Module>(this, androID.R.layout.simple_List_item_1, moduleList); setlistadapter(adapter);}
总结 以上是内存溢出为你收集整理的java-在数据库上未显式调用close()全部内容,希望文章能够帮你解决java-在数据库上未显式调用close()所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)