i try to delete the data from listview by using the context menu and i get this java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
public List<AssignmentRecord> getAllAssignment(){
List<AssignmentRecord> records = new ArrayList<AssignmentRecord>();
Cursor cursor = database.query(AssigmentContract.Assigment.TABLE_NAME, allColumn , null,
null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
AssignmentRecord assignmentRecord = new AssignmentRecord();
assignmentRecord.setAssname(cursor.getString(0));
assignmentRecord.setAssTime(cursor.getString(1));
assignmentRecord.setAssID(cursor.getString(2));
records.add(assignmentRecord);
cursor.moveToNext();
}
first line error assignmentRecord.setAssID(cursor.getString(2));
dbcon.open();
List<AssignmentRecord> records = dbcon.getAllAssignment();
dbcon.close();
second error is List records = dbcon.getAllAssignment();
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE "
+ AssigmentContract.Assigment.TABLE_NAME +
"(" + AssigmentContract.Assigment.COLUMN_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " +
AssigmentContract.Assigment.COLUMN_ASS + " TEXT," +
AssigmentContract.Assigment.COLUMN_ASSDATE+ " TEXT)";
public final class AssigmentContract {
public AssigmentContract(){}
public static abstract class Assigment implements BaseColumns{
public static final String TABLE_NAME ="AssignmentV2";
public static final String COLUMN_ASS ="AssignmentTitle";
public static final String COLUMN_ASSDATE ="AssignmentDate";
public static final String COLUMN_ID ="AssignmentID";
}
}
LOGCAT
my.com.chyi.schedulev2 E/CursorWindow﹕ Failed to read row 0, column 2 from a CursorWindow which has 1 rows, 2 columns.
my.com.chyi.schedulev2 D/AndroidRuntime﹕ Shutting down VM
my.com.chyi.schedulev2 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x9e4f5908)
/my.com.chyi.schedulev2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{my.com.chyi.schedulev2/my.com.chyi.schedulev2.assigmentActivity}: java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:434)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at my.com.chyi.schedulev2.SQLController.getAllAssignment(SQLController.java:102)
at my.com.chyi.schedulev2.assigmentActivity.onCreate(assigmentActivity.java:73)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230
at android.app.ActivityThread.access$600(ActivityThread.java:141)at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234 at android.os.Handler.dispatchMessage(Handler.java:99)at android.os.Looper.loop(Looper.java:137)at android.app.ActivityThread.main(ActivityThread.java:5041) at java.lang.reflect.Method.invokeNative(Native Method)at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Try this,
while(!cursor.isAfterLast()){
AssignmentRecord assignmentRecord = new AssignmentRecord();
assignmentRecord.setAssname(cursor.getString(cursor.getColumnIndex("your_respective_column_name));
assignmentRecord.setAssTime(cursor.getString(cursor.getColumnIndex("your_respective_column_name)));
assignmentRecord.setAssID(cursor.getString(cursor.getColumnIndex("your_respective_column_name)));
records.add(assignmentRecord);
cursor.moveToNext();
I have demonstrated what Harry suggested you to do. Here replace your_respective column name with the value you given for the columns which your trying to retrieve. For Ex: when you are trying to fetch the value of AssId it will be _id or some thing. Hope this helps you.
Your getAllAssignment() should be as,
List<AssignmentRecord> records = new ArrayList<AssignmentRecord>();
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery("select * from " + TABLE_NAME, null);
if(cursor.moveToFirst()){
do {
AssignmentRecord assignmentRecord = new AssignmentRecord();
assignmentRecord.setAssID(cursor.getString(0));
assignmentRecord.setAssname(cursor.getString(1));
assignmentRecord.setAssTime(cursor.getString(2));
} while(cursor.moveToNext());
}
database.close();
Related
When i am trying to display the contacts in card view when i click on Button it shows fatal exception error it doesnot display cardview anyone can solve this programming with brillliance and another error is it show only one cardview when i click on again the app will be strucked?
Showcontacts.java
public class ShowContacts extends Activity
{
private SQLiteDatabase db;
DbOperations doo;
private List<Contacts> contactsList;
private RecyclerView rv;
private Cursor c;
String names,email,address;
int phone;
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycle_layout);
doo = new DbOperations(this);
openDatabase();
rv = (RecyclerView)findViewById(R.id.recyclerview);
initializeData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
rv.setLayoutManager(linearLayoutManager);
rv.setHasFixedSize(true);
ContactAdapter cc = new ContactAdapter(contactsList);
rv.setAdapter(cc);
}
public void initializeData() {
contactsList = new ArrayList<>();
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
private void openDatabase() {
db = openOrCreateDatabase("contactDB", Context.MODE_PRIVATE,null);
}
}
Logacat error
06-28 08:57:43.107 568-568/com.example.anilkumar.contactstask E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anilkumar.contactstask/com.example.anilkumar.contactstask.ShowContacts}: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:127)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:94)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:53)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1538)
at com.example.anilkumar.contactstask.ShowContacts.initializeData(ShowContacts.java:44)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:34)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
Another logact error
06-28 13:14:40.552 11252-11261/com.example.anilkumar.contactstask E/SQLiteDatabase: close() was never explicitly called on database '/data/data/com.example.anilkumar.contactstask/databases/contactDB'
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1943)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1007)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:986)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:962)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1043)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1036)
at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:761)
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:215)
at com.example.anilkumar.contactstask.ShowContacts.openDatabase(ShowContacts.java:66)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:33)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
Just update
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
to
String read_query = "select * from "+ ContactsTask.ContactsEntry.TABLE_NAME;
Always close cursor. update your initializeData method
public void initializeData() {
try {
contactsList = new ArrayList<>();
try{
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
} catch (Exception e) {
// exception handling
} finally {
if(c != null){
c.close();
}
}
}
All files under my SQLite package are giving errors. As these are predefined classes and don't require or allow editing, I'm having a hard time making my project.
The codes are too long to be posted here.
For instance, these imports in SQLiteDatabase.java are appearing in red:
import android.database.sqlite.SQLiteDebug.DbStats;
import dalvik.system.CloseGuard;
and my logcat shows the following errors:
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: FATAL EXCEPTION: main
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: android.database.sqlite.SQLiteException: no such table: user (code 1): , while compiling: select * from user
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1253)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at com.example.abcd.helloworld.DatabaseHelper.insertUser(DatabaseHelper.java:40)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at com.example.abcd.helloworld.SignUp$1.onClick(SignUp.java:52)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.view.View.performClick(View.java:4240)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:17721)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:730)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:92)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5103)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:525)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
All coding done by me seems to be correct.
The code for table creation is:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "user.db";
private static final String TABLE_NAME = "user";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_EMAIL = "email";
private static final String COLUMN_UNAME = "uname";
private static final String COLUMN_PASS = "pass";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table user (id integer primary key autoincrement," +
"name text, email text, uname text, pass text);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
this.db = db;
}
public void insertUser(User u) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from user";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put(COLUMN_ID, count);
values.put(COLUMN_NAME, u.getName());
values.put(COLUMN_EMAIL, u.getEmail());
values.put(COLUMN_UNAME, u.getUname());
values.put(COLUMN_PASS, u.getPass());
db.insert(TABLE_NAME, null, values);
}
public String searchPass(String uname) {
db = this.getReadableDatabase();
String query = "select uname, pass from" + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
String a, b;
b = "not found";
if (cursor.moveToFirst()) {
do {
a = cursor.getString(0);
if (a.equals(uname)) {
b = cursor.getString(1);
break;
}
}
while (cursor.moveToNext());
}
db.close();
return b;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS" + TABLE_NAME;
db.execSQL(query);
this.OnCreate(db);
}
private void OnCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
this.db = db;
}
}
You are using onCreate method twice in your code. Remove duplication.
Try below code:
public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "user.db";
public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "create table user(" +
"id integer primary key autoincrement, " +
"name text, "+
"email text, "+
"uname text, "+
"pass text"+
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "drop table if exists user";
db.execSQL(query);
onCreate(db);
}
/*
Remaining code
Please do not add onCreate and onUpgrade method anymore.
*/
}
Your code seems to be ok, try to debug the SQLite code. Execute the statement outside the android code. Open your terminal and execute the sql statement, and after that execute .tables, this command will show you the existed tables in your db.
More info, you can find here,
http://www.tutorialspoint.com/sqlite/sqlite_create_table.htm
I am working on a simple app for myself that posts information to a database. I'm really new at this and tried to follow some tutorials along with other tidbits to assemble this.
There is a home screen that gets to the second screen which has a button (add item). Onclicking, this is supposed to build/update the database. I get a crash when I enter that second screen before anything happens. I tried to put in breakpoints to debug but I can't even to get anywhere. It doesn't pause at my breakpoints (or doesn't seem to) so I can't see what's going on
Can anyone point in the right direction for debugging/fixing this?
This is my 2nd screen code - java
public class AddItem extends Activity {
private final String TAG = "Main Activity";
View view;
SQLiteDatabase db;
DbPrice dbprice ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
Log.i(TAG, "OnCreate");
dbprice = new DbPrice(this);
db = dbprice.getWritableDatabase();
Button addButton = (Button) findViewById(R.id.addNew);
addButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String subcat,item,store,extra;
Integer day,month,year,price,quantity,weight,volume;
Boolean sale;
DatePicker datePicker1 = (DatePicker) findViewById(R.id.datePicker1);
AutoCompleteTextView autoCompleteSubCat = (AutoCompleteTextView) findViewById(R.id.autoCompleteSubCat);
EditText editItem = (EditText) findViewById(R.id.editItem);
EditText editPrice = (EditText) findViewById(R.id.editPrice);
EditText editQuantity = (EditText) findViewById(R.id.editQuantity);
EditText editWeight = (EditText) findViewById(R.id.editWeight);
EditText editVolume = (EditText) findViewById(R.id.editVolume);
CheckBox checkSale = (CheckBox) findViewById(R.id.checkSale);
AutoCompleteTextView autoCompleteStore = (AutoCompleteTextView) findViewById(R.id.autoCompleteStore);
EditText editExtra = (EditText) findViewById(R.id.editExtra);
day = datePicker1.getDayOfMonth();
month = datePicker1.getMonth();
year = datePicker1.getYear();
subcat = autoCompleteSubCat.getText().toString();
item = editItem.getText().toString();
extra = editExtra.getText().toString();
price = Integer.parseInt(editPrice.getText().toString());
quantity = Integer.parseInt(editQuantity.getText().toString());
weight = Integer.parseInt(editWeight.getText().toString());
volume = Integer.parseInt(editVolume.getText().toString());
// sale = checkSale.isChecked();
store = autoCompleteStore.getText().toString();
ContentValues cv = new ContentValues();
cv.put(DbPrice.SUBCAT, subcat);
cv.put(DbPrice.ITEM, item);
cv.put(DbPrice.EXTRA, extra);
cv.put(DbPrice.PRICE, price);
cv.put(DbPrice.QUANTITY, quantity);
cv.put(DbPrice.WEIGHT, weight);
cv.put(DbPrice.VOLUME, volume);
cv.put(DbPrice.SALE, sale);
cv.put(DbPrice.STORE, store);
db.insert(DbPrice.TABLE_NAME, null, cv);
}
});
}
#Override
public void onStart() {
super.onStart();
Log.i(TAG, "OnStart");
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "OnResume");
}
public void OnPause() {
super.onPause();
Log.i(TAG,"OnPause");
}
public void OnStop() {
super.onStart();
Log.i(TAG, "OnStop");
}
public void OnDestroy() {
super.onDestroy();
Log.i(TAG, "OnDestroy");
}
public void addNewItem (View v) {
Log.i(TAG, "Starting New Activity");
Intent intent = new Intent (this, AllItems.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_item, menu);
return true;
}
}
The database class java is below. I don't know if you need the xml too but I included the catlog.
public class DbPrice extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "data";
public static final String TABLE_NAME = "price_table";
public static final String C_ID = "_id";
public static final String DAY = "day";
public static final String MONTH = "month";
public static final String YEAR = "day";
public static final String SUBCAT = "subcategory";
public static final String ITEM = "item";
public static final String PRICE = "price";
public static final String QUANTITY = "quantity";
public static final String WEIGHT = "weight";
public static final String VOLUME = "volume";
public static final String SALE = "sale";
public static final String STORE = "store";
public static final String EXTRA = "extra";
public static final int VERSION = 1;
private final String createDb = "create table if not exists " + TABLE_NAME+ " ( "
+ C_ID + " integer primary key autoincrement, "
+ DAY + " text, "
+ MONTH + " text, "
+ YEAR + " text, "
+ SUBCAT + " text, "
+ ITEM + " text, "
+ PRICE + " text, "
+ QUANTITY + " text, "
+ WEIGHT + " text, "
+ VOLUME + " text, "
+ SALE + " text, "
+ STORE + " text, "
+ EXTRA + " text) ";
public DbPrice(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createDb);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
db.execSQL("drop table " + TABLE_NAME);
}
}
CATLOG BELOW
12-29 01:27:20.834: I/Main Activity(1362): OnCreate
12-29 01:27:21.044: E/SQLiteLog(1362): (1) duplicate column name: day
12-29 01:27:21.054: D/AndroidRuntime(1362): Shutting down VM
12-29 01:27:21.064: W/dalvikvm(1362): threadid=1: thread exiting with uncaught exception (group=0xb4b11b90)
12-29 01:27:21.194: E/AndroidRuntime(1362): FATAL EXCEPTION: main
12-29 01:27:21.194: E/AndroidRuntime(1362): Process: com.unsuccessfulstudent.grocerypricehistory, PID: 1362
12-29 01:27:21.194: E/AndroidRuntime(1362): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.unsuccessfulstudent.grocerypricehistory/com.unsuccessfulstudent.grocerypricehistory.AddItem}: android.database.sqlite.SQLiteException: duplicate column name: day (code 1): , while compiling: create table if not exists price_table ( _id integer primary key autoincrement, day text, month text, day text, subcategory text, item text, price text, quantity text, weight text, volume text, sale text, store text, extra text)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.app.ActivityThread.access$700(ActivityThread.java:135)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.os.Handler.dispatchMessage(Handler.java:102)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.os.Looper.loop(Looper.java:137)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.app.ActivityThread.main(ActivityThread.java:4998)
12-29 01:27:21.194: E/AndroidRuntime(1362): at java.lang.reflect.Method.invokeNative(Native Method)
12-29 01:27:21.194: E/AndroidRuntime(1362): at java.lang.reflect.Method.invoke(Method.java:515)
12-29 01:27:21.194: E/AndroidRuntime(1362): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
12-29 01:27:21.194: E/AndroidRuntime(1362): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
12-29 01:27:21.194: E/AndroidRuntime(1362): at dalvik.system.NativeStart.main(Native Method)
12-29 01:27:21.194: E/AndroidRuntime(1362): Caused by: android.database.sqlite.SQLiteException: duplicate column name: day (code 1): , while compiling: create table if not exists price_table ( _id integer primary key autoincrement, day text, month text, day text, subcategory text, item text, price text, quantity text, weight text, volume text, sale text, store text, extra text)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1672)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1603)
12-29 01:27:21.194: E/AndroidRuntime(1362): at com.unsuccessfulstudent.grocerypricehistory.DbPrice.onCreate(DbPrice.java:49)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
12-29 01:27:21.194: E/AndroidRuntime(1362): at com.unsuccessfulstudent.grocerypricehistory.AddItem.onCreate(AddItem.java:31)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.app.Activity.performCreate(Activity.java:5243)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-29 01:27:21.194: E/AndroidRuntime(1362): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
12-29 01:27:21.194: E/AndroidRuntime(1362): ... 11 more
12-29 01:27:24.554: I/Process(1362): Sending signal. PID: 1362 SIG: 9
The reason for your app crash is caused by the fact that in your database creation query you are defining the same key twice. Thats why you are getting a duplicate column error.
Both the keys you have,i.e., DAY as well as YEAR have the same value day. You cannot have two columns in a database with the same name. So, to resolve this, all you need to do is change the YEAR definition to-
public static final String YEAR = "year";
Hope this helps!!!
You use two same columns
DAY = "day";
YEAR = "day";
Code:
create table if not exists price_table
(
_id integer primary key autoincrement,
"**day**" text,
month text,
"**day**" text,...
)
Whenever there is an Exception, if you see a line FATAL EXCEPTION: main in Logcat, look at the below lines. The line with Unable to start activity ComponentInfo, will give you a clear idea about the cause of exception. Still if you are confused, look for a line starting with Caused by:.
So here your problem is "duplicate column name: day".
Also you can navigate to the specific line which caused the exception. Just look for your package name. Here in this case,
12-29 01:27:21.194: E/AndroidRuntime(1362): at com.unsuccessfulstudent.grocerypricehistory.DbPrice.onCreate(DbPrice.java:49)
12-29 01:27:21.194: E/AndroidRuntime(1362): at com.unsuccessfulstudent.grocerypricehistory.AddItem.onCreate(AddItem.java:31)
At the end of the lines, There is corresponding class and line number. Note that these are the lines caused exception, but the cause of exception may be somewhere else. In this case, String YEAR
I am getting error in my code which is not understandable.. please help me find out what issue is it.
i have database class and main activity.. it shows in log but when it comes to appear at my emulator's screen it gives me error.
my database class:
package com.example.nearby_places;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Database extends SQLiteOpenHelper {
//database name & version number
private static final String db_name = "nearby_places";
private static final int db_version = 1;
//tables
private static final String table_placetypes = "placetypes";
private static final String table_places = "table_places";
//column names
private static final String type_id = "type_id";
private static final String type_name = "type_name";
private static final String place_id = "place_id";
private static final String place_name = "place_name";
private static final String place_address = "place_address";
private static final String place_contact = "place_contact";
public Database(Context context) {
super(context, db_name, null, db_version);
// TODO Auto-generated constructor stub
}
// create table queries
String create_table_placetypes = "CREATE TABLE IF NOT EXISTS " + table_placetypes + "("
+ type_id + " INTEGER PRIMARY KEY NOT NULL," + type_name + " TEXT" + ")";
String create_table_places = "CREATE TABLE IF NOT EXISTS table_places (place_id INTEGER PRIMARY KEY NOT NULL, place_name TEXT, place_address TEXT, place_contact TEXT, type_id INTEGER, FOREIGN KEY (type_id) REFERENCES table_placetypes(type_id))";
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(create_table_placetypes);
Log.d("creating", "placetypes created");
db.execSQL(create_table_places);
Log.d("creating", "places created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + table_placetypes);
db.execSQL("DROP TABLE IF EXISTS " + table_places);
onCreate(db);
}
// add placetypes
void addplacetypes (placetypes pt) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(type_name, pt.getTypename());
db.insert(table_placetypes, null, values);
db.close();
}
// Getting single placetypes
placetypes getPlacetypes(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(table_placetypes, new String[] {type_id,
type_name }, type_id + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
placetypes pt = new placetypes(Integer.parseInt(cursor.getString(0)),
cursor.getString(1));
// return contact
return pt;
}
// Getting All placetypes
public List<placetypes> getAllPlacetypes() {
List<placetypes> placetypesList = new ArrayList<placetypes>();
// Select All Query
String selectQuery = "SELECT * FROM " + table_placetypes;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
placetypes pt = new placetypes();
pt.setTypeid(Integer.parseInt(cursor.getString(0)));
pt.setTypename(cursor.getString(1));
//String name = cursor.getString(1);
//MainActivity.ArrayofName.add(name);
// Adding contact to list
placetypesList.add(pt);
} while (cursor.moveToNext());
}
// return placetype list
return placetypesList;
}
// Getting placetypes Count
public int getPlacetypesCount() {
String countQuery = "SELECT * FROM " + table_placetypes;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
public void addplaces(places p) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(place_name, p.getPlace_name());
values.put(place_address, p.getPlace_address());
values.put(place_contact, p.getPlace_contact());
values.put(type_id, p.getT_id());
Log.d("Type ID", String.valueOf(p.getT_id()));
db.insert(table_places, null, values);
db.close();
}
places getPlaces(int pid) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(table_places, new String[] {place_id, place_name, place_address, place_contact,type_id}, place_id + "=?", new String[] { String.valueOf(pid) } , null, null, null, null);
if(cursor != null)
cursor.moveToFirst();
places p = new places(Integer.parseInt(cursor.getString(0)),
Integer.parseInt(cursor.getString(1)),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4)
);
cursor.close();
return p;
}
public List<places> getAllPlaces(String typeName) {
List<places> placeList = new ArrayList<places>();
//String selectQuery = "SELECT * FROM table_places INNER JOIN placetypes ON placetypes.type_id=table_places.type_id ";
//String selectQuery = "SELECT * FROM table_places WHERE table_places.type_id="+Integer.toString(typeid);
String selectQuery ="SELECT * FROM table_places WHERE placetypes.place_name="+typeName+" INNER JOIN placetypes ON placetypes.type_id=table_places.type_id";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst() )
{
do{
places p = new places();
/*p.setT_id(cursor.getColumnIndex(type_id));
p.setPlace_id(cursor.getColumnIndex(place_id));
p.setPlace_name(cursor.getColumnIndex(place_name));
*/
p.setT_id(cursor.getInt(0));
p.setPlace_id(cursor.getInt(1));
p.setPlace_name(cursor.getString(2));
p.setPlace_address(cursor.getString(3));
p.setPlace_contact(cursor.getString(4));
/*String t_id = cursor.getString(4);
String p_name = cursor.getString(2);
String p_address = cursor.getString(3);
String p_contact = cursor.getString(1);*/
placeList.add(p);
}while(cursor.moveToNext());
}
cursor.close();
return placeList;
}
public int getPlaceCount () {
String selectQuery = "SELECT * FROM " +table_places;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(create_table_places, null);
cursor.close();
return cursor.getCount();
}
}
MainActivity
package com.example.nearby_places;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
private ListView listView;
public static ArrayList<String> ArrayofName = new ArrayList<String>();
public static final String PLACETYPE = "com.example";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Database db = new Database(this);
if(db.getAllPlacetypes().isEmpty())
{
/**
* CRUD Operations
* */
// Inserting Places
Log.d("Insert: ", "Inserting ..");
db.addplacetypes(new placetypes("RESTURAUNTS"));
db.addplacetypes(new placetypes("MALLS"));
db.addplacetypes(new placetypes("GAS STATIONS"));
db.addplacetypes(new placetypes("HOTELS"));
db.addplacetypes(new placetypes("MOTELS"));
}
// Reading all Places
Log.d("Reading: ", "Reading all placetypes..");
if(ArrayofName.isEmpty())
{
List<placetypes> placetypes = db.getAllPlacetypes();
for (placetypes pt : placetypes)
{
String log = "Id: "+pt.getTypeid()+" ,Name: " + pt.getTypename();
// Writing Places to log
Log.d("Name: ", log);
System.out.println(log);
ArrayofName.add(pt.getTypename());
}
}
listView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ArrayofName);
int pos = listView.getAdapter().getCount() -1;
listView.getAdapter().getItemId(pos);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
String type = ((TextView) v).getText().toString();
Toast.makeText(getApplicationContext(), type, Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(),MainActivity2.class);
i.putExtra(PLACETYPE, type);
startActivity(i);
/*Cursor cursor = (Cursor) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "id: " +id+ "position: " +position+ "row id: " +(cursor.getColumnIndex("" +
"")), Toast.LENGTH_LONG).show();
*/
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
}
}
);
}
}
Logcat
10-11 17:21:51.871: D/Reading:(4932): Reading all placetypes..
10-11 17:21:51.871: D/Name:(4932): Id: 1 ,Name: RESTURAUNTS
10-11 17:21:51.875: I/System.out(4932): Id: 1 ,Name: RESTURAUNTS
10-11 17:21:51.875: D/Name:(4932): Id: 2 ,Name: MALLS
10-11 17:21:51.875: I/System.out(4932): Id: 2 ,Name: MALLS
10-11 17:21:51.875: D/Name:(4932): Id: 3 ,Name: GAS STATIONS
10-11 17:21:51.875: I/System.out(4932): Id: 3 ,Name: GAS STATIONS
10-11 17:21:51.875: D/Name:(4932): Id: 4 ,Name: HOTELS
10-11 17:21:51.875: I/System.out(4932): Id: 4 ,Name: HOTELS
10-11 17:21:51.875: D/Name:(4932): Id: 5 ,Name: MOTELS
10-11 17:21:51.875: I/System.out(4932): Id: 5 ,Name: MOTELS
10-11 17:21:51.887: D/AndroidRuntime(4932): Shutting down VM
10-11 17:21:51.887: W/dalvikvm(4932): threadid=1: thread exiting with uncaught exception (group=0x41c77300)
10-11 17:21:51.894: E/AndroidRuntime(4932): FATAL EXCEPTION: main
10-11 17:21:51.894: E/AndroidRuntime(4932): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nearby_places/com.example.nearby_places.MainActivity}: java.lang.NullPointerException
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.os.Handler.dispatchMessage(Handler.java:99)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.os.Looper.loop(Looper.java:137)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-11 17:21:51.894: E/AndroidRuntime(4932): at java.lang.reflect.Method.invokeNative(Native Method)
10-11 17:21:51.894: E/AndroidRuntime(4932): at java.lang.reflect.Method.invoke(Method.java:511)
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-11 17:21:51.894: E/AndroidRuntime(4932): at dalvik.system.NativeStart.main(Native Method)
10-11 17:21:51.894: E/AndroidRuntime(4932): Caused by: java.lang.NullPointerException
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.example.nearby_places.MainActivity.onCreate(MainActivity.java:62)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.Activity.performCreate(Activity.java:5008)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
10-11 17:21:51.894: E/AndroidRuntime(4932): ... 11 more
10-11 17:21:53.695: I/Process(4932): Sending signal. PID: 4932 SIG: 9
Your call to getAdapter is returning null because you're calling it before setAdapter, try this instead :
listView.setAdapter(adapter);
int pos = listView.getAdapter().getCount() -1;
listView.getAdapter().getItemId(pos);
If you have a NULLPOINTER Exception please have a deep look at your LogCat. Especial at the Line where it says Caused by.
Learn how to read and use your LogCat, and try to find the Line where it mentions your class/package name and analyse this line.
Caused by: java.lang.NullPointerException
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.example.nearby_places.MainActivity.onCreate(MainActivity.java:62)
The problem is in
List<placetypes> placetypes = db.getAllPlacetypes();
The query you are using is wrong. It should be
`SELECT * FROM table_places INNER JOIN placetypes ON placetypes.type_id=table_places.type_id WHERE placetypes.place_name="+typeName+`"
I am trying to implement a SQLite database for a highscores table. I am just testing it to see if my database creation, insertion and selecting is working with the below code. I am trying to insert the first row into the database and then immediately pull from it and display the values to TextViews. All of the hardcoding is for testing purposes to just get the database working correctly.
I am getting a IllegalStateException on the below lines. I have commented in the errors on the appropriate lines.
Any additional advice on code structure is much appreciate too.
Thank you in advance!
Highscores.java
public class Highscores extends Activity {
DatabaseHelper dh;
SQLiteDatabase db;
int percentages;
long scores;
TableLayout table;
TableRow rowHeader, row1, row2, row3, row4, row5, row6, row7, row8, row9, row10;
TextView rank, percentage, score;
Button btn1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.highscoresmain);
dh = new DatabaseHelper(this);
db = dh.openDB();
long x = 11;
int y = 22;
dh.insert(x, y);
percentages = dh.getPercentage(db); //Line 45
scores = dh.getScore(db);
Button btn1 = (Button)findViewById(R.id.homeBtn);
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);
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;
private static final String TABLE = "HighscoresList";
public static DatabaseHelper mSingleton = null;
// 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 synchronized static DatabaseHelper getInstance(Context context) {
if(mSingleton == null) {
mSingleton = new DatabaseHelper(context.getApplicationContext());
}
return mSingleton;
}
public SQLiteDatabase openDB() {
db = this.getWritableDatabase();
return db;
}
//I am using hard coded numbers in the below 2 methods for testing purposes.
public long getScore(SQLiteDatabase db) {
Cursor c = db.rawQuery("SELECT " + SCORE + " FROM " + TABLE + " WHERE " + SCORE + " = " + 11 + ";", null); //Line 45
long i = 0;
if(c.getCount() != 0) {
c.moveToFirst();
int columnIndex = c.getInt(c.getColumnIndex("SCORE"));
if(columnIndex != -1) {
i = c.getLong(columnIndex);
} else {
i = 999;
}
} else {
i = 555;
}
c.close();
return i;
}
public int getPercentage(SQLiteDatabase db) {
Cursor c = db.rawQuery("SELECT " + PERCENTAGE + " FROM " + TABLE + " WHERE " + PERCENTAGE + " = " + 22 + ";", null);
int i = 0;
if(c.getCount() != 0) {
c.moveToFirst();
int columnIndex = c.getInt(c.getColumnIndex("PERCENTAGE"));
if(columnIndex != -1) {
i = c.getInt(columnIndex);
} else {
i = 999;
}
} else {
i = 555;
}
c.close();
return i;
}
//Insert new record.
public long insert(long score, int percentage) {
ContentValues values = new ContentValues();
values.put(SCORE, score);
values.put(PERCENTAGE, percentage);
return db.insert(TABLE, null, values);
}
}
LogCat output
01-03 15:39:13.952: E/AndroidRuntime(938): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.Highscores}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
01-03 15:39:13.952: E/AndroidRuntime(938): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.os.Handler.dispatchMessage(Handler.java:99)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.os.Looper.loop(Looper.java:137)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-03 15:39:13.952: E/AndroidRuntime(938): at java.lang.reflect.Method.invokeNative(Native Method)
01-03 15:39:13.952: E/AndroidRuntime(938): at java.lang.reflect.Method.invoke(Method.java:511)
01-03 15:39:13.952: E/AndroidRuntime(938): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-03 15:39:13.952: E/AndroidRuntime(938): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-03 15:39:13.952: E/AndroidRuntime(938): at dalvik.system.NativeStart.main(Native Method)
01-03 15:39:13.952: E/AndroidRuntime(938): Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
01-03 15:39:13.952: E/AndroidRuntime(938): at android.database.CursorWindow.nativeGetLong(Native Method)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.database.CursorWindow.getLong(CursorWindow.java:507)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.database.CursorWindow.getInt(CursorWindow.java:574)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.database.AbstractWindowedCursor.getInt(AbstractWindowedCursor.java:69)
01-03 15:39:13.952: E/AndroidRuntime(938): at com.example.test.DatabaseHelper.getPercentage(DatabaseHelper.java:67)
01-03 15:39:13.952: E/AndroidRuntime(938): at com.example.test.Highscores.onCreate(Highscores.java:45)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.app.Activity.performCreate(Activity.java:5104)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-03 15:39:13.952: E/AndroidRuntime(938): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-03 15:39:13.952: E/AndroidRuntime(938): ... 11 more
EDIT: I updated my getScore() and getPercentage() methods. Anyways, I still used some hardcoded numbers so I know exactly what is going on but the program is still crashing. It seems that the if-else statement should set i to 555 instead of crashing but it isn't.
I updated the LogCat output also.
I don't see any database initializing code overriding onCreate but it says your column doesn't exist in the table check it's name again or check the table. Also get into the habit of closing your cursors once your done using them. Otherwise the database will throw errors when you haven't closed a previous cursor.
Just noticed the error its you're using "PERCENTAGE" while you defined it as
PERCENTAGE = "percentage";
so just be consistent in using the defined variable.
Android - SQLite Cursor getColumnIndex() is case sensitive?
public int getPercentage(SQLiteDatabase db) {
Cursor c = db.rawQuery("SELECT " + PERCENTAGE + " FROM " + TABLE + " WHERE " + PERCENTAGE + " = " + 22 + ";", null);
int i = 0;
if (c.moveToFirst())
{
int colIdx = c.getColumnIndex(PERCENTAGE);
if (colIdx != -1) // Column exists
i = c.getInt(colIdx); //Line 54
}
c.close();
return i;
}
Building off of David's comment:
public int getPercentage(SQLiteDatabase db) {
Cursor c = db.rawQuery("SELECT " + PERCENTAGE + " FROM " + TABLE + " WHERE " + PERCENTAGE + " = " + 22 + ";", null);
if(c.getCount() != 0){
c.moveToFirst();
int i = c.getInt(c.getColumnIndex(PERCENTAGE)); //Line 54
return i;
} else { return 0 }
}
Use the constant consistently, and make sure it's exactly like your sqllite DB. Apparently getColumnIndex is case sensitive ;)