Android Sqlite Read Column Values with Previous and Next Options - android

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);
}

Related

How do I modify the effect of a button with another button in android studio?

I am trying to create an app that adds, at first the value 1 to the textView.
Then I tried creating another button that doubles the value shown in the textview.
Everytime I press the first button, it should increment by 1
and everytime I press the other button it should double that result.
But when I add 1 to the value again, the value goes back to the undoubled stage and increments by one.
I need to cover the operations by making a button that adds value X
and the other button that multiplies that value of the button by 2.
This is the main.kt I made so far
value.setText("" + id)
plusBtn.setOnClickListener {
value.setText("" + ++id)
}
doubleBtn.setOnClickListener {
value.setText("" + 2*id)
}
I think this could solve the problem. You haven't saved the value in the variable. when you set the text to 2*id, the id variable is still the same.
value.setText("" + id)
plusBtn.setOnClickListener {
value.setText("" + ++id)
}
doubleBtn.setOnClickListener {
value.setText("" + 2*id)
id=2*id;
}
You have to get updated value from textView when you click on any button.
Check following statements, I had written in Java but you may able to convert in kotlin.
plusBtn.setOnClickListener {
id = Integer.parseInt(value.getText().toString());
value.setText("" + ++id)
}
doubleBtn.setOnClickListener {
id = Integer.parseInt(value.getText().toString());
value.setText("" + 2*id)
}
This is because you are just setting the double value of id as text to the value, not assigning the double value to the id.
to do this you can either assign the
value.setText("" + 2*id)
id = Integer.parseInt(value.getText().toString());
or
id = 2*id
value.setText(id)
I'm only answering because the other answers so far are convoluted (converting back and forth from Strings) or use needless repetition (calculating the doubled value twice).
When you use ++id, you are using the increment operator, which adds one to the value in id, but also changes id to the new value. It is a shorthand way of writing what would normally take two lines of code. What you're doing is equivalent to
plusBtn.setOnClickListener {
id = id + 1
value.setText("" + id)
}
When you use 2*id, you are calculating a new value, but you are not assigning this new value to id. There isn't a shorthand operator for doing both actions like there is for adding or subtracting one.
The simplest solution is to assign the new value before changing the text. So your second button listener becomes:
doubleBtn.setOnClickListener {
id = id * 2
value.setText("" + id)
}
or, more succinctly:
doubleBtn.setOnClickListener {
id *= 2
value.setText("" + id)
}

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

Checking data enter by user with parameter set, sqlite android

i'm doing a checking from data enter by user with data that already set.
As example, data save in sqlite is 60-80. If user input is 88. i want to check the user input which is 88 with data 60-80, so that i can come out with appropriate advice
Help me.
i did like this
public String getRangeFromUserInput(int b1, int b2, int b3, int a1, int a2, int a3) {
if
(((70<b1<<100)||(70<b2<<100)||(70<b3<<100))&&((70<a1<<135)||(70<a2<<135)||(70<a3<<135)))
Toast.makeText(GlucoseAdd.this, "Your glucose level is at normal range", Toast.LENGTH_LONG).show();
else if
(((50<b1<<60)||(50<b2<<60)||(50<b3<<60))&&((135<a1<<180)||(135<a2<<180)||(135<a3<<180)))
Toast.makeText(GlucoseAdd.this, "You need to start diet. The diet should " +
"also be low in fat and high in dietary fibre. Regular exercise " +
"is important in maintaining balanced blood glucose levels.", Toast.LENGTH_LONG).show();
else if
(((b1<50)||(b2<50)||(b3<50))&&((180<a1<<200)||(180<a2<<200)||(180<a3<<200)))
Toast.makeText(GlucoseAdd.this, "You are in danger state.", Toast.LENGTH_LONG).show();
return null;
}
but when i enter data all prompt out the first one.. Why?
Since the data stored in your DB table is in the format of string i.e. 60-80
So you'll need to convert the user input value (for ex. 88) into i.e. 80-100 using the following code:
public String getRangeFromUserInput(String userInput) {
return getRangeFromUserInput(Integer.parseInt(userInput));
}
public String getRangeFromUserInput(int userInput) {
if (userInput >= 60 && userInput < 80)
return "60-80";
else if (userInput >= 80 && userInput < 100)
return "80-100";
// ...more range checks
return null;
}
Now, use the output of the method getRangeFromUserInput() which is a string (for ex. 80-100) in the where clause of your query as follows:
String where = "range = '" + getRangeFromUserInput("88") + "'";
Assuming the column name is range in your table. If the query returns a row then you can read the advice corresponding to the range using
cursor.getString(cursor.getColumnIndex("advice"))
Assuming the column name is advice in your table.

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);
}

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

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.

Categories

Resources