Error opening the Android studio database

1

I'm doing an application where I use a database. I miss this error

02-17 02:25:56.504 21955-21955/dev.mros.espanyaapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{dev.mros.espanyaapp/dev.mros.espanyaapp.Done}: android.database.sqlite.SQLiteException: no such table: Ranking (code 1): , while compiling: INSERT INTO Ranking(Score) VALUES(Infinity)
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
                                                                     at android.app.ActivityThread.access$700(ActivityThread.java:159)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                     at android.os.Looper.loop(Looper.java:176)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5419)
                                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                                     at java.lang.reflect.Method.invoke(Method.java:525)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
                                                                     at dalvik.system.NativeStart.main(Native Method)
                                                                  Caused by: android.database.sqlite.SQLiteException: no such table: Ranking (code 1): , while compiling: INSERT INTO Ranking(Score) VALUES(Infinity)
                                                                     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1118)
                                                                     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:691)
                                                                     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                     at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1794)
                                                                     at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1725)
                                                                     at dev.mros.espanyaapp.DbHelper.DbHelper.insertScore(DbHelper.java:197)
                                                                     at dev.mros.espanyaapp.Done.onCreate(Done.java:89)
                                                                     at android.app.Activity.performCreate(Activity.java:5372)
                                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349) 
                                                                     at android.app.ActivityThread.access$700(ActivityThread.java:159) 
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316) 
                                                                     at android.os.Handler.dispatchMessage(Handler.java:99) 
                                                                     at android.os.Looper.loop(Looper.java:176) 
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5419) 
                                                                     at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                     at java.lang.reflect.Method.invoke(Method.java:525) 
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046) 
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862) 
                                                                     at dalvik.system.NativeStart.main(Native Method) 

I can not solve it because this has never happened to me. I miss the error in this method

    public void openDataBase() {
    String myPath = DB_PATH + DB_NAME;
    mDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}

