Android : set selected item of a Spinner from DB with Cursor - android

I have a problem with Cursors.
I have 3 tables in my DB : facture (means invoice), vehicule (vehicle) and garage.
An invoice concerns one vehicle and one garage. When I create an invoice, I select the vehicle and the garage from spinners.
When I want to update an invoice, I need to set the item selected in these spinners.
Here is how I do :
for (int iVhc = 0; iVhc < spListeVhc.getCount(); iVhc++) {
Cursor valueVhc = (Cursor) spListeVhc.getItemAtPosition(iVhc);
long idVhc = facture.getLong(facture.getColumnIndexOrThrow("TB_VEHICULE._id"));
long idSpVhc = valueVhc.getLong(valueVhc.getColumnIndex("TB_VEHICULE._id"));
if (idSpVhc == idVhc) {
spListeVhc.setSelection(iVhc);
}
}
for (int iGar = 0; iGar < spListeGar.getCount(); iGar++) {
Cursor valueGar = (Cursor) spListeGar.getItemAtPosition(iGar);
long idGar = facture.getLong(facture.getColumnIndexOrThrow("TB_GARAGE._id"));
long idSpGar = valueGar.getLong(valueGar.getColumnIndex("TB_GARAGE._id"));
if (idSpGar == idGar) {
spListeGar.setSelection(iGar);
}
}
It works for the garage, but the problem is that, for a reason that I don't understand, the spinner of vehicles takes the same ID than the garage.
That means, if the garage selected has the ID 2 in the DB, the selected vehicle will be the vehicle with ID 2 too.
??
Here is my query to get the invoice:
public Cursor recupFacture(long idFacture){
return db.rawQuery("SELECT TB_FACTURE._id, libelle_fa, date_fa, nom_vhc, kilometrage_fa, nom_garage, remarque_fa, date_paie_fa, montant_fa, TB_VEHICULE._id, TB_GARAGE._id" +
" FROM TB_FACTURE, TB_VEHICULE, TB_GARAGE" +
" WHERE fk_vhc_fa = TB_VEHICULE._id" +
" AND fk_gar_fa = TB_GARAGE._id" +
" AND TB_FACTURE._id ="+idFacture, null);
}
And I realised that I have thi kind of mistakes in my log :
08-10 12:54:22.431: ERROR/Cursor(17072): requesting column name with table name -- TB_VEHICULE._id
And same for garage...
Thanks for your help!
EDIT :
I found a solution.
I replaced the TB_GARAGE._id and TB_VEHICULE._id by the fk at the lines :
long idVhc = facture.getLong(facture.getColumnIndexOrThrow("TB_VEHICULE._id"));
long idGar = facture.getLong(facture.getColumnIndexOrThrow("TB_GARAGE._id"));
However, I can't really explain why it works like this but not with the ID.
The prefix of the table causes a strange mistake...

Are you saving the invoice correctly? Make sure you are not accidentally saving the garage ID as vehicle ID as well.
Otherwise, how is "fracture" defined? Perhaps there is a mistake there.

Related

Android Sqlite Read Column Values with Previous and Next Options

I have a Sqlite table In that I am Selecting one row at a time with Limit 1.. like
cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + SQLiteHelper.TABLE_NAME + " WHERE status in ('new') LIMIT 1", null);
So Now I want to read the values of all columns with previous/next options
I tried with String list but its not working
I am Using this for Voice Based application So If User Says Next/Previous It should Say/Display Next Value..
I have Done with Speech to text and Text to speech but I Struck at Previous Next
If I Filter Previous and Next from that row I can add voice to them
My Column Values like
1,Android,Oreo,4gb,64gb,2.2Ghz,4000mhz,$800,May2019.
I want to get these Column values one by one
I googled a lot but I got previous and next with rows.. but not column values
You could use the following as the basis
........ existing code
int current_column = 0;
show_value();
}
// Called when event requires next
private next_column() {
if (current_column < (cursor.getColumnCount() - 1) {
current_column++;
show_value();
}
}
// Called when event requires prev
private prev_column() {
if (current_column > 0 {
current_column--;
show_value();
}
}
private void show_value() {
String current_value = cursor.getString(current_column);
your_appropriate_view.setText(current_value);
}

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 avoid duplicate call history details in android

hi am getting call log details from content Provider it's working fine but output show duplicated call details also how to avoid duplicates in call logs.
current output like
id name number time
1 abc 1233 2.30 pm
2 bdc 2897 1.pm
3 abc 1233 11.30 am
4 abc 1233 11.00 am
but i don't want this output i need like
id name number time
1 abc (3) 1233 2.30 pm
2 bdc 2897 1.00 pm
how to achieve this see my code and help me
public void readCallLogs() {
Cursor callLog = getActivity().getContentResolver().query(
CallLog.Calls.CONTENT_URI, null, null, null,
android.provider.CallLog.Calls.DATE + " DESC");
int cid = callLog.getColumnIndex(CallLog.Calls._ID);
int cName = callLog.getColumnIndex(CallLog.Calls.CACHED_NAME);
int cNumber = callLog.getColumnIndex(CallLog.Calls.NUMBER);
int cType = callLog.getColumnIndex(CallLog.Calls.TYPE);
int cDate = callLog.getColumnIndex(CallLog.Calls.DATE);
int cDuration = callLog.getColumnIndex(CallLog.Calls.DURATION);
// looping call log cursor object
while (callLog.moveToNext()) {
String mId = callLog.getString(cid);
String mName = callLog.getString(cName);
String mNumber = callLog.getString(cNumber);
long mCallDate = callLog.getLong(cDate);
}
I think this is the matter of display....
hence once you receive the data you need to apply the filter or you need to write your own code to group the data.
NOTE: you need to be careful while choosing the Data structure (Array, Map). this can hit the performance.

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.

Using previous value when calculating in loop

I'm displaying a scoreboard from a SQLite table in my app.
I want to the players so that they have the position in front of there name.
The problem i am having is that if they have equal time i want them to have equal position.
and after this i want the loop to jump over the next position. All this should be calculated and inserted into the SQLite database.
Like this:
position name time
1 George 4.00
2 Bill 5.02
2 Henry 5.02
4 Sabina 6.05
5 Heini 6.32
I'm not shure how to tackle this.
I want the loop to run just before i set my view, because the background data is changing also.
Can I use an cursor to select from my database an run a while loop? and how can i refer to the previous selection?
Thanks
Try something like this:
int position = 1;
int time, previousTime = 0;
String name;
while (cursor.moveToNext()) {
name = cursor.getString(...);
time = cursor.getInt(...);
if (time != previousTime) {
position = cursor.getPosition() + 1;
}
System.out.println(position + " " + name + " " + time);
}

Categories

Resources