Java - Android SQLite没有这样的表存在

时间:2013-01-08 12:41:50

标签: android sqlite cursor android-cursor

我正在创建一个会查询数据库的应用程序,但无法检测到这些表。

我已按照此博客中指出的步骤进行操作:http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

我制作了android_metadata表,将其复制到assets文件夹,并创建了DataBaseHelper类,如下所示:

public class DataBaseHelper extends SQLiteOpenHelper{
private static final String MedicalStaff = null;
private static final String Patients = null;

//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.angelo.thesis/databases/";

private static String DB_NAME = "androidHospital";

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");
            System.out.println("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(){

    SQLiteDatabase checkDB = null;

    try{
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }catch(SQLiteException e){

        //database does't exist yet.

    }

    if(checkDB != null){

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

/**
 * 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) {

}

}

然后使用:

初始化此数据库助手
DataBaseHelper myDbHelper = new DataBaseHelper(null);

onCreate方法中:

myDbHelper = new DataBaseHelper(this);

    try {
        myDbHelper.createDataBase();
        System.out.println("Database Created!");
    } 
    catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("Unable to create database");
    }


    try {
        myDbHelper.openDataBase();
        System.out.println("Database Opened!");
    } 
    catch (SQLException e) {
        // TODO Auto-generated catch block
        System.out.println("Unable to open database");
    }

try-catch语句有效,LogCat显示已创建和已打开的消息。

然后通过此函数进行查询: 字符串输入是用户输入,用于查找与该号码对应的人员的数字。

public String searchStaff(DataBaseHelper myDB, String input){

    System.out.println("searchStaff entered");

    String data = null;
    Cursor cursor = null;
    SQLiteDatabase db = myDB.getReadableDatabase();

    //int myNum = Integer.parseInt(input);

    try{
        cursor = db.rawQuery("SELECT LastName, FirstName FROM MedicalStaff WHERE _id =" + input, null);

    }   
    catch(Exception e){
    }

    if( cursor != null ){
        cursor.moveToFirst();

        data = cursor.getString(cursor.getColumnIndexOrThrow("LastName")) + " " +
                cursor.getString(cursor.getColumnIndex("FirstName"));   
        cursor.close();
    }

    System.out.println("Data: " + data);
    return data;

}

但是,显示的数据变为null,Log Cat告诉我表MedicalStaff不存在。

我有一种感觉,我错过了一些非常基本的东西。 谢谢你的帮助。

4 个答案:

答案 0 :(得分:2)

更改此行代码

`DataBaseHelper myDbHelper = new DataBaseHelper(null);

DataBaseHelper myDbHelper = new DataBaseHelper(this);

这是因为您使用null创建Databasehelper对象。所以用指定的上下文创建。

答案 1 :(得分:1)

我认为数据库已成功创建。但表创建未完成。请检查..

答案 2 :(得分:0)

更改此行代码

DataBaseHelper myDbHelper = new DataBaseHelper(null);

DataBaseHelper myDbHelper;

如果初始化DataBaseHelper传递null作为参数,那么Database Helper将不会获得Context并将导致您现在面临的意外行为。所以改变你的代码,并尝试。希望它适合你。

答案 3 :(得分:0)

new DataBaseHelper(null);看起来不太好。您应该使用有效的上下文

对其进行初始化