我的android应用程序在调用getWritableDatabase()时崩溃;方法

时间:2015-04-08 08:56:32

标签: android database sqlite

我刚刚发现当我尝试调用getWritableDatabase();方法并运行它时,应用程序崩溃了。我之所以调用该方法只是为了测试onCreate方法是否会运行,但在调用onCreate之前它会卡在getWritableDatabase

    package com.mycompany.database;
    import android.database.sqlite.*;
    import android.content.*;
    import java.util.*;
    import java.sql.*;

    public class DBmanager extends SQLiteOpenHelper
    {
        public static final int database_version=9;
        public static final String database_name="testDB";
        public static final String table="tblAMIGO";
        public static final String key_name="name";
        public static final String key_id="recID";

        public DBmanager(Context context)
        {
            super(context, "sdcard/"+database_name, null, database_version);
        }

        @Override
        public void onCreate(SQLiteDatabase DB)
        {
            DB.execSQL("create table tblAMIGO(" + " recID integer, " + " name  text );  "    );
        }

        @Override
        public void onUpgrade(SQLiteDatabase p1, int p2, int p3)
        {
            p1.execSQL("drop table if exists "+table);
            onCreate(p1);
        }

        public void addName(String id, String name)
        {
            //I get the error only when I implement this method
            SQLiteDatabase db=this.getWritableDatabase();

            db.execSQL("create table IF NOT EXISTS tblAMIGO(" + " recID integer, " + " name  text );  "    );
            ContentValues values=new ContentValues();
            values.put(key_name, name);
            values.put(key_id, id);

            db.insert("tblAMIGO",null,values);
            db.close();
        }

    }

1 个答案:

答案 0 :(得分:0)

提供自定义路径可能会导致问题,因为在创建之前未检查路径的可用性。为简化(默认),请在构造函数中更改代码,如下所示:

super(context, database_name, null, database_version);