2013-01-08 4 views
0

데이터베이스를 쿼리 할 수있는 앱을 만들고 있지만 테이블을 찾을 수 없습니다. 아래 그림과 같이Java - Android SQLite 테이블이 존재하지 않습니다.

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/ 내가의 android_metadata 테이블을 만든 자산 폴더에 복사하고, 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 문이 작업의 로그 캣 표시 생성과 메시지를 개설.

그런 다음이 함수가 쿼리를 작성합니다. 문자열 입력은 사용자 입력이며 해당 숫자에 해당하는 사람을 찾는 데 사용되는 숫자입니다.

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되고 로그인 고양이 테이블 MedicalStaff이 존재하지 않음을 알려줍니다.

나는 여기에서 아주 기본적인 것을 놓치고 있다고 느낍니다. 도움 주셔서 감사합니다.

답변

2

변경

`DataBaseHelper myDbHelper = new DataBaseHelper(null);

코드

이 줄을 초기화해야한다. 따라서 지정된 컨텍스트로 작성하십시오.

+0

여전히 같은 오류가 나타납니다. – Razgriz

+0

@Razgriz는 sqlite 데이터베이스 브라우저에서 해당 테이블로 데이터베이스가 생성되었는지 여부를 확인했습니다. 데이터베이스 객체를 두 번 초기화하지 않았는지 확인하십시오. – GoCrazy

+0

예 작성되었습니다. 나는 또한 다른 테이블을 쿼리하려고했지만 찾을 수없는 것 같습니다. – Razgriz

0

변경이 코드 줄

DataBaseHelper myDbHelper = new DataBaseHelper(null); 

DataBaseHelper myDbHelper; 

당신이 DataBaseHelper 당신이 직면하고있는로 데이터베이스 도우미 문맥을받지 않습니다 및 예기치 않은 동작이 발생합니다, 다음 매개 변수로 null을 전달 초기화 할 경우

에 지금. 그래서 위와 같이 코드를 변경하고 시도하십시오. 희망이 당신을 위해 작동합니다.

0

new DataBaseHelper(null); 잘 보이지 않습니다. 당신은 당신이 널 (null)과 Databasehelper 객체를 생성하기 때문이다

DataBaseHelper myDbHelper = new DataBaseHelper(this);

에 유효한 컨텍스트

1

데이터베이스가 성공적으로 생성되었다고 생각합니다.하지만 테이블 생성이 완료되지 않았습니다. 확인하십시오.

+0

어떻게 확인하나요? – Razgriz

+0

@Razgiz http://developer.android.com/tools/help/adb.html#sqlite –

+0

에서 원격 셸의 sqlite3 데이터베이스 검사를 읽어보십시오. 그것을 읽을 것입니다. 고맙습니다. – Razgriz

관련 문제