마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

안드로이드 SQLite no such table 오류

0 추천
public class DataBaseHelper extends SQLiteOpenHelper {

    private static String DB_PATH = Environment.getDataDirectory().getAbsolutePath() + "/data/패키지명/" ;
    private static String DB_NAME = "member.db";
    private static final int DB_VERSION  = 40;
    private static final String SP_KEY_DB_VER = "db_ver";
    private SQLiteDatabase myDataBase;
    private final Context myContext;
    public DataBaseHelper(Context context)
    {
        super(context, DB_NAME, null, DB_VERSION);
        this.myContext=context;
    }


    public void createDataBase() throws IOException
    {
        boolean dbExist = checkDataBase();
        if(dbExist)
        {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(myContext);
            int dbVersion = prefs.getInt(SP_KEY_DB_VER, 18);
            if (DB_VERSION != dbVersion)
            {
                File dbFile = myContext.getDatabasePath(DB_PATH+DB_NAME);
                if (!dbFile.delete()) {

                }
                this.getReadableDatabase();
                try {
                    copyDataBase();

                }
                catch (IOException e) {
                    //throw new Error("Error copying database");

                }
            }
            //do nothing - database already exist
            else {
                //  Toast.makeText(myContext, "DB媛� 媛숇꽕�슂", Toast.LENGTH_SHORT).show();
            }
        }
        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");

            }
        }

        // Shareprerece �뿉 DB 踰꾩쟾 �엯�젰�빐�꽌 李⑦썑 DB�� 鍮꾧탳�븯湲� �쐞�빐
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(myContext);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(SP_KEY_DB_VER, DB_VERSION);
        editor.commit();
    }
    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;
    }
    private void copyDataBase() throws IOException {
        //Open your local db as the input stream
      //  SQLiteDatabase dbe = SQLiteDatabase.openDatabase("/data/data/패키지명/member.db",null, 0);
        InputStream myInput = myContext.getAssets().open(Environment.getDataDirectory().getAbsolutePath() + "/data/패키지명" + "/member.db");
        // 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)
    {
        try {
            copyDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
DataBaseHelper라는 클래스를 생성하여 DB를 불러옵니다. 

로그캣 입니다.
android.database.sqlite.SQLiteException: no such table: tb_member (code 1): , while compiling: select * from tb_member where name like '%ㅛ%'
                                                                       at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                       at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                       at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                       at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                       at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                       at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
                                                                       at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                                                                       at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1318)
                                                                       at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1257)
                                                                       at com.fecsen.deiceo.MemberSearchActivity.selectDB(MemberSearchActivity.java:174)
                                                                       at com.fecsen.deiceo.MemberSearchActivity.access$000(MemberSearchActivity.java:37)
                                                                       at com.fecsen.deiceo.MemberSearchActivity$2.onClick(MemberSearchActivity.java:111)
                                                                       at android.view.View.performClick(View.java:5637)
                                                                       at android.view.View$PerformClick.run(View.java:22429)
                                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
꼭 부탁드립니다 ~!!
익명사용자 님이 2018년 2월 18일 질문
private void selectDB(String srch_query) {

        db_search = myDbHelper_search.getReadableDatabase();
        query_search="select * from tb_member where name like '%"+srch_query.toString()+"%'";
        cursor_search = db_search.rawQuery(query_search, null);
        DBAdapter_search dbadapter_search= new DBAdapter_search(this,cursor_search);
        //    dbadapter_search.changeCursor(cursor_search);


        if(cursor_search.getCount()>0)
        {

            startManagingCursor(cursor_search);

            listview_search = (ListView)this.findViewById(R.id.lv_search);
            listview_search.setAdapter(dbadapter_search);
            tv_numberoflist.setText("검색하신 결과는 총"+cursor_search.getCount()+"명 입니다.");

        }
        else
        {
            startManagingCursor(cursor_search);

            listview_search = (ListView)this.findViewById(R.id.lv_search);
            listview_search.setAdapter(dbadapter_search);
            tv_numberoflist.setText("검색하신 결과는 총"+cursor_search.getCount()+"명 입니다.");

        }


    }

제일 문제되는것으로 판단되는 메소드입니다... 더 필요하시면 댓글 남겨주세요 !!!

1개의 답변

0 추천
오류 로그는 at com.fecsen.deiceo.MemberSearchActivity.selectDB(MemberSearchActivity.java:174)

부분에 나오듯 tb_member 라는 table을 못 찾아서 나왔습니다.

아무래도  올려주신 코드 중 copyDataBase() 뷰분의   입력 path와 출력 path가 동일해서, 첫 1024 byte만 제대로 적고, 의도하지 않는 동작을 한 듯 합니다.

복사 위치를 조정해 보세요..
익명사용자 님이 2018년 2월 19일 답변
...