SQLite Cursor crashes - java

i have a problem with my SQLite class. In fact, i was learning how to setting up (update and read) a database on android and I successfully wrote on the database, but when i try to read the informations and display them on the screen, my application just crashes.
I searched the problem and found that the cause of the crash is the Cursor. I commented the cursor's method, so if someone can help me with that, i would be thankful.
This my Database class.
package com.example.sqlprogramming;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseClass {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "person_name";
public static final String KEY_RATE = "person_rate";
private static final String DATABASE_NAME = "HotOrNotdb";
private static final String DATABASE_TABLE = "peopleTable";
private static final int DATABASE_VERSION = 2;
private Dhelper ourHelperdb;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class Dhelper extends SQLiteOpenHelper{
public Dhelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table if not exists " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + "VARCHAR NOT NULL, " +
KEY_RATE + "VARCHAR NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public DatabaseClass(Context c){
ourContext = c;
}
public DatabaseClass open() throws SQLException{
ourHelperdb = new Dhelper(ourContext);
ourDatabase = ourHelperdb.getWritableDatabase();
return this;
}
public void close(){
ourHelperdb.close();
}
public long addEntry(String personName, String personHotness) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, personName);
cv.put(KEY_RATE, personHotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
//HERE IS MY PROBLEM WITH THE CURSOR
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_RATE};
String result = "hello";
Cursor c = ourDatabase.query(true, DATABASE_TABLE, columns, null, null, null, null, null, null);
int iRowId = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iRate = c.getColumnIndex(KEY_RATE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRowId) + " " + c.getString(iName) +" " + c.getString(iRate) + "\n";
}
c.close();
return result;
}
}
And this Class call the Database Class and should take informations from database to display it on the screen.
package com.example.sqlprogramming;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SQLview extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_sqlview);
TextView textInfo = (TextView) findViewById (R.id.tvSQLinfo);
DatabaseClass info = new DatabaseClass(this);
info.open();
String _data = info.getData();
info.close();
textInfo.setText(_data);
}
}
Thank you again.
I'll post stacktrace and logcat soon.
Here is my Logcat/Stacktrace
02-24 20:08:12.378: E/Curosr!(1221): I got an error here :
02-24 20:08:12.378: E/Curosr!(1221): android.database.sqlite.SQLiteException: no such column: person_name (code 1): , while compiling: SELECT _id AS _id, person_name, person_rate FROM peopleTable
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
02-24 20:08:12.378: E/Curosr!(1221): at com.example.sqlprogramming.DatabaseClass.getData(DatabaseClass.java:75)
02-24 20:08:12.378: E/Curosr!(1221): at com.example.sqlprogramming.SQLview.onCreate(SQLview.java:14)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.Activity.performCreate(Activity.java:5104)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
02-24 20:08:12.378: E/Curosr!(1221): at android.os.Handler.dispatchMessage(Handler.java:99)
02-24 20:08:12.378: E/Curosr!(1221): at android.os.Looper.loop(Looper.java:137)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.main(ActivityThread.java:5039)
02-24 20:08:12.378: E/Curosr!(1221): at java.lang.reflect.Method.invokeNative(Native Method)
02-24 20:08:12.378: E/Curosr!(1221): at java.lang.reflect.Method.invoke(Method.java:511)
02-24 20:08:12.378: E/Curosr!(1221): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-24 20:08:12.378: E/Curosr!(1221): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-24 20:08:12.378: E/Curosr!(1221): at dalvik.system.NativeStart.main(Native Method)

Your create statement is missing a few spaces. Try using:
db.execSQL("create table if not exists " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " VARCHAR NOT NULL, " +
KEY_RATE + " VARCHAR NOT NULL);");
According to your current statement, your last two column names become person_nameVARCHAR and person_rateVARCHAR

