微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Android和SQlite中从不显式调用close()

我在stackoverflow上看了很多关于这个错误的帖子,看起来修复是在重写onDestroy()方法关闭数据库.但这似乎不适用于我的情况.当Eclipse最初在我的手机上运行应用程序时,我实际上没有收到任何错误,但当我关闭应用程序并在我的手机上重新启动它时 – 就是在LogCat中从未在数据库显示上显式调用close()时.我正在调用我的资产文件夹中的外部数据库,不确定它是否与它有关.

将对DBAdapter:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlException;
import android.database.sqlite.sqliteDatabase;
import android.database.sqlite.sqliteException;
import android.database.sqlite.sqliteOpenHelper;

public class DBAdapter extends sqliteOpenHelper {

public static final String KEY_ROWID = "_id";
public static final String KEY_HDATE = "date";
public static final String KEY_MONTHDAY = "monthday";
public static final String KEY_YEAR = "year";
public static final String KEY_HD = "happened";

// The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.vdm.whtt/databases/";
private static String DB_NAME = "wht.db";
private static final String DB_TABLE = "historydaytable";

private sqliteDatabase db;

private final Context ourContext;

public DBAdapter(Context context) {
    super(context,DB_NAME,null,1);
    this.ourContext = context;
}

public void createDataBase() throws IOException {

    boolean dbExist = checkDataBase();

    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");

        }
    }

}

private boolean checkDataBase() {
    sqliteDatabase checkDB = null;

    try {
        String myPath = DB_PATH + DB_NAME;
        checkDB = sqliteDatabase.openDatabase(myPath,sqliteDatabase.OPEN_READONLY);
    } catch (sqliteException e) {
        // database does't exist yet.
    }

    if (checkDB != null) {
        checkDB.close();
    }

    return checkDB != null ? true : false;
}

private void copyDataBase() throws IOException {
    InputStream myInput = ourContext.getAssets().open(DB_NAME);
    String outFileName = DB_PATH + DB_NAME;
    OutputStream myOutput = new FileOutputStream(outFileName);

    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer,length);
    }

    myOutput.flush();
    myOutput.close();
    myInput.close();
}

public void open() throws sqlException {
    String myPath = DB_PATH + DB_NAME;
    db = sqliteDatabase.openDatabase(myPath,sqliteDatabase.OPEN_READONLY);
}

@Override
public synchronized void close() {
    if (db != null)
        db.close();
    super.close();
}

@Override
public void onCreate(sqliteDatabase db) {
}

@Override
public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) {
    db.execsql("DROP TABLE IF EXISTS " + DB_TABLE);
    onCreate(db);
}

public String[] getTH(long aLong) { 
    String[] columns = new String[] { KEY_YEAR,KEY_MONTHDAY,KEY_HD };
    Cursor cursor = db.query(DB_TABLE,columns,KEY_HDATE + "=" + aLong,null);

    if (cursor != null) {
        cursor.movetoFirst();
        String hpToday[] = new String[3];
        hapToday[0] = cursor.getString(0);
        hapToday[1] = cursor.getString(1);
        hapToday[2] = cursor.getString(2);
        cursor.close();
        this.db.close();
        return hpToday;
    }
    return null;
}

public String[] getFirstRandomAnswer(int randomNum1) {
    String[] columns = new String[] { KEY_YEAR,null);
    if (cursor != null) {
        cursor.movetoPosition(randomNum1);
        String r1Str[] = new String[3];
        r1Str[0] = cursor.getString(0);
        r1Str[1] = cursor.getString(1);
        r1Str[2] = cursor.getString(2);
        cursor.close();
        this.db.close();
        return r1Str;
    }
    return null;
}

public String[] getSecondRandomAnswer(int randomNum2) {
    String[] columns = new String[] { KEY_YEAR,null);
    if (cursor != null) {
        cursor.movetoPosition(randomNum2);
        String r2Str[] = new String[3];
        r2Str[0] = cursor.getString(0);
        r2Str[1] = cursor.getString(1);
        r2Str[2] = cursor.getString(2);
        cursor.close();
        this.db.close();
        return r2Str;
    }
    return null;
}
}

主要活动:

    import java.io.IOException;
import java.util.Locale;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;
import android.app.Activity;
import android.database.sqlException;

public class MainActivity extends Activity {
private DBAdapter dba;
TextView hiddenDBdatetv,todayIstv,optionAtv;
String Mmdstr;
String[] todayArray;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    hiddenDBdatetv = (TextView) findViewById(R.id.hiddenDBdate_TV);
    todayIstv = (TextView) findViewById(R.id.todayIs_TV);
    optionAtv = (TextView) findViewById(R.id.optionA_TV);

    dba = new DBAdapter(this);

    try {
        dba.createDataBase();
    } catch (IOException ioe) {
        throw new Error("Unable to create database");
    }
    try {
        dba.open();
    } catch (sqlException sqle) {
        throw sqle;
    }

    getMMdDate();
    getTH();
}

private void getMMdDate() {
    Date anotherCurDate = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("MMd",Locale.US);
    Mmdstr = formatter.format(anotherCurDate);
    SimpleDateFormat dateFormat = new SimpleDateFormat("MMd");
    Date myDate = null;
    try {
        myDate = dateFormat.parse(Mmdstr);
    } catch (ParseException e) {
        e.printstacktrace();
    }
    SimpleDateFormat timeFormat = new SimpleDateFormat("MMMMMMMMMM d");
    String finalDate = timeFormat.format(myDate);
}

private void getTH() {
    long aLong = Long.parseLong(Mmdstr);
    dba.open();
    todayArray = dba.getTH(aLong);
    dba.close();
    optionAtv.setText(todayArray[2]);
}

@Override
protected void onDestroy() {
    dba.close();
    super.onDestroy();
}

}
最佳答案
您将在createDatabase()中保留一个打开的数据库(当dbExist == false时),并且您在onCreate()中再次打开数据库,然后在getTH()中再次打开数据库

避免此错误的诀窍是在数据库已经打开时进行跟踪,并确保在完成数据库使用后将其关闭.如果您发现自己多次打开数据库,请在尝试打开数据库之前检查isOpen().

原文地址:https://www.jb51.cc/android/430736.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