I leave here my database

    public class DbHelper extends SQLiteOpenHelper {

    private static String DB_NAME = "MyDB.db";
    private static String DB_PATH = "";
    private SQLiteDatabase mDataBase;
    private Context mContext = null;

    public DbHelper(Context context) {
        super(context, DB_NAME, null, 1);

        DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
        File file = new File(DB_PATH+"MyDB.db");
        if(file.exists())
            openDataBase();
        this.mContext = context;

    }

    public void openDataBase() {
        String myPath = DB_PATH + DB_NAME;
        mDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    }

    public void copyDataBase() throws IOException {
        try {
            InputStream myInput = mContext.getAssets().open(DB_NAME);
            String outputFileName = DB_PATH + DB_NAME;
            OutputStream myOutput = new FileOutputStream(outputFileName);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0)
                myOutput.write(buffer, 0, length);

            myOutput.flush();
            myOutput.close();
            myInput.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean checkDataBase() {
        SQLiteDatabase tempDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            tempDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
        if (tempDB != null)
            tempDB.close();
        return tempDB != null ? true : false;
    }

    public void createDataBase() throws IOException {
        boolean isDBExists = checkDataBase();
        if (isDBExists) {

        } else {
            this.getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    @Override
    public void onCreate(SQLiteDatabase db) {

    }

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

    }

    //Question (PREGUNTA) *BASE DE DATOS*
    public List<Question> getAllQuestion() {
        List<Question> listQuestion = new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor c;
        try {
            c = db.rawQuery("SELECT * FROM Question ORDER BY Random()", null);
            if (c == null) return null;
            c.moveToFirst();
            do {
                int Id = c.getInt(c.getColumnIndex(mContext.getString(R.string.IDdb)));
                String Image = c.getString(c.getColumnIndex(mContext.getString(R.string.IMAGEdb)));
                String AnswerA = c.getString(c.getColumnIndex(mContext.getString(R.string.ANSWERAdb)));
                String AnswerB = c.getString(c.getColumnIndex(mContext.getString(R.string.ANSWERBdb)));
                String AnswerC = c.getString(c.getColumnIndex(mContext.getString(R.string.ANSWERCdb)));
                String AnswerD = c.getString(c.getColumnIndex(mContext.getString(R.string.ANSWERDdb)));
                String CorrectAnswer = c.getString(c.getColumnIndex(mContext.getString(R.string.CorrectAnswerdb)));

                Question question = new Question(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
                listQuestion.add(question);
            }
            while (c.moveToNext());
            c.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        db.close();
        return listQuestion;
    }

    //Tipos de NIVELES
    public List<Question> getQuestionMode(String mode) {
        List<Question> listQuestion = new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor c;
        int limit = 0;
        if (mode.equals(Common.MODE.FACIL.toString()))
            limit = 6;
        else if (mode.equals(Common.MODE.MEDIO.toString()))
            limit = 12;
        else if (mode.equals(Common.MODE.DIFICIL.toString()))
            limit = 27;
        else if (mode.equals(Common.MODE.DIFICILISOMO.toString()))
            limit = 50;
        try {
            c = db.rawQuery(String.format("SELECT * FROM Question ORDER BY Random() LIMIT %d", limit), null);
            if (c == null) return null;
            c.moveToFirst();
            do {
                int Id = c.getInt(c.getColumnIndex(mContext.getString(R.string.ID2db)));
                String Image = c.getString(c.getColumnIndex(mContext.getString(R.string.IMAGE2db)));
                String AnswerA = c.getString(c.getColumnIndex(mContext.getString(R.string.ANSWER2db)));
                String AnswerB = c.getString(c.getColumnIndex(mContext.getString(R.string.ANSWERB2db)));
                String AnswerC = c.getString(c.getColumnIndex(mContext.getString(R.string.ANSWERC2db)));
                String AnswerD = c.getString(c.getColumnIndex(mContext.getString(R.string.ANSWERD2db)));
                String CorrectAnswer = c.getString(c.getColumnIndex(mContext.getString(R.string.CorrectAnswer2db)));

                Question question = new Question(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
                listQuestion.add(question);
            }
            while (c.moveToNext());
            c.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        db.close();
        return listQuestion;
    }

    //Un insert para el RANKING
    public void insertScore(double score) {
        String query = "INSERT INTO Ranking(Score) VALUES("+score+")";
        mDataBase.execSQL(query);
    }

    public void updatePlayCount(int level,int playCount)
    {
        String query = String.format("UPDATE UserPlayCount Set PlayCount = %d WHERE Level = %d",playCount,level);
        mDataBase.execSQL(query);
    }

    public int getPlayCount(int level)
    {
        int result = 0;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c;
        try{
            c = db.rawQuery("SELECT PlayCount FROM UserPlayCount WHERE Level="+level+";",null);
            if(c == null) return 0;
            c.moveToNext();
            do{
                result  = c.getInt(c.getColumnIndex(mContext.getString(R.string.PLAYCOUNTdb)));
            }while(c.moveToNext());
            c.close();
        }catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return result;
    }

    //Obtener el Score (PUNTUACION)
    public List<Ranking> getRanking() {
        List<Ranking> listRanking = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c;
        try {
            c = db.rawQuery("SELECT * FROM Ranking Order By Score DESC;", null);
            if (c == null) return null;
            c.moveToNext();
            do {
                int Id = c.getInt(c.getColumnIndex(mContext.getString(R.string.ID3db)));
                double Score = c.getDouble(c.getColumnIndex(mContext.getString(R.string.SCOREdb)));

                Ranking ranking = new Ranking(Id, Score);
                listRanking.add(ranking);
            } while (c.moveToNext());
            c.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        db.close();
        return listRanking;

    }



}
    
asked by zzxbx 16.02.2018 в 22:59
source

1 answer

0

Seeing the error:

  

java.lang.RuntimeException: Unable to start activity   ComponentInfo {dev.mros.espanyaapp / dev.mros.espanyaapp.Playing}:   android.database.sqlite. SQLiteCantOpenDatabaseException: unknown error   (code 14): Could not open database

First you must verify you have specified the permission WRITE_EXTERNAL_STORAGE , in this case:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Remember that if your device has Android 6.0 or later operating system, you must manually require this permission:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
    //Verifica permisos para Android 6.0+
     checkExternalStoragePermission();
}

You can use this method:

private void checkExternalStoragePermission() {
    int permissionCheck = ContextCompat.checkSelfPermission(
            this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        Log.i("Mensaje", "No se tiene permiso para leer.");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 225);
    } else {
        Log.i("Mensaje", "Se tiene permiso para leer!");
    }
}

Second you must ensure that the database actually exists , you can try the method mentioned:

Verify BD existence and table in Android

private boolean checkDataBase(String Database_path) {
    SQLiteDatabase checkDB = null;
    try {
        checkDB = SQLiteDatabase.openDatabase(Database_path, null, SQLiteDatabase.OPEN_READONLY);
        checkDB.close();
    } catch (SQLiteException e) {
        Log.e("Error", "No existe la base de datos " + .getMessage());
    }
    return checkDB != null;
}

Update: It's really not right to open the database from your class that extends from SQLiteOpenHelper , a class DatabaseManager is created in the builder that creates an instance of DbHelper to create the database, if you do not do this you will not have a database.

private DbHelper mDbHelper ;

private DatabaseManager(Context context) {
    DbHelper = new DbHelper (context);
}

You can simply make sure to call the DbHelper constructor when you start your application to create the database:

DbHelper dbHelper = new DbHelper(this);

In fact DbHelper does not have the creation of tables specified, I do not think you want a database without tables:

@Override
public void onCreate(SQLiteDatabase db) {
 //???
}

I suggest you review the official documentation: "How to save data on bases of SQL data "

    
answered by 17.02.2018 в 01:00