If you're reading, you need to use:
ourDatabase = ourHelperdb.getReadableDatabase();
When you open your DB, you are setting it to write.
(That's my first guess, post stack trace).
Here's a working example from some of my code on how to read a cursor:
mDb = mDbHelper.getReadableDatabase();
Cursor c = mDb.query("Timesheets", new String[] {
KEY_TIMESHEETS_ROWID + " AS _id", KEY_TIMESHEETS_DESCRIPTION,
KEY_TIMESHEETS_TITLE, KEY_TIMESHEETS_DATE_START,
KEY_TIMESHEETS_DATE_END, KEY_TIMESHEETS_INVOICED,
KEY_TIMESHEETS_PROJECTID }, "timesheet_id = ?",
new String[] { String.valueOf(timesheetId) }, null, null, null);
c.moveToFirst();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Timesheet timesheet = new Timesheet();
while (c.isAfterLast() == false) {
timesheet.setTimesheetId(c.getInt(0));
// ...
c.moveToNext();
}
c.close();

Related

SQLite Database Error Newbie

This is my first SQLite App and I found a lot of errors and I don't what to do.
Can anyone tell me what I need to do?
This is my log cat:
12-26 18:58:05.870 26185-26185/? I/art: Late-enabling -Xcheck:jni
12-26 18:58:05.889 26185-26185/? E/Environment: initForCurrentUser:userId= 0
12-26 18:58:05.889 26185-26185/? D/Environment: UserEnvironment current
userId IS : 0
12-26 18:58:05.889 26185-26185/? D/Environment: UserEnvironment PRIMARY
STORAGE IS : MEDIA_INTERNAL
12-26 18:58:05.982 26185-26185/com.example.acer.sqlitecrud I/LoadedApk: No
resource references to update in package com.hmct.hmcttheme
12-26 18:58:06.010 26185-26185/com.example.acer.sqlitecrud W/art: Before
Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
12-26 18:58:06.135 26185-26185/com.example.acer.sqlitecrud E/SQLiteLog: (1)
near "TABLEstudentTable": syntax error
12-26 18:58:06.136 26185-26185/com.example.acer.sqlitecrud D/AndroidRuntime:
Shutting down VM
12-26 18:58:06.138 26185-26185/com.example.acer.sqlitecrud E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.acer.sqlitecrud, PID: 26185
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.acer.sqlitecrud/com.example.acer.sqlitecrud.MainActivity}: android.database.sqlite.SQLiteException: near "TABLEstudentTable": syntax error (code 1): , while compiling: CREATE TABLEstudentTable(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2328)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2394)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5270)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:708)
Caused by: android.database.sqlite.SQLiteException: near "TABLEstudentTable": syntax error (code 1): , while compiling: CREATE TABLEstudentTable(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com.example.acer.sqlitecrud.DatabaseHelper.onCreate(DatabaseHelper.java:27)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.example.acer.sqlitecrud.DatabaseHelper.<init>(DatabaseHelper.java:22)
at com.example.acer.sqlitecrud.MainActivity.onCreate(MainActivity.java:22)
at android.app.Activity.performCreate(Activity.java:6075)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2281)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2394) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5270) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:708) 
12-26 18:58:06.249 26185-26185/com.example.acer.sqlitecrud I/Process: Sending signal. PID: 26185 SIG: 9
This is my class:
DatabaseHelper.Java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String dbName = "Student.db";
public static final String tbName = "studentTable";
public static final String colID = "ID";
public static final String colName = "NAME";
public static final String colMarks = "MARKS";
public DatabaseHelper(Context context) {
super(context, dbName, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE"+tbName+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS"+tbName);
onCreate(db);
}
public boolean insertData (String Name, String Marks){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(colName,Name);
contentValues.put(colMarks,Marks);
long result = db.insert(tbName,null,contentValues);
if (result == -1){
return false;
}else {
return true;
}
}
}
MainActivity.java:
package com.example.acer.sqlitecrud;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText Name, Marks;
Button addData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
Name = (EditText)findViewById(R.id.edtNama);
Marks = (EditText)findViewById(R.id.edtNilai);
addData = (Button)findViewById(R.id.btnInsert);
InsertData();
}
private void InsertData() {
addData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.insertData(Name.getText().toString(),
Marks.getText().toString());
if (isInserted = true){
Toast.makeText(MainActivity.this,"Data Telah Di Inputkan !!",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this,"Data Gagal Di Inputkan !!",Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+tbName+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)");
}
note the space between the TABLE and tbName
Query syntax error, space is missing.
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+tbName+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)");
}
You are missing space in syntax of create table
db.execSQL("CREATE TABLE "+tbName+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)");
In drop table also you missed the space
"DROP TABLE IF EXISTS "+tbName
check below code
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+tbName+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)"); //add space after TABLE
}

java.lang.IllegalStateException: Could not execute method of the activity caused by Invocation and NPE error

