尝试使用db.execSQL创建数据库时出现NullPointerException(DATABASE_CREATE)

时间:2012-07-27 18:20:46

标签: android sqlite nullpointerexception

我尝试了多次实验,并意识到在尝试执行SQL查询时我得到NullPointerException。我的完整查询是:

create table transactiontable(_id integer primary key autoincrement, name text not null, reason text not null, money text not null );

关于我哪里出错的建议?堆栈跟踪是:

Caused by: java.lang.NullPointerException
at com.example.startandroid.DBAdapter$DatabaseHelper.<init>(DBAdapter.java:110)
at com.example.startandroid.DBAdapter.open(DBAdapter.java:43)
at com.example.startandroid.MainActivity.onButtonClick(MainActivity.java:34)
Not sure what is the issue.

我的SQL适配器类是:

public class DBAdapter {

private static final String DATABASE_NAME = "transaction.db";
private static final String DATABASE_TABLE = "transactiontable";
private static final int    DATABASE_VERSION = 1;

public static final String KEY_ID   = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_REASON = "reason";
public static final String KEY_MONEY = "money";

private static final String DATABASE_CREATE = "create table " 
        + DATABASE_TABLE 
        + "("
        + KEY_ID + " integer primary key autoincrement, "
        + KEY_NAME + " text not null,  " 
        + KEY_REASON + " text not null, "
        + KEY_MONEY + " text not null "
        + ");";

private final Context context;

private DatabaseHelper DBHelper;
private static SQLiteDatabase db;

public DBAdapter(Context context)
{
    this.context = context;
}

// Open the database
public DBAdapter open() throws SQLException
{
    DBHelper = new DatabaseHelper(context);
    if (DBHelper != null )
        db = DBHelper.getWritableDatabase();
    return this;
}

// Close the database
public void close()
{
    DBHelper.close();
}


private static class DatabaseHelper extends SQLiteOpenHelper
{
    DatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onCreate(SQLiteDatabase arg0) 
    {

    }

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

我使用代码调用此类的函数:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    db = new DBAdapter(this);
    Log.e(TAG, "OnCreate is run");
    myIntent = new Intent(MainActivity.this, FrameActivity.class);
}

public void onButtonClick(View v)
{
    try
    {
        Log.e(TAG, "OnButtonClick starts");
        if (db != null)
        {
            db.open();
            db.close();
        }
    }
    catch(SQLException e)
    {
        e.printStackTrace();
    }
    MainActivity.this.startActivity(myIntent);
    finish();
}

1 个答案:

答案 0 :(得分:1)

{p> dbnull的构造函数中为DatabaseHelper。移动线:

db.execSQL(DATABASE_CREATE);
onCreate DatabaseHelper方法中的

@Override
public void onCreate(SQLiteDatabase arg0) {
    arg0.execSQL(DATABASE_CREATE);
}