Android的 - 无法打开数据库 [英] Android - Could not open database

查看:179
本文介绍了Android的 - 无法打开数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在资产文件夹我的 db.sqlite 文件,当我试图打开我得到这个错误它:


  

android.database.sqlite.SQLiteCantOpenDatabaseException:未知
  错误(code 14):无法打开数据库


我已经尝试了不同的路径和名称(带和不带扩展名),但我不能使它工作。

 包com.example.APP.db;进口的java.io.File;
进口java.io.FileOutputStream中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.OutputStream中;进口android.content.Context;
进口android.database.SQLException;
进口android.database.sqlite.SQLiteDatabase;
进口android.database.sqlite.SQLiteException;
进口android.database.sqlite.SQLiteOpenHelper;
进口android.widget.Toast;公共类DataBaseHelper扩展SQLiteOpenHelper {//你的应用程序数据库的Andr​​oid的默认系统路径。
私人静态字符串DB_PATH =/data/data/com.example.APP/databases/;
私人静态字符串DB_NAME =应用程序;
私人SQLiteDatabase MYDATABASE;
私人最终上下文myContext;/ **
 *构造函数和不断传递的上下文中的一个参考,以
 *访问应用程序的资产和资源。
 *
 * @参数方面
 * /
公共DataBaseHelper(上下文的背景下){
    超级(上下文,DB_NAME,空,1);
    this.myContext =背景;
}/ **
 *在系统上创建一个空数据库,然后用自己的重写它
 *数据库。
 * * /
公共无效的CreateDatabase()抛出IOException
    布尔dbExist = checkDataBase();    如果(dbExist){
        //什么也不做 - 已存在于数据库
    }其他{        //通过调用此方法与空的数据库将被创建成
        //默认的系统路径
        //你的应用程序,所以我们要能够覆盖
        //数据库与我们的数据库。
        this.getReadableDatabase();
        尝试{
            copyDataBase();
        }赶上(IOException异常五){
            抛出新的错误(错误复制数据库);
        }
    }
}/ **
 *检查是否已存在于数据库,以避免重新复制每个文件
 *一次打开应用程序。
 *
 *如果存在返回:真的,假的,如果它不
 * /
 私人布尔checkDataBase(){
        布尔CHECKDB = FALSE;
        尝试{
            字符串mypath中= myContext.getFilesDir()getAbsolutePath()代替(文件,数据库)+文件分割符+ DB_NAME。;
            文件DBFILE =新的文件(mypath中);
            CHECKDB = dbfile.exists();
        }
        赶上(SQLiteException E){
            的System.out.println(数据库不存在);
        }        返回CHECKDB;
    }/ **
 *副本数据库从本地资产文件夹复制到刚创建
 *在系统文件夹,空数据库从那里可以访问和
 *处理。这是通过转流的字节流进行。
 * * /
私人无效copyDataBase()抛出IOException    //打开本地数据库的输入流
    InputStream的myInput = myContext.getAssets()开(DB_NAME)。    //路径刚刚创建的空分贝
    字符串outFileName = DB_PATH + DB_NAME;    //打开空分贝的输出流
    的OutputStream myOutput =新的FileOutputStream(outFileName);    //传递从inputfile中字节到OUTPUTFILE
    字节[]缓冲区=新的字节[1024];
    INT长;
    而((长度= myInput.read(缓冲液))大于0){
        myOutput.write(缓冲液,0,长度);
    }    //关闭流
    myOutput.flush();
    myOutput.close();
    myInput.close();
} 公共无效的openDatabase()抛出的SQLException {    //打开数据库
    字符串mypath中= DB_PATH + DB_NAME;
    MYDATABASE = SQLiteDatabase.openDatabase(mypath中,空,SQLiteDatabase.OPEN_READONLY);    }@覆盖
公共同步无效的close(){    如果(MYDATABASE!= NULL)
        myDataBase.close();    super.close();}@覆盖
公共无效的onCreate(SQLiteDatabase DB){}@覆盖
公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){}
}