I cant seem to figure out how how to fix the NPE error. Is it because I have not included the ID column when inserting? or is it because the db is returning a data type which is not a long (or int)?
The Activity:
public class CreateActivity extends ActionBarActivity {
Database db;
SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_create);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.create, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void save(View v){
EditText theitems = (EditText) findViewById(R.id.editText1);
EditText thedescription = (EditText) findViewById(R.id.editText2);
String items = theitems.getText().toString();
String description=thedescription.getText().toString();
long success = db.insertRecord(items, description);
if (success != -1)
Toast.makeText(getApplicationContext(), "Inserted",Toast.LENGTH_LONG).show();
}
public void save_send(View v){
EditText theitems = (EditText)findViewById(R.id.editText1);
EditText thedescription = (EditText)findViewById(R.id.editText2);
String items = theitems.getText().toString();
String description=thedescription.getText().toString();
long success = db.insertRecord(items, description);
if (success != -1)
Toast.makeText(getApplicationContext(), "Inserted",Toast.LENGTH_LONG).show();
}
}
The Database File
public class Database {
DatabaseHelper dbHelper;
public Database(Context context){
dbHelper = new DatabaseHelper(context, DatabaseHelper.DB_NAME, null, DatabaseHelper.DB_VERSION);
}
public long insertRecord(String items, String description) {
SQLiteDatabase db=dbHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(DatabaseHelper.KEY_ITEMS, items);
initialValues.put(DatabaseHelper.KEY_DESCRIPTION, description);
long id= db.insert(DatabaseHelper.DB_TABLE, null, initialValues);
return id;
}
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
public static final String KEY_ROWID = "id";
public static final String KEY_ITEMS = "items";
public static final String KEY_DESCRIPTION = "description";
public static final String DB_NAME = "shop";
public static final String DB_TABLE = "shop_record";
public static final int DB_VERSION = 2;
public static final String DB_CREATE = "create table if not exists shop_record ("
+ "ID int not null auto_increment,"
+ "items varchar(255),"
+ "description varchar(255),"
+ "date datetime,"
+ "send_status char(10)," + "primary key (ID));";
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DB_CREATE);
} catch (android.database.SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
}
The logcat:
02-24 00:07:26.908: D/OpenGLRenderer(16859): Render dirty regions requested: true
02-24 00:07:26.918: D/Atlas(16859): Validating map...
02-24 00:07:26.947: I/Adreno-EGL(16859): <qeglDrvAPI_eglInitialize:410>: QUALCOMM Build: 10/28/14, c33033c, Ia6306ec328
02-24 00:07:26.948: I/OpenGLRenderer(16859): Initialized EGL, version 1.4
02-24 00:07:26.974: D/OpenGLRenderer(16859): Enabling debug mode 0
02-24 00:07:32.126: D/AndroidRuntime(16859): Shutting down VM
02-24 00:07:32.127: E/AndroidRuntime(16859): FATAL EXCEPTION: main
02-24 00:07:32.127: E/AndroidRuntime(16859): Process: com.example.mythirdapp, PID: 16859
02-24 00:07:32.127: E/AndroidRuntime(16859): java.lang.IllegalStateException: Could not execute method of the activity
02-24 00:07:32.127: E/AndroidRuntime(16859): at android.view.View$1.onClick(View.java:4007)
02-24 00:07:32.127: E/AndroidRuntime(16859): at android.view.View.performClick(View.java:4756)
02-24 00:07:32.127: E/AndroidRuntime(16859): at android.view.View$PerformClick.run(View.java:19749)
02-24 00:07:32.127: E/AndroidRuntime(16859): at android.os.Handler.handleCallback(Handler.java:739)
02-24 00:07:32.127: E/AndroidRuntime(16859): at android.os.Handler.dispatchMessage(Handler.java:95)
02-24 00:07:32.127: E/AndroidRuntime(16859): at android.os.Looper.loop(Looper.java:135)
02-24 00:07:32.127: E/AndroidRuntime(16859): at android.app.ActivityThread.main(ActivityThread.java:5221)
02-24 00:07:32.127: E/AndroidRuntime(16859): at java.lang.reflect.Method.invoke(Native Method)
02-24 00:07:32.127: E/AndroidRuntime(16859): at java.lang.reflect.Method.invoke(Method.java:372)
02-24 00:07:32.127: E/AndroidRuntime(16859): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
02-24 00:07:32.127: E/AndroidRuntime(16859): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
02-24 00:07:32.127: E/AndroidRuntime(16859): Caused by: java.lang.reflect.InvocationTargetException
02-24 00:07:32.127: E/AndroidRuntime(16859): at java.lang.reflect.Method.invoke(Native Method)
02-24 00:07:32.127: E/AndroidRuntime(16859): at java.lang.reflect.Method.invoke(Method.java:372)
02-24 00:07:32.127: E/AndroidRuntime(16859): at android.view.View$1.onClick(View.java:4002)
02-24 00:07:32.127: E/AndroidRuntime(16859): ... 10 more
02-24 00:07:32.127: E/AndroidRuntime(16859): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'long com.example.edit.Database.insertRecord(java.lang.String, java.lang.String)' on a null object reference
02-24 00:07:32.127: E/AndroidRuntime(16859): at com.example.edit.CreateActivity.save(CreateActivity.java:62)
02-24 00:07:32.127: E/AndroidRuntime(16859): ... 13 more
02-24 00:07:34.147: I/Process(16859): Sending signal. PID: 16859 SIG: 9
02-24 00:07:34.621: D/OpenGLRenderer(16947): Render dirty regions requested: true
02-24 00:07:34.629: D/Atlas(16947): Validating map...
02-24 00:07:34.663: I/Adreno-EGL(16947): <qeglDrvAPI_eglInitialize:410>: QUALCOMM Build: 10/28/14, c33033c, Ia6306ec328
02-24 00:07:34.664: I/OpenGLRenderer(16947): Initialized EGL, version 1.4
02-24 00:07:34.685: D/OpenGLRenderer(16947): Enabling debug mode 0
You got NPE because your db=null at
long success = db.insertRecord(items, description);
So initialized it before used
db=new Database(CreateActivity.this);
NullPointerException: Attempt to invoke virtual method 'long
com.example.edit.Database.insertRecord
Because db object of Database is null.
Initialize db object before using to call any method from Database class:
db=new Database(CreateActivity.this);
Database db;
Which means db is null. Not yet initialized
Try this:
db = new Database(getApplciationContext());

