java.lang.IllegalStateException: get field slot from row 0 col 25 failed - android

I am trying to create a android app using GreenDAO, this is ERP kind of project so practically it is not possible to post all code here, but i am going to share only related code
QueryBuilder<PartyCommunication> partyCommQueryBuilder = partyCommunicationDao.queryBuilder();
partyCommQueryBuilder = partyCommQueryBuilder.where(
PartyCommunicationDao.Properties.CommType.eq("ALERT"),
PartyCommunicationDao.Properties.ReferenceCategory.eq("Low Stock"));
List<PartyCommunication> listOfPartyComm = partyCommQueryBuilder.list();
PartyCommunication daoPartyCommunication = listItr.next();
Long reference_entity_key = daoPartyCommunication.getReferenceEntityKey();
Product product = daoSessionUni.getProductDao().load(reference_entity_key);
ProductDetail productDetail = new ProductDetail(product);
Integer inventoryQOH= productDetail.getInventoryQOH();
I am getting exception in this line
Product product = daoSessionUni.getProductDao().load(reference_entity_key);
When i debug our application i found that it throwing exception from one of our DAO class as below
public Product readEntity(Cursor cursor, int offset) {
Product entity = new Product( //
.
.
.
.
cursor.getShort(offset + 23) != 0, // isSync
cursor.getShort(offset + 24) != 0, // isDeleted
cursor.getString(offset + 25), // createdBy
cursor.getString(offset + 26), // modifiedBy
cursor.isNull(offset + 27) ? null : new java.util.Date(cursor.getLong(offset + 27)), // lastSyncTime
new java.util.Date(cursor.getLong(offset + 28)), // created
new java.util.Date(cursor.getLong(offset + 29)) // modified
);
return entity;
}
In this line
cursor.getString(offset + 25), // createdBy
This is our 25th column of table.I know that all code is not enough to understand what is going wrong and why i am getting this exception , so i am also going to post logcat output
java.lang.IllegalStateException: get field slot from row 0 col 25 failed
at net.sqlcipher.CursorWindow.getString_native(Native Method)
at net.sqlcipher.CursorWindow.getString(CursorWindow.java:382)
at net.sqlcipher.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at android.database.CursorWrapper.getString(CursorWrapper.java:114)
at com.tarnea.kareeb.model.ProductDao.readEntity(ProductDao.java:273)
at com.tarnea.kareeb.model.ProductDao.readEntity(ProductDao.java:1)
at de.greenrobot.dao.AbstractDao.loadCurrent(AbstractDao.java:417)
at de.greenrobot.dao.AbstractDao.loadUnique(AbstractDao.java:163)
at de.greenrobot.dao.AbstractDao.loadUniqueAndCloseCursor(AbstractDao.java:150)
at de.greenrobot.dao.AbstractDao.load(AbstractDao.java:139)
at com.tarnea.android.DataCleaningService.adjustLowStockAlertTable(DataCleaningService.java:115)
at com.tarnea.sync.kareeb.pharma.syncadapter.SyncManager.performSync(SyncManager.java:970)
at com.tarnea.sync.kareeb.pharma.syncadapter.SyncAdapter.onPerformSync(SyncAdapter.java:96)
at android.content.AbstractThreadedSyncAdapter$SyncThread.run(AbstractThreadedSyncAdapter.java:254
Thanks in advance to all.If anybody have some interest to solve my problem then please please ask any further information whatever you want.

Your problem isn't the query. The SQLite-Table simply does only contain 24 columns.
Probably you modified your database schema by adding new columns like createdBy.
Either you forgot to update your db using OpenHelper
Or you had an error in your ALTER TABLE-statements
Or you ran your app with the new schema-version but without your ALTER TABLE-statements yet included (which is practically the same as 1.
Have a look at your database using SqliteManager, to verify your tables have the columns you expect.
If you cannot get your database-file you can simply delete your app with all data or increase your schema-version and use the DevOpenHelper to recreate the whole database.

Related

Google Sheets API v4 - How to get the last row with value?

How to get the last row with value in the new Google Sheets API v4 ?
i use this to get a range from a sheet:
mService.spreadsheets().values().get("ID_SHEET", "Sheet1!A2:B50").execute();
how to detect the last row with value in the sheet ?
You can set the range to "A2:D" and this would fetch as far as the last data row in your sheet.
I managed to get it by counting the total rows from current Sheets.
Then append the data to the next row.
rowcount = this.mService.spreadsheets().values().get(spreadsheetId, range).execute().getValues().size()
Rather than retrieving all the rows into memory just to get the values in the last row, you can use the append API to append an empty table to the end of the sheet, and then parse the range that comes back in the response. You can then use the index of the last row to request just the data you want.
This example is in Python:
#empty table
table = {
'majorDimension': 'ROWS',
'values': []
}
# append the empty table
request = service.spreadsheets().values().append(
spreadsheetId=SPREADSHEET_ID,
range=RANGE_NAME,
valueInputOption='USER_ENTERED',
insertDataOption='INSERT_ROWS',
body=table)
result = request.execute()
# get last row index
p = re.compile('^.*![A-Z]+\d+:[A-Z]+(\d+)$')
match = p.match(result['tableRange'])
lastrow = match.group(1)
# lookup the data on the last row
result = service.spreadsheets().values().get(
spreadsheetId=SPREADSHEET_ID,
range=f'Sheetname!A{lastrow}:ZZ{lastrow}'
).execute()
print(result)
😢 Google Sheets API v4 does not have a response that help you to get the index of the last written row in a sheet (row that all cells below it are empty). Sadly, you'll have to workaround and fetch all sheet rows' into memory (I urge you to comment if I'm mistaken)
Example:
spreadsheet_id = '1TfWKWaWypbq7wc4gbe2eavRBjzuOcpAD028CH4esgKw'
range = 'Sheet1!A:Z'
rows = service.spreadsheets().values().get(spreadsheetId=spreadsheet_id, range=range).execute().get('values', [])
last_row = rows[-1] if rows else None
last_row_id = len(rows)
print(last_row_id, last_row)
Output:
13 ['this', 'is ', 'my', 'last', 'row']
💡 If you wish to append more rows to the last row, see this
You don't need to. Set a huge range (for example A2:D5000) to guarantee that all your rows will be located in it. I don't know if it has some further impact, may be increased memory consumption or something, but for now it's OK.
private List<String> getDataFromApi() throws IOException {
String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
String range = "A2:D5000";
List<String> results = new ArrayList<String>();
ValueRange response = this.mService.spreadsheets().values()
.get(spreadsheetId, range)
.execute();
List<List<Object>> values = response.getValues();
if (values != null) {
results.add("Name, Major");
for (List row : values) {
results.add(row.get(0) + ", " + row.get(3));
}
}
return results;
}
Look at the loop for (List row : values). If you have two rows in your table you will get two elements in values list.
Have a cell somewhere that doesn't interfere with your datarange with =COUNTA(A:A) formula and get that value.
In your case
=MAX(COUNTA(A:A50),COUNTA(B:B50))
?
If there could be empty cells inbetween the formula would be a little more tricky but I believe it saves you some memories.
2022 Update
I I don’t know if this will be relevant for someone in 2022, but now you can do it differently.
You can just set next value as range :
const column = "A"
const startIndex = 2
const range = column + startIndex + ":" + column
In resolve you get all data in column and range with last index.
I tested it on js and php
Following Mark B's answer, I created a function that performs a dummy append and then extracts the last row info from the dummy append's response.
def get_last_row_with_data(service, value_input_option="USER_ENTERED"):
last_row_with_data = '1'
try:
dummy_request_append = service.spreadsheets().values().append(
spreadsheetId='<spreadsheet id>',
range="{0}!A:{1}".format('Tab Name', 'ZZZ'),
valueInputOption='USER_ENTERED',
includeValuesInResponse=True,
responseValueRenderOption='UNFORMATTED_VALUE',
body={
"values": [['']]
}
).execute()
a1_range = dummy_request_append.get('updates', {}).get('updatedRange', 'dummy_tab!a1')
bottom_right_range = a1_range.split('!')[1]
number_chars = [i for i in list(bottom_right_range) if i.isdigit()]
last_row_with_data = ''.join(number_chars)
except Exception as e:
last_row_with_data = '1'
return last_row_with_data

How to insert a table in to group in Corona SDK (.Lua)?

I get error message when i try to insert a table into a group
My table code is containing images
Here is the code i am using for the table
local myJoints = {}
for i = 1,5 do
local link = {}
for j = 1,17 do
link[j] = display.newImage( "link.png" )
link[j].x = 121 + (i*34)
link[j].y = 55 + (j*17)
physics.addBody( link[j], { density=2.0, friction=0, bounce=0 } )
-- Create joints between links
if (j > 1) then
prevLink = link[j-1] -- each link is joined with the one above it
else
prevLink = wall -- top link is joined to overhanging beam
end
myJoints[#myJoints + 1] = physics.newJoint( "pivot", prevLink, link[j], 121 + (i*34), 46 + (j*17) )
end
end
and here is the code for group
GUI:insert(myJoints);
i have my background image in the GUI group and it is covering the table.
I don't know if it is actually possible to insert table into a group
Any help please
Thanks in Advance!
You can't insert a table into a group using the "insert" method because that method is looking for a display object. Try calling GUI.myJoints = myJoints. Also keep in mind that your table just references your display objects, which is different from having them in a group.

Check Value from mysql using android

I have a table which has a field called Sold , in that field i store 0 and 1.
So 1 means sold and 0 mean Available.
K, my problem is that ,I want to change 0 to available and 1 to sold when i diplay information into my emulator , here what i tried but it returning sold even though i have 0 in my database :
if (sold.length()==0){
Log.d("checking","Inside = 0");
val = "Available";}
else if (sold.length()>0)
Log.d("checking","Inside = 1");
val = "Sold
And sold contains a value from a database.
please help to change 0 to Available and 1 to Sold.
if(sold.equalIgnoreCase("0"))
{
Log.d("checking","Inside = 0");
}else
{
Log.d("checking","Inside = 1");
}
The sold.length you have there is the actual length of the String representation "sold" that you are using. Meaning that if you have the word "some" this .length() equals 4.
So in your snippet the sold variable is the "0" or "1" respectively so the sold.length() always equals to 1. Try to cast the String variable into an Integer and make the comparison or even better try to make the variable into Integer from the beginning.

Display all records that are stored in SQlite database

I want to display all my records that are stored in the database
c = db.DBhelper.getChamp1(c.getCount);
//startManagingCursor(c);
int j = 0;
stateNameArray = new String[c.getCount()];
c.moveToFirst();
while(!c.isAfterLast()) {
stateNameArray[j] = c.getString(0);
j++;
Log.i("DEBUG_SQL","" + c.getString(0)+ " "+c.getString(j));
c.moveToNext();
}
//String resultat = ;
Log.i("DEBUG_SQL","" + c.getColumnIndex("article"));
I get an error when I write c.getCount – why? When I write a number like 1 or 2 or 3... that works.
And if I write
c = db.rawQuery("SELECT * FROM loan", null);
I get an error, but if I write
db.rawQuery("SELECT * FROM loan WHERE _id=1", null);
That works. Why?
At the very least, I see a problem with this log statement, where c.getString(j) doesn't make sense. And it may trigger an error as j gets larger.
Log.i("DEBUG_SQL","" + c.getString(0)+ " "+c.getString(j));
What data did you intend to access with the statement c.getString(j)?
On the getCount error. I assumed the error in the following was a typo. But is this where the error associated with getCount was located?
c = db.DBhelper.getChamp1(c.getCount);
But I shouldn't assume - you never know. It should read (add brackets to the method call).
c = db.DBhelper.getChamp1(c.getCount());
And as #Barak mentioned, what is going on with this statement?
To answer the question about your getCount isuue, you get the error because of this:
c = db.DBhelper.getChamp1(c.getCount);
You're trying to get the count of the cursor before you have it (and you're missing ()).
This would work since you have a cursor to count before you pull the next one:
c = db.getSomeCursor;
c1 = db.DBhelper.getChamp1(c.getCount());
Let us know what you're trying to achieve (I can't figure it out from the code you posted) and maybe we can be more helpful.

Android: Need Advice on SQLite, searching slow

I have to search a database that is 26024 entries and counting. It used to be fast with less records but now is taking like 10 seconds and slowing the app. I was wondering if i could get advice as to how speed up the process or if i'm doing anything wrong. Here is the code.
while (cursor.moveToNext()) {
String word = cursor.getString(0);
if (word.equals(input)) {
String nikus = cursor.getString(1);
String def = cursor.getString(2);
ret.append(" " + nikus + "\n"+ def + "\n");
g = null;
}
EDIT:
In my Database i have a definitions table and in the table there are 3 fields one is the words to be compared to, the sencond is the full word, and the third is the definition itself. Hopefully that helps you guys a little more.
CREATE TABLE [definitions] (
[word] TEXT,
[fullword] TEXT,
[definition] TEXT);
EDIT: here is the error im getting
01-04 00:47:54.678: E/CursorWindow(4722): need to grow: mSize = 1048576, size = 17, freeSpace() = 13, numRows = 15340
laalto's comment above is correct. You should be running a select with a where clause that only pulls back the rows where word is equal to input (don't forget about case sensitivity.) An index on the word column will help the query go even faster.

Categories

Resources