Reputation: 21
Whenever I fire the database my app crashes. I have been working on this for couple of days. (I am entering only the important code snippets of my databaseAdapter.java
file here). I am getting the error in getWritableDatabase()
: NullPointerException
.
private SQLiteDatabase db;
static final boolean assertionsDisabled = false;
private DBHelper dbHelper;
// private Context context;
public DatabaseAdapter(Context context) {
dbHelper = new DBHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE_ENTRIES);
//db = DBHelper.getWritableDatabase();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int j)
{
Log.w("mytag", (new StringBuilder("Upgrading from version ")).append(i).append(" to ").append(j).append(", which will destroy all old data").toString());
db.execSQL("DROP TABLE IF EXISTS CREATE TABLE IF NOT EXISTS entries (_id INTEGER PRIMARY KEY AUTOINCREMENT, input_type INTEGER NOT NULL, activity_type INTEGER NOT NULL, date_time DATETIME NOT NULL, duration INTEGER NOT NULL, distance FLOAT, avg_pace INTEGER, avg_speed INTEGER,calories INTEGER, climb INTEGER, avg_heartrate INTEGER, comment TEXT, privacy INTEGER, gps_data BLOB );");
onCreate(db);
}
}
public DatabaseAdapter open()
throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
/////////////////////////////////////////////////////////////////////
EDIT 1: I am calling databaseAdapter.java from the ActivityManualInput.java code //////////////////////// This is the code snippet in ActivityManualInput.java from where databaseAdapter is called
public class ActivityManualInput extends ListActivity {
// Some code here
private Context mContext;
// Some code here
protected void onCreate(Bundle savedInstanceState) {
//TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.xml.manualinput);
// Some code here
Button btn = ((Button) findViewById(R.id.btnSave));
View.OnClickListener myListener;
myListener= new View.OnClickListener(){
@Override
public void onClick(View v)
{
// mDateTime = new GregorianCalendar(mYear, mMonth, mDay, mHour, mMinute);
mDateTime = new GregorianCalendar(2, 3, 1, 4,5);
db = new DatabaseAdapter(mContext);
db.open();
// long id = db.insertEntry(mInputType, mActivityType, mDateTime, mDuration, mDistance, mCalories, mComment);
long id = db.insertEntry(3, 3, mDateTime, 4, 5, 5, "ant");
db.close();
Toast.makeText(getApplicationContext(), "Entry #" + id + "Saved!", Toast.LENGTH_SHORT)
.show();
finish();
}
};
btn.setOnClickListener(myListener);
///////// Log files...... /////////////////////
12-03 06:03:00.318: W/dalvikvm(270): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
12-03 06:03:00.318: E/AndroidRuntime(270): Uncaught handler: thread main exiting due to uncaught exception
12-03 06:03:00.398: E/AndroidRuntime(270): java.lang.NullPointerException
12-03 06:03:00.398: E/AndroidRuntime(270): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:98)
12-03 06:03:00.398: E/AndroidRuntime(270): at com.android.saud.lab3.DatabaseAdapter.open(DatabaseAdapter.java:147)
12-03 06:03:00.398: E/AndroidRuntime(270): at com.android.saud.lab3.ActivityManualInput$1.onClick(ActivityManualInput.java:85)
12-03 06:03:00.398: E/AndroidRuntime(270): at android.view.View.performClick(View.java:2364)
12-03 06:03:00.398: E/AndroidRuntime(270): at android.view.View.onTouchEvent(View.java:4179)
12-03 06:03:00.398: E/AndroidRuntime(270): at android.widget.TextView.onTouchEvent(TextView.java:6541)
12-03 06:03:00.398: E/AndroidRuntime(270): at android.view.View.dispatchTouchEvent(View.java:3709)
12-03 06:03:00.398: E/AndroidRuntime(270): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
12-03 06:03:00.398: E/AndroidRuntime(270): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
12-03 06:03:00.398: E/AndroidRuntime(270): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
12-03 06:03:00.398: E/AndroidRuntime(270): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
12-03 06:03:00.398: E/AndroidRuntime(270): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
12-03 06:03:00.398: E/AndroidRuntime(270): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
12-03 06:03:00.398: E/AndroidRuntime(270): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
12-03 06:03:00.398: E/AndroidRuntime(270): at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
12-03 06:03:00.398: E/AndroidRuntime(270): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
12-03 06:03:00.398: E/AndroidRuntime(270): at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
12-03 06:03:00.398: E/AndroidRuntime(270): at android.os.Handler.dispatchMessage(Handler.java:99)
12-03 06:03:00.398: E/AndroidRuntime(270): at android.os.Looper.loop(Looper.java:123)
12-03 06:03:00.398: E/AndroidRuntime(270): at android.app.ActivityThread.main(ActivityThread.java:4363)
12-03 06:03:00.398: E/AndroidRuntime(270): at java.lang.reflect.Method.invokeNative(Native Method)
12-03 06:03:00.398: E/AndroidRuntime(270): at java.lang.reflect.Method.invoke(Method.java:521)
12-03 06:03:00.398: E/AndroidRuntime(270): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
12-03 06:03:00.398: E/AndroidRuntime(270): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
12-03 06:03:00.398: E/AndroidRuntime(270): at dalvik.system.NativeStart.main(Native Method)
12-03 06:03:00.418: I/dalvikvm(270): threadid=7: reacting to signal 3
12-03 06:03:00.418: E/dalvikvm(270): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
12-03 06:08:00.478: I/Process(270): Sending signal. PID: 270 SIG: 9
EDIT #2: The above error has been solved. Now I am getting the app does not crash. But the data is not stored in the data base. The error is in the return db.insert(TABLE_NAME_ENTRIES, null, contentvalues); line of the databaseadapter.java file
public long insertEntry(int i, int j, GregorianCalendar gregoriancalendar, long l, double d,
int k, String s)
{
ContentValues contentvalues = new ContentValues();
contentvalues.put(KEY_INPUT_TYPE, Integer.valueOf(i));
contentvalues.put(KEY_ACTIVITY_TYPE, Integer.valueOf(j));
contentvalues.put(KEY_DATE_TIME, Long.valueOf(gregoriancalendar.getTimeInMillis() / 1000L));
contentvalues.put(KEY_DURATION, Long.valueOf(l));
contentvalues.put(KEY_DISTANCE, Double.valueOf(d));
contentvalues.put(KEY_CALORIES, Integer.valueOf(k));
contentvalues.put(KEY_COMMENT, s);
return db.insert(TABLE_NAME_ENTRIES, null, contentvalues); // Logcat is howing
error here
}
and this is the logcat
12-03 08:51:10.608: E/Database(327): Error inserting input_type=3 calories=5 distance=5.0 duration=4 comment=ant date_time=-62096464100 activity_type=3
12-03 08:51:10.608: E/Database(327): android.database.sqlite.SQLiteException: no such table: entries: , while compiling: INSERT INTO entries(input_type, calories, distance, duration, comment, date_time, activity_type) VALUES(?, ?, ?, ?, ?, ?, ?);
12-03 08:51:10.608: E/Database(327): at android.database.sqlite.SQLiteProgram.native_compile(Native Method)
12-03 08:51:10.608: E/Database(327): at android.database.sqlite.SQLiteProgram.compile(SQLiteProgram.java:110)
Upvotes: 2
Views: 3372
Reputation: 86948
Original Error
You haven't posted the LogCat errors, but this is a typical error. I'm guessing that your are trying to create your DatabaseAdapter as a field variable incorrectly as described in the comments.
public class MainActivity extends Activity {
// Do not do this!
// This will case a NullPointerException later when your call getWritableDatabase()...
//DatabaseAdapter dba = new DatabaseAdapter(this);
// Do this instead:
DatabaseAdapter dba;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dba = new DatabaseAdapter(this); // Right way!
The Context referred to with this
is invalid in the commented out code. You must wait until the Context is valid. The first chance you get is in onCreate()
.
Addition
In this case you were using new DatabaseAdapter(mContext);
but had forgotten to initialize mContext
so it was null
...
The new LogCat shows the table entries does not exist and the reason is that you cannot chain these SQL commands together:
db.execSQL("DROP TABLE IF EXISTS CREATE TABLE IF NOT EXISTS entries ...
This is a syntax error, so the table entries
was never built. These must be separate commands:
db.execSQL("DROP TABLE IF EXISTS entries");
db.execSQL("CREATE TABLE IF NOT EXISTS entries ...
Don't forget to increment DATABASE_VERSION
so the tables will be created in onUpgrade()
.
Hopefully this has solved your current problem. Feel free to ask a new question if you encounter more exceptions. Good luck! :)
Upvotes: 2