Error: sqlite returned: error code = 1, msg = no such table

I am working on a small app which stores the place latitude and longitude in SQLite database. I have three classes as follows:
AddPlaceActyivity.java
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.rememberthislocation.R;
public class AddPlaceActivity extends Activity{
Button btn_remember,btn_maps;
Fragment fr;
Button addlocation;
EditText locationname;
String mylocationname,mylatitude,mylongitude;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Log.d("my","In oncreateview");
setContentView(R.layout.remember_fragment);
addlocation = (Button)findViewById(R.id.btn_addlocation);
locationname = (EditText)findViewById(R.id.locationname);
mylocationname = locationname.getText().toString();
Log.d("my","value 1 taken");
mylatitude = "0.0";
mylongitude = "0.0";
Log.d("my", "data values taken");
addlocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MySqliteHelper db = new MySqliteHelper(getApplicationContext());
db.addPlaces(new Place(mylocationname,mylatitude,mylongitude));
}
});
}
}
MySqliteHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySqliteHelper extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contactsManager";
private static final String KEY_ID = "id";
private static final String KEY_PLACENAME = "placename";
private static final String KEY_LATITUDE = "latitude";
private static final String KEY_LONGITUDE = "longitude";
private static final String TABLE_NAME = "places";
public MySqliteHelper(Context context) {
super(context, DATABASE_NAME,null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//actual query = create table places (id primary key autoincrement, placename taxt, latitude real, longitude real);
String query = "CREATE TABLE" +TABLE_NAME + "( " + KEY_ID+
"INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_PLACENAME+
"TEXT, "+KEY_LATITUDE+
"REAL, "+KEY_LONGITUDE+ "REAL)";
try {
db.execSQL(query);
Log.d("my", "Successfully created table: " + query);
} catch (SQLiteException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS places");
this.onCreate(db);
}
public void addPlaces(Place place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues convalues = new ContentValues();
convalues.put(KEY_PLACENAME,place.getname());
convalues.put(KEY_LATITUDE,place.getlatitude());
convalues.put(KEY_LONGITUDE,place.getlongitude());
db.insert(TABLE_NAME, null, convalues);
Log.d("my","db.insert(TABLE_NAME, null, convalues)");
Log.d("my", "Values inserted");
db.close();
}
}
Place.java
public class Place {
String mname,mlatitude,mlongitude,mstring;
public Place(String name, String latitude, String longitude)
{
mname = name;
mlatitude = latitude;
mlongitude = longitude;
}
public Place() {
// TODO Auto-generated constructor stub
}
public void setname(String placename)
{
mname = placename;
}
public String getname()
{
return mname;
}
public void setlatitude(String latitude)
{
mlatitude=latitude;
}
public String getlatitude()
{
return mlatitude;
}
public void setlongitude(String longitude)
{
mlongitude = longitude;
}
public String getlongitude()
{
return mlongitude;
}
}
And my logcat log:
11-20 17:40:02.770: D/my(10604): In oncreateview
11-20 17:40:02.890: D/my(10604): acivity layout initialized
11-20 17:40:02.950: I/PGA(10604): New SOCKET connection: berthislocation (pid 10604, tid 10604)
11-20 17:40:16.510: D/my(11196): in remember's onclick
11-20 17:40:16.540: D/my(11196): intent started
11-20 17:40:16.560: D/my(11196): In oncreateview
11-20 17:40:16.560: D/my(11196): value 1 taken
11-20 17:40:16.560: D/my(11196): data values taken
11-20 17:40:27.290: I/SqliteDatabaseCpp(11196): sqlite returned: error code = 1, msg = no such table: places, db=/data/data/com.example.rememberthislocation/databases/contactsManager
11-20 17:40:27.290: E/SQLiteDatabase(11196): Error inserting longitude=0.0 latitude=0.0 placename=
11-20 17:40:27.290: E/SQLiteDatabase(11196): android.database.sqlite.SQLiteException: no such table: places: , while compiling: INSERT INTO places(longitude,latitude,placename) VALUES (?,?,?)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteStatement.acquireAndLock(SQLiteStatement.java:260)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:112)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1718)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1591)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at com.example.rememberthisplace.MySqliteHelper.addPlaces(MySqliteHelper.java:74)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at com.example.rememberthisplace.AddPlaceActivity$1.onClick(AddPlaceActivity.java:52)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.view.View.performClick(View.java:3511)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.view.View$PerformClick.run(View.java:14105)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.os.Handler.handleCallback(Handler.java:605)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.os.Handler.dispatchMessage(Handler.java:92)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.os.Looper.loop(Looper.java:137)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.app.ActivityThread.main(ActivityThread.java:4424)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at java.lang.reflect.Method.invokeNative(Native Method)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at java.lang.reflect.Method.invoke(Method.java:511)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at dalvik.system.NativeStart.main(Native Method)
Clearly the error is in MySqliteHelper.java
Error: sqlite returned: error code = 1, msg = no such table: places
So, my MySqliteHelper class's oncreate() isn't called. I tried for hours..but can't find the solution. Can anyone help me?
You have bugs in your onCreate() that are hidden by the catch:
String query = "CREATE TABLE" +TABLE_NAME + "( " + KEY_ID+
"INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_PLACENAME+
"TEXT, "+KEY_LATITUDE+
"REAL, "+KEY_LONGITUDE+ "REAL)";
Missing whitespace, change to:
String query = "CREATE TABLE " +TABLE_NAME + "( " + KEY_ID+
" INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_PLACENAME+
" TEXT, "+KEY_LATITUDE+
" REAL, "+KEY_LONGITUDE+ " REAL)";
Remove the try-catch. If there's a problem, the framework should be thrown an exception. If onCreate() returns normally, the framework thinks the database was set up successfully. onCreate() is only called once when the database is first set up.
Uninstall your app or clear its data to get rid of the old empty database file and to get onCreate() rerun.
Further reading: When is SQLiteOpenHelper onCreate() / onUpgrade() run?

