Reputation: 81
In the main activity I create database
class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, "myDB", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table mytable ("
+ "id integer primary key autoincrement,"
+ "name text,"
+ "obId text,"
+ "latit text,"
+ "long text" + ");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
In the second activity I call the class of database
MainActivity myActivity = new MainActivity();
dbHelper = myActivity.new DBHelper(myActivity);
And insert data
ContentValues cv = new ContentValues();
db = openOrCreateDatabase("myDB.db", SQLiteDatabase.OPEN_READWRITE, null);
cv.put("name", textViewName.getText().toString());
long rowID = db.insert("mytable", null, cv);
db.insert("mytable", null, cv);
dbHelper.close();
The output "rowID" is "-1". I do not understand why this is happening
Upvotes: 1
Views: 1833
Reputation: 152847
Use getWritableDatabase()
on your database helper instead of openOrCreateDatabase()
on a Context
to get a database reference. You're operating on two different databases, out of which the other doesn't have the table you're attempting to insert to.
Also, you're inserting the same data twice.
If I use db = dbHelper.getWritableDatabase(); I will in Log java.lang.NullPointerException at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:203) at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:118) at com.ex.test.AddPoint.writePointsToDatabase(Add.java:264) at com.ex.test.AddPoint$3$2.onClick(Add.java:238)
That's because of you've passed in an invalid Context
to the helper here:
MainActivity myActivity = new MainActivity();
dbHelper = myActivity.new DBHelper(myActivity);
You cannot instantiate activities with new
. In an activity, use this
to refer to a valid Context
.
Upvotes: 1
Reputation: 73
You're operating on two different databases
That is "myDB" in
super(context, "myDB", null, 1);
as opposed to "myDB.db" in
db = openOrCreateDatabase("myDB.db", SQLiteDatabase.OPEN_READWRITE, null);
Best
Upvotes: 0