0

cursor = execQuery("SELECT " + COL_DISORDER_NAME + " FROM " + TBL_DISORDERLIST);ステートメントを実行すると、データベースが開いていないことがログ猫に表示されます。私を助けてください。データベースからデータを取得するにはどうすればよいですか?

ありがとうございます

 public class DBHelper extends SQLiteOpenHelper {

    public static String DB_PATH = "";
    public static final String DB_NAME = "braindatabse.db";
    public static final int DB_VERSION = 1;
    public static final String TBL_DISORDERLIST = "disorderlist";

    public static final String COL_ROWID = "_id";
    public static final String COL_DISORDER_NAME = "disordername";
    public static final String COL_NICK_NAME = "nickname";
    public static final String COL_DESCRIPTION = "description";
    public static final String COL_TREATMENT = "treatment";
    public static final String COL_PROGNOSIS = "prognosis";

    public static SQLiteDatabase myDataBase;
    public final Context myContext;

    public static DBHelper mDBConnection;

    /**
     * Constructor Takes and keeps a reference of the passed context in order to
     * access to the application assets and resources.
     * 
     * @param context
     */
     public DBHelper(Context context) {
            super(context, DB_NAME, null, 1);
            if(myDataBase != null && myDataBase.isOpen())
                close();
            this.myContext = context;
            DB_PATH = "/data/data/"
                    + context.getApplicationContext().getPackageName()
                    + "/databases/";
            // The Android's default system path of your application database is
            // "/data/data/mypackagename/databases/"
            try{
                createDataBase();
                openDataBase();
            }catch(IOException e){
                Log.i("db","Exception in creation of database : " + e.getMessage());
                e.printStackTrace();
            }
        }

     /**
         * Creates an empty database on the system and rewrites it with your own database.
         **/
        public void createDataBase() throws IOException {
            boolean dbExist = checkDataBase();
            Log.d("db", "creating db");
            if(!dbExist)
            {
                this.getReadableDatabase();
                try 
                {
                    //Copy the database from assests
                    copyDataBase();
                    Log.e("Err", "createDatabase database created");
                } 
                catch (IOException mIOException) 
                {
                    throw new Error("ErrorCopyingDataBase");
                }
            }
        }

        /**
         * 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 static boolean checkDataBase() {
            /* File dbFile = new File(DB_PATH + DB_NAME);
             Log.d("db", "dbFile exists");
             return dbFile.exists();*/

          SQLiteDatabase checkDB = null;
            try {
                String myPath = DB_PATH + DB_NAME;
                checkDB = SQLiteDatabase.openDatabase(myPath, null,
                        SQLiteDatabase.OPEN_READONLY);
                Log.d("db", "db exists");

            } catch (SQLiteException e) {
                // database does't exist yet.
            }
            if (checkDB != null) {
                checkDB.close();
            }
            return checkDB != null ? true : false;
        }

        /**
         * getting Instance
         * @param context
         * @return DBAdapter
         */
        public static synchronized DBHelper getDBAdapterInstance(Context context) {
            if (mDBConnection == null) {
                mDBConnection = new DBHelper(context);
            }
            return mDBConnection;
        }

        /**
         * 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();
            Log.d("db", "database copied");
        }

        /**
         * Open the database
         * @throws SQLException
         */
        public static void openDataBase() throws SQLException {
            String myPath = DB_PATH + DB_NAME;
            myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
            Log.d("db", "databse open");
        }


        public boolean isOpen()
        {
            if(myDataBase != null)
                return myDataBase.isOpen();

            return false;
        }

        public synchronized static void execNonQuery(String sql)
        {
            try
            {
                myDataBase.execSQL(sql);
                //Log.d("SQL", sql);
            }
            catch ( Exception e )
            {
                Log.e("Err", e.getMessage());
            }
            finally
            {
                // closeDb();
            }
        }

        public synchronized static Cursor execQuery(String sql)
        {
            Cursor cursor = null;
            {
                try 
                {
                cursor = myDataBase.rawQuery(sql, null);
                //Log.d("SQL", sql);
            }
            catch(Exception e)
            {
                Log.e("Err", "database not open");
            }
            }
            return cursor;
        }

        /**
         * Close the database if exist
         */
        @Override
        public synchronized void close() {
            if (myDataBase != null)
                myDataBase.close();
            super.close();
        }



    /**
     * Call on creating data base for example for creating tables at run time
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    /**
     * can used for drop tables then call onCreate(db) function to create tables
     * again - upgrade
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    // ----------------------- CRUD Functions ------------------------------

        /**
         * This function used to select the records from DB.
         * @param tableName
         * @param tableColumns
         * @param whereClase
         * @param whereArgs
         * @param groupBy
         * @param having
         * @param orderBy
         * @return A Cursor object, which is positioned before the first entry.
         */
        public Cursor selectRecordsFromDB(String tableName, String[] tableColumns,
                String whereClase, String whereArgs[], String groupBy,
                String having, String orderBy) {
            return myDataBase.query(tableName, tableColumns, whereClase, whereArgs,
                    groupBy, having, orderBy);
        }

        public static List<Dboutput> readAll()
        {
            Cursor cursor =null;

            try
            {
                List<Dboutput> all = new ArrayList<Dboutput>();

                cursor = execQuery("SELECT " + COL_DISORDER_NAME + " FROM " + TBL_DISORDERLIST); // when this statement executes it shows error database not open

                if(cursor.getCount() > 0)
                {
                    int idIndex = cursor.getColumnIndex(COL_ROWID);
                    int nameIndex = cursor.getColumnIndex(COL_DISORDER_NAME);
                    int nicknameIndex = cursor.getColumnIndex(COL_NICK_NAME);
                    int descriptionIndex = cursor.getColumnIndex(COL_DESCRIPTION);
                    int treatmentIndex = cursor.getColumnIndex(COL_TREATMENT);
                    int prognosisIndex = cursor.getColumnIndex(COL_PROGNOSIS);
                    cursor.moveToFirst();
                    do
                    {
                        int id = cursor.getInt(idIndex);
                        String disorder_name = cursor.getString(nameIndex);
                        String nickname = cursor.getString(nicknameIndex);
                        String description = cursor.getString(descriptionIndex);
                        String treatment = cursor.getString(treatmentIndex);
                        String prognosis = cursor.getString(prognosisIndex);

                        Dboutput out = new Dboutput();
                        out.setId(id);
                        out.setdisorder_name(disorder_name);
                        out.setnick_name(nickname);
                        out.setdescription(description);
                        out.settreatment(treatment);
                        out.setprognosis(prognosis);

                        all.add(out);

                        cursor.moveToNext();
                    }while(!cursor.isAfterLast());
                }

                return (List<Dboutput>) all;
            }
            finally
            {
                if(cursor != null)
                {
                    cursor.close();
                }
            }
        }
4

2 に答える 2

0

createDataBase()データベースが存在しないのに、なぜフォローインをしているのですか?

boolean dbExist = checkDataBase();
if(!dbExist)
{
    this.getReadableDatabase();
    ...
于 2012-07-24T10:56:55.560 に答える
0

データベースにクエリを実行する前に、データベースを開く必要があります

dataBaseHelper = new DataBaseHelper(context);
    try {
        dataBaseHelper.createDataBase();
        dataBaseHelper.openDataBase();
    } catch (Exception e) {
        e.printStackTrace();
}

ここdataBaseHelperにクラスがDBHelperあり、他のことは、を使用してカーソルを最初の位置に移動する必要があるということです

cursor.moveToFirst();

破棄するには、を使用してデータベースを閉じる必要がありますdataBaseHelper.close();

于 2012-07-24T11:09:13.553 に答える