Getting error while inserting the data in data base in android

I am inserting the data from data base using sqlite but I am getting an error .Here is my code and error.I just enter one entry and want to display that entry ?
package com.example.database_example;
public class Information {
String name;
public Information(String name) {
// TODO Auto-generated constructor stub
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Data Base.java class
package com.example.database_example;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Information inf=new Information("naveen");
DataBaseExample dbx=new DataBaseExample(MainActivity.this);
if(dbx.insertname(inf)){
Log.v("checkdbx.insertname(inf);", "save ok.");
}else{
Log.v("checkdbx.insertname(inf);", "save failed.");
}
}
}
package com.example.database_example;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseExample extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "information";
// Contacts table name
private static final String TABLE_Name= "Name";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
public DataBaseExample(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String createTable= "CREATE TABLE " + TABLE_Name+"("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
+ ")";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Name);
// Create tables again
onCreate(db);
}
public boolean insertname(Information information) {
boolean createSuccessful = false;
ContentValues values = new ContentValues();
// values.put(KEY_ID, information.getId());
values.put(KEY_NAME, information.getName());
SQLiteDatabase db = this.getWritableDatabase();
createSuccessful = db.insert(TABLE_Name, null, values) > 0;
db.close();
return createSuccessful;
}
}
Here is my error
09-24 07:25:07.138: I/Database(392): sqlite returned: error code = 1, msg = near ")": syntax error
09-24 07:25:07.138: E/Database(392): Failure 1 (near ")": syntax error) on 0x2a7080 when preparing 'CREATE TABLE Name(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,)'.
09-24 07:25:07.148: D/AndroidRuntime(392): Shutting down VM
09-24 07:25:07.148: W/dalvikvm(392): threadid=1: thread exiting with uncaught exception (group=0x40015560)
09-24 07:25:07.158: E/AndroidRuntime(392): FATAL EXCEPTION: main
09-24 07:25:07.158: E/AndroidRuntime(392): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.database_example/com.example.database_example.MainActivity}: android.database.sqlite.SQLiteException: near ")": syntax error: CREATE TABLE Name(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.os.Handler.dispatchMessage(Handler.java:99)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.os.Looper.loop(Looper.java:123)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.main(ActivityThread.java:3683)
09-24 07:25:07.158: E/AndroidRuntime(392): at java.lang.reflect.Method.invokeNative(Native Method)
09-24 07:25:07.158: E/AndroidRuntime(392): at java.lang.reflect.Method.invoke(Method.java:507)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-24 07:25:07.158: E/AndroidRuntime(392): at dalvik.system.NativeStart.main(Native Method)
09-24 07:25:07.158: E/AndroidRuntime(392): Caused by: android.database.sqlite.SQLiteException: near ")": syntax error: CREATE TABLE Name(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.database.sqlite.SQLiteDatabase.native_execSQL(Native Method)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1763)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.example.database_example.DataBaseExample.onCreate(DataBaseExample.java:34)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:126)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.example.database_example.DataBaseExample.insertname(DataBaseExample.java:55)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.example.database_example.MainActivity.onCreate(MainActivity.java:18)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
09-24 07:25:07.158: E/AndroidRuntime(392): ... 11 more
Change
String createTable= "CREATE TABLE " + TABLE_Name+"("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
+ ")";
to
String createTable= "CREATE TABLE " + TABLE_Name+"("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT"
+ ")";
removing the comma after TEXT
EDIT
To read all the values from the database, you can add the following method to your class DataBaseExample:
private List<Information> getAllItems()
List<Information> itemsList = new ArrayList<Information>();
Cursor cursor = null;
try {
//get all rows
cursor = mDatabase.query(TABLE_Name, null, null, null, null,
null, null);
if (cursor.moveToFirst()) {
do {
Information c = new Information();
c.setName(cursor.getString(KEY_NAME));
itemsList.add(c);
} while (cursor.moveToNext());
}
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
cursor.close();
}
return itemsList;
}

