我尝试了多个实验,并意识到我NullPointerException
在尝试执行 SQL 查询时遇到了问题。我的完整查询是:
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();
}