我得到的错误,当我尝试在这里打开它:

 包com.example.APP;进口android.app.Activity;
进口android.os.Bundle;
进口android.widget.TextView;
进口com.example.APP.db.DataBaseHelper;
公共类SpeakersListActivity延伸活动{公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.mylayout);    DataBaseHelper dbHelper =新DataBaseHelper(本);
    dbHelper.openDataBase();
}
}


解决方案

您需要检查数据库文件第一,你没有做这里的存在

  DataBaseHelper dbHelper =新DataBaseHelper(本);
dbHelper.openDataBase();

你只是做DataBaseHelper的对象,然后调用.openDataBase()

试试这个构造:

 公共DataBaseHelper(上下文的背景下){
    超级(上下文,DB_NAME,空,1);
   this.myContext =背景;
   尝试{
        字符串mypath中= DB_PATH + DB_NAME; //还要检查你的扩展数据库文件
        文件DBFILE =新的文件(mypath中);
            如果(dbfile.exists());
             Toast.makeText(背景下,数据库中不存在,Toast.LENGTH_LONG).show();
            其他
             Toast.makeText(背景下,不能找到数据库,Toast.LENGTH_LONG).show();
        }
        赶上(SQLiteException E){
            的System.out.println(数据库不存在);
        }}

I have my db.sqlite file in the Asset folder and I get this error when I try to open it:

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

I've tried different paths and names (with and without the extension) but I can't make it work.

package com.example.APP.db;

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

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

public class DataBaseHelper extends SQLiteOpenHelper {

// The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.example.APP/databases/";
private static String DB_NAME = "app";
private SQLiteDatabase myDataBase;
private final Context myContext;

/**
 * Constructor Takes and keeps a reference of the passed context in order to
 * access to the application assets and resources.
 * 
 * @param context
 */
public DataBaseHelper(Context context) {
    super(context, DB_NAME, null, 1);
    this.myContext = context;
}

/**
 * Creates a empty database on the system and rewrites it with your own
 * database.
 * */
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");
        }
    }
}

/**
 * Check if the database already exist to avoid re-copying the file each
 * time you open the application.
 * 
 * @return true if it exists, false if it doesn't
 */
 private boolean checkDataBase(){
        boolean checkdb = false;
        try{
            String myPath = myContext.getFilesDir().getAbsolutePath().replace("files", "databases")+File.separator + DB_NAME;
            File dbfile = new File(myPath);                
            checkdb = dbfile.exists();
        }
        catch(SQLiteException e){
            System.out.println("Database doesn't exist");
        }

        return checkdb;
    }

/**
 * Copies your database from your local assets-folder to the just created
 * empty database in the system folder, from where it can be accessed and
 * handled. This is done by transfering bytestream.
 * */
private void copyDataBase() throws IOException {

    // Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
}

 public void openDataBase() throws SQLException{

    //Open the database
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }

@Override
public synchronized void close() {

    if (myDataBase != null)
        myDataBase.close();

    super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
}

I get the error when I try to open it here:

package com.example.APP;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.example.APP.db.DataBaseHelper;


public class SpeakersListActivity extends Activity {

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mylayout);      

    DataBaseHelper dbHelper = new DataBaseHelper(this);
    dbHelper.openDataBase();
}
}

解决方案

you need to check the existence of the database file first which you are not doing here

DataBaseHelper dbHelper = new DataBaseHelper(this);
dbHelper.openDataBase();

you are simply making an object of DataBaseHelper and then calling .openDataBase()

try this constructor :

public DataBaseHelper(Context context) {
    super(context, DB_NAME, null, 1);
   this.myContext = context;
   try{
        String myPath = DB_PATH + DB_NAME; // also check the extension of you db file 
        File dbfile = new File(myPath);                
            if( dbfile.exists());
             Toast.makeText(context, "database exists", Toast.LENGTH_LONG).show();
            else
             Toast.makeText(context, "cant find database", Toast.LENGTH_LONG).show();
        }
        catch(SQLiteException e){
            System.out.println("Database doesn't exist");
        }

}

这篇关于Android的 - 无法打开数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