NullPointerException when trying to insert into SQLite - Android

Anyone who follows Android tags are probably familiar with me. I am having the hardest time implementing a SQLite database for my highscores. This is also my first time working with SQLite.
I am trying to insert just two variables -- int and long. My insert() method is not working correctly. Any advice other than the stuff talked about above is also appreciated.
Thank you in advance for your help.
Highscores.java
public class Highscores extends Activity {
DatabaseHelper dh;
SQLiteDatabase db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.highscoresmain);
dh = new DatabaseHelper(this);
dh.openDB(db);
long x = 11;
int y = 22;
TextView rank = (TextView)findViewById(R.id.rank);
TextView percentage = (TextView)findViewById(R.id.percentage);
TextView score = (TextView)findViewById(R.id.score);
TextView r1r = (TextView)findViewById(R.id.r1r);
TextView r1p = (TextView)findViewById(R.id.r1p);
TextView r1s = (TextView)findViewById(R.id.r1s);
dh.insert(x, y, db); //Line 55
scores = dh.getScore(db);
percentages = dh.getPercentage(db);
rank.setText("Rank Column - TEST");
percentage.setText("Percentage Column - TEST ");
score.setText("Score Column - Test");
r1r.setText("test..rank");
r1p.setText("" + percentages);
r1s.setText("test..score");
table = (TableLayout)findViewById(R.id.tableLayout);
dh.closeDB(db);
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
SQLiteDatabase db;
// Table columns names.
private static final String RANK = "_id";
private static final String SCORE = "score";
private static final String PERCENTAGE = "percentage";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
}
public SQLiteDatabase openDB(SQLiteDatabase db) {
db = this.getWritableDatabase();
return db;
}
public int getPercentage(SQLiteDatabase db) {
//Cursor c = db.rawQuery("SELECT " + PERCENTAGE + " FROM " + TABLE + " WHERE " + PERCENTAGE + " = " + 22 + ";", null);
Cursor c = db.rawQuery("SELECT " + PERCENTAGE + " FROM " + TABLE + ";", null);
int i = 0;
if(c.getCount() == 0) {
i = 333;
} else if (c.getCount() == 1) {
i = 444;
} else {
i = 888;
/*c.moveToFirst();
int columnIndex = c.getInt(c.getColumnIndex("PERCENTAGE"));
if(columnIndex != -1) {
i = c.getInt(columnIndex);
} else {
i = 999;
}*/
}
c.close();
return i;
}
//Insert new record.
public long insert(long score, int percentage, SQLiteDatabase db) {
ContentValues values = new ContentValues();
values.put(SCORE, score);
values.put(PERCENTAGE, percentage);
return db.insert(TABLE, null, values); //Line 120
}
public synchronized void closeDB(SQLiteDatabase db) {
if(db != null) {
db.close();
}
super.close();
}
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE + " ("
+ RANK + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SCORE + " LONG,"
+ PERCENTAGE + " INTEGER"
+ ");");
}
LogCat output
01-03 17:09:18.232: E/AndroidRuntime(1712): FATAL EXCEPTION: main
01-03 17:09:18.232: E/AndroidRuntime(1712): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.Highscores}: java.lang.NullPointerException
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.os.Handler.dispatchMessage(Handler.java:99)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.os.Looper.loop(Looper.java:137)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-03 17:09:18.232: E/AndroidRuntime(1712): at java.lang.reflect.Method.invokeNative(Native Method)
01-03 17:09:18.232: E/AndroidRuntime(1712): at java.lang.reflect.Method.invoke(Method.java:511)
01-03 17:09:18.232: E/AndroidRuntime(1712): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-03 17:09:18.232: E/AndroidRuntime(1712): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-03 17:09:18.232: E/AndroidRuntime(1712): at dalvik.system.NativeStart.main(Native Method)
01-03 17:09:18.232: E/AndroidRuntime(1712): Caused by: java.lang.NullPointerException
01-03 17:09:18.232: E/AndroidRuntime(1712): at com.example.test.DatabaseHelper.insert(DatabaseHelper.java:120)
01-03 17:09:18.232: E/AndroidRuntime(1712): at com.example.test.Highscores.onCreate(Highscores.java:55)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.Activity.performCreate(Activity.java:5104)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-03 17:09:18.232: E/AndroidRuntime(1712): ... 11 more
On this line, you open the DB:
dh.openDB(db);
This stores the member variable of the database in DatabaseHelper.db (but nowhere else, and particularly not in Highscores.db). Then, you call:
dh.insert(x, y, db);
Using a null db object from Highscores. Lastly, within insert(), you use this null db object:
return db.insert(TABLE, null, values);
What you should do instead is use the following as your insert() method:
public long insert(long score, int percentage) { // Remove db parameter
ContentValues values = new ContentValues();
values.put(SCORE, score);
values.put(PERCENTAGE, percentage);
return db.insert(TABLE, null, values); // This will use the member variable
}
Then, call dh.insert(x, y); instead.
You should also change openDB(SQLiteDatabase db) to openDB() so that it is writing the correct DB; as it stands, it just overwrites the local variable's value (which changes nothing once the function's scope is done).
Instead of
dh.openDB(db);
say
db = dh.openDB(db);
(although the openDB method really doesn't need to have an argument). Your call to openDB doesn't store the database object reference in db, so it's NULL when you get around to calling dh.insert(..., db);.

Categories