I have a sqlitedatabase I'm implementing within my app and I keep receiving an IllegalStateException when launching.
09-21 22:48:26.749 15762-16277/nz.co.exium.panther E/AndroidRuntime﹕ FATAL EXCEPTION: SyncAdapterThread-2
java.lang.IllegalStateException: Couldn't read row 0, col 4 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:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at android.database.CursorWrapper.getString(CursorWrapper.java:114)
at nz.co.exium.panther.sync.PantherSyncAdapter.getRegistrationId(PantherSyncAdapter.java:269)
at nz.co.exium.panther.sync.PantherSyncAdapter.onPerformSync(PantherSyncAdapter.java:64)
at android.content.AbstractThreadedSyncAdapter$SyncThread.run(AbstractThreadedSyncAdapter.java:254)
I believe this is caused by the query returning a fairly empty table (except for _ID that is autoincremented) and then when I attempt to get a String from the cursor.
String registrationID = "";
Uri uri = CustomerEntry.CONTENT_URI;
Cursor cursor = mContext.getContentResolver().query(uri, CUSTOMER_PROJECTION, null, null, null);
if (cursor.moveToFirst()) {
registrationID = cursor.getString(INDEX_CUST_REGID);
}
SQL create table call:
final String SQL_CREATE_CUSTOMER_TABLE = "CREATE TABLE " + CustomerEntry.TABLE_NAME + " (" +
CustomerEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
CustomerEntry.COLUMN_CUST_NAME + " TEXT NOT NULL, " +
CustomerEntry.COLUMN_CUST_EMAIL + " TEXT NOT NULL, " +
CustomerEntry.COLUMN_CUST_QRHASH + " TEXT NOT NULL," +
CustomerEntry.COLUMN_CUST_REGID + " TEXT NOT NULL)";
In this case, the INDEX_CUST_REGID is a final static int related to the position in the String[] projection, 3rd position in this case. It makes sense this would throw but is there a method or way to query the SyncAdapter for a specific column like the CUST_REGID or a method to check if the Column requested was returned before attempting a cursor.getString()?
This also might solve another problem I have with saving the Reg ID before knowing the EMAIL, NAME, QRHASH. Can't insert just one column without the rest having a value as well (NOT NULL), even though it would be worthless data and overwritten asap.
Method attempting to store Reg ID.
private void storeRegistrationID(Context context, String regID) {
//DB insert regid
ContentValues cValues = new ContentValues();
cValues.put(CustomerEntry.COLUMN_CUST_NAME, "");
cValues.put(CustomerEntry.COLUMN_CUST_EMAIL, "");
cValues.put(CustomerEntry.COLUMN_CUST_QRHASH, "");
cValues.put(CustomerEntry.COLUMN_CUST_REGID, regID);
mContext.getContentResolver().insert(CustomerEntry.CONTENT_URI, cValues);
}
projection as requested:
String[] CUSTOMER_PROJECTION = new String[]{
CustomerEntry._ID,
CustomerEntry.COLUMN_CUST_NAME,
CustomerEntry.COLUMN_CUST_EMAIL,
CustomerEntry.COLUMN_CUST_QRHASH,
CustomerEntry.COLUMN_CUST_REGID
};
Are you certain the table was actually created? There's a semi-colon mising from the end of your SQL_CREATE_CUSTOMER_TABLE text string - although I'm not sure if it is mandatory to run the sql for creating the table. I would suggest running it on the Eclipse emulator, then from the DDMS perspective, take a copy of the database somewhere where you can open it with the SQLite Manager plugin for Firefox - this will show you the database tables.
Related
So I have a method that allows me to get the id of a certain item by using a name i already have in an SQL Database. How would I go about getting the entire row of information and storing each item in its own variable.
Method that only works with ID
public Cursor getID(String name){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query = " SELECT " + COL1 + " FROM " + TABLE_NAME + " WHERE " + COL2 + " = '" + name + "'";
Cursor data = sqLiteDatabase.rawQuery(query, null);
return data;
}
And the method that gets the query and stores the result
Cursor data = mydb2.getID(name);
int itemId= -1;
while(data.moveToNext()){
itemId = data.getInt(0);
}
Using this method below how would i store all of the data in its own variable using this (or any other way to get data of entire row).
public Cursor rowData(String name){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query = " SELECT * FROM " + TABLE_NAME + " WHERE " + COL2 + " = '" + name + "'";
Cursor data = sqLiteDatabase.rawQuery(query, null);
return data;
}
I know this might be a dumb question, and I have tried looking at other questions, I have gotten this far I just don't know what to do next (I'm very new to Sq Lite databases and Android development)
You'd use something like :-
Cursor csr = instance_of_yourdbhelper.rowData();
while(csr.moveToNext()) {
long thisItemId = csr.getLong(csr.getColumnIndex(yourdbhelper.COL_1));
String thisName = csr.getString(csr.getColumnIndex(yourdbhelper.COL_2));
// etc for other columns
}
Notes
yourdbhelper is the class for your DatabaseHelper which is the class that extends SQLiteOpenHelper (the assumption is that the above methods are from such a class, as this is a common usage of SQLite)
instance_of_yourdbhelper is the instance of the DatabaseHelper class i.e. you may have yourdbhelper dbhlpr = new yourdbhelper(parameters);, in which case dbhlpr is the instance.
This just overwrites the same variables (thisItemId and thisName) for each row in the cursor, although there is perhaps the likliehood that the rowData method only returns one row.
You will likely encounter fewer errors using the getColumnIndex method as it returns the offset according to the column name. Miscalculated offsets is a frequent cause of problems.
You may wish to handle a no rows returned situation in which case you can use cursor.getCount(), which will return the number of rows in the cursor.
I am making a app that incorporates login/register functionalities and I'm making a issue that I have been trying to solve.
When a user logins and the login is successful, I'd like to use the email that they signed in with to pass to the next activity using Intent (I checked that the email is in fact getting passed by displaying what is being passed through the intent) and then passing that email to a function in the Dbhelper that uses that email to look for the name of the person that signed in then displaying "Welcome (name of person)" in the current activity but I keep getting a null returned in the function which ultimately leads to the app crashing.
Here is where I'm calling the function in the activity where I want to display the name.
if(!session.loggedIn())
{
Logout();
}
else
{
Intent in = getIntent();
String email = in.getStringExtra("email");
Name.setText("Welcome " + db.findName(email));
}
And this is the function in my DbHelper.java where I'm looking for the name with a query and such.
public String findName(String user_email)
{
String query = "SELECT " + COLUMN_NAME + " FROM " + USER_TABLE + " WHERE " + COLUMN_EMAIL + " = " + "'" + user_email + "'";
SQLiteDatabase db = this.getWritableDatabase();
//reads for database
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
if(c.getCount() > 0) // if cursor is not empty
{
String n = c.getString(0);
return n;
}
else
{
return null;
}
}
As you can see, it's returning null. And yes there is entries in the database already. Also, I tried just passing the email to the function and returning what was passed and it still gave me an error.
Normally, to check for a value in a text column, you do not use the equal = sign, but rather WHERE Column LIKE '%text%'. Also, when saving to a database you should escape and "sanitize" strings. If you did this, then you should also be doing the same process when looking for them, else you won't find them.
I am telling you this since, even if you are sure there are entries in your table, the result of the query may be empty. You could just debug by printing the result of the c.getCount() call or something.
I am working on an android application that uses two databases. Recently, I had to add a new column to one of the databases. Upon doing so, it broke my database. Installing and re-installing the application on my device did nothing, and I also updated the DB version.
Trying to insert data will net me this error:
E/SQLiteLog﹕ (1) table message_table has no column named msg_type
So, I tried taking out the "msg_type" column from the insert, and inserting data which gave me this error:
E/SQLiteLog﹕ (1299) abort at 8 in [INSERT INTO message_table(recipient,message) VALUES (?,?)]: NOT NULL constraint failed: message_table.msg_typeTEXT
Here is the oncreate:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + //msg_id
COL_2 + " TEXT NOT NULL, " + //recipient
COL_3 + " TEXT, " + //message
COL_4 + "TEXT NOT NULL);"); //message type
}
and the insert class:
public boolean addMessage(String recipient, String message, String type){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//populate message object
contentValues.put(COL_2, recipient);
contentValues.put(COL_3, message);
contentValues.put(COL_4, type);
//insert new message
long result = db.insert(TABLE_NAME, null, contentValues);
//check if operation was successful
if(result == -1)
return false;
else
return true;
}
How can I be getting an error for either case? I thought that it didn't recognize the new column was added from the first error, but it also doesn't like not receiving the data for that column.
The error is happening because there is no space between the column name and the TEXT. So the column name becomes message_table.msg_typeTEXT:
COL_4 + "TEXT NOT NULL);"); //message type
This should fix the error:
COL_4 + " TEXT NOT NULL);"); //message type
I have an application in Android (running 4.0.3) that stores a lot of data in Table A. Table A resides in SQLite Database. I am using a ContentProvider as an abstraction layer above the database.
Lots of data here means almost 80,000 records per month. Table A is structured like this:
String SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_A + " ( " +
COLUMN_ID + " INTEGER PRIMARY KEY NOT NULL" + "," +
COLUMN_GROUPNO + " INTEGER NOT NULL DEFAULT(0)" + "," +
COLUMN_TIMESTAMP + " DATETIME UNIQUE NOT NULL" + "," +
COLUMN_TAG + " TEXT" + "," +
COLUMN_VALUE + " REAL NOT NULL" + "," +
COLUMN_DEVICEID + " TEXT NOT NULL" + "," +
COLUMN_NEW + " NUMERIC NOT NULL DEFAULT(1)" + " )";
Here is the index statement:
String SQL_CREATE_INDEX_TIMESTAMP = "CREATE INDEX IF NOT EXISTS " + TABLE_A +
"_" + COLUMN_TIMESTAMP + " ON " + TABLE_A + " (" +
COLUMN_TIMESTAMP + ") ";
I have defined the columns as well as the table name as String Constants.
I am already experiencing significant slow down when retrieving this data from Table A. The problem is that when I retrieve data from this table, I first put it in an ArrayList and then I display it. Obviously, this is possibly the wrong way of doing things. I am trying to find a better way to approach this problem using a ContentProvider. But this is not the problem that bothers me.
The problem is for some reason, it takes a lot longer to retrieve data from other tables which have only upto 12 records maximum. I see this delay increase as the number of records in Table A increase. This does not make any sense. I can understand the delay if I retrieve data from Table A, but why the delay in retrieving data from other tables.
To clarify, I do not experience this delay if Table A is empty or has less than 3000 records.
What could be the problem?
EDIT: 09/14/2012 9:53 AM
To clarify, I am using a ContentProvider to manage the database. To query the data, I am using the context.getContentResolver().query method.
My query code in the ContentProvider:
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
final SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
final SQLiteDatabase db = dbHelper.getReadableDatabase();
String tableName = getTableName(uri);
queryBuilder.setTables(tableName);
Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
So this is embarrassing:
Apparently, there was one line of code somewhere during the Application Load that was retrieving data from Table A. That was what was slowing down the application as a whole.
In any case, I still have to figure out how to optimize loading data from Table A using a ContentProvider.
I have an SQL table which is created by the following code:
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + _ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + SUBJECT
+ " TEXT NOT NULL," + TOPIC + " TEXT NOT NULL, "
+ LECTURENUMBER + " TEXT NOT NULL, " + PAGENUMBER
+ " TEXT NOT NULL, " + DATE + " TEXT NOT NULL, " + _DATA
+ " TEXT NOT NULL);");
}
I query the table as follows:
String sql = "SELECT " + _ID + "," + SUBJECT + " FROM " + TABLE_NAME
+ " GROUP BY " + SUBJECT + ";";
Cursor cursor = subjects.getReadableDatabase().rawQuery(sql, null);
The problem is I have to start an Activity A if the cursor is empty(i.e. the table is storing no values) and Activity B if the cursor is not empty(i.e. table is filled).
I am unable to find a method which can tell me if the table is empty or not.
I Have tried to used Log as follows:
private void showSubjectsOnList() {
String sql = "SELECT " + _ID + "," + SUBJECT + " FROM " + TABLE_NAME
+ " GROUP BY " + SUBJECT + ";";
Cursor cursor = subjects.getReadableDatabase().rawQuery(sql, null);
Log.d("Events",Integer.toString(cursor.getCount()));
if(cursor.isNull(0)!=false){
cursor.close();
subjects.close();
startActivity(new Intent(this,OpenScreen.class));
}
}
But the LOG shows 1, if the table is empty...and again 1, if table has 1 entry....it shows 2, if table has two entries and so on.
Can you suggest some method of solving my problem of starting different activities based on if cursor is empty or not.
What about testing the cursor like this, and then doing what you've said:
if(cursor!=null && cursor.getCount()>0)
getCount ()
Returns the numbers of rows in the cursor
http://developer.android.com/reference/android/database/Cursor.html#getCount()
The easiest and cleanest way to test for an empty cursor is the following code:
if ( cursor.moveToFirst() ) {
// start activity a
} else {
// start activity b
}
Per the docs, the method returns false if the cursor is empty:
http://developer.android.com/reference/android/database/Cursor.html#moveToFirst%28%29
public abstract boolean moveToFirst ()
Added in API level 1 Move the cursor to the first row.
This method will return false if the cursor is empty.
Returns whether the move succeeded.
You just need to use getCount().
If your sql is correct but doesn't return any row you will have a NOT null cursor object but without a rows and getCount() will return 0.
Deleted records remain in SQLite as null records, but getCount() counts only not null records. If your table has some records that are null, some of not null records will have _Id numbers bigger than result of getCount(). To reach them, you can iterate cursor ( using for() loop ) double the number of times than result of getCount() and use the cursor to fill record_Id numbers into an array. Lets say resulting array is { 1, 2, 5, 6, 7, 8, 9, 11, 12, 14 }.
That means records 3, 4, 10, 13, are null records and your table has 14 record all together, not 10 that you got from getCount().
Remember:
getCount() returns number of not null records ,
cursor returns _Id numbers of not null records,
_Id numbers "missed" by cursor are _Id numbers of null records,
must reach sufficiently further than getCount() to get them all.
My suggestion would be using a ListActivity.
Those are Activity's which are meant to display items in a ListView. You can simply use a SimpleCursorAdapter to populate them (also illustrated in the ListActivitys JavaDoc page).
They also offer a setEmptyView()-method, which can be used to display a View (might be a TextView) which informs the user that there are no records yet and how he can create one.
An example on how to do that can be found here.
I believe your problem is you're not creating a proper query.
You should use the SQLiteDatabase query.
Cursor c = db.query(TABLE_NAME, null,
null, null, null, null, null);
You then can use c.getCount() to determine if the table has anything.