Check Value from mysql using android - 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.

Related

Given an array of Long values in Kotlin and a position parameter, when the position is in the middle of two of the array values, return the lowest

Spotify's lyrics API provides an Array of miliseconds to mark when the lyric line has changed. Having a Media Player that updates it's position every 50ms, how should i code in Kotlin the way to find the correct lyric line? The position param can be in the middle of two values of the array, so I want to get the lowest one of that two.
I tried to get the lowest value compared to the position parameter but lol, it will always be the first value of the Array... Silly fault of mine.
The problem is that I have a third one that indicates the range of that two value. For example: I have an Array of [45, 78, 125, 198]. If I pass the position param where it's value is 95, I want to return the 78 (that is the lowest value from itself, the position param and 125).
/** Input data for example (from your comment). */
val yourArray = arrayOf(45, 78, 125, 198)
val inputValue = 95
/** How to get needed index. */
val resultIndex = yourArray.indexOfLast { it < inputValue }.takeIf { it != -1 }
If you get resultIndex == null - it means you don't have value inside your array which lower then your inputValue.
I think it's simpler than find indexOfFirst and compare result later. And absolutely better and safer when sort() solution.
Insert the position param into the array, sort it, find its index and use it to get the closest value.
val array: MutableList<Long> = mutableListOf(4L, 9L, 5L, 1L)
val position = 7L
array.add(position)
println(array[array.sorted().indexOf(position) - 1])
Output: 5
If I correctly understand, you need simply use min function for compare two numbers in Kotlin and find the low one: link
Here’s a way to do it without having to make two copies of the list and doing a sort.
val foundIndex = lyricTimesList.indexOfFirst { it > inputTime }
val result = if (foundIndex == -1) lyricTimesList.size - 1 else foundIndex - 1
Note the result could be -1 if the input time is less than the first number in the list.

Create list/array of Textviews to change .text via index

So I was hoping to make a list/array of textviews so that I can iterate a loop and set the .text value of the TextViews as I go. Otherwise I would have to set the values in the code statically which would be a whole lot messier and potentially not even feasible for my needs.
So in the code below the idea would be to iterate the loop and when the correct value is confirmed that [index] would then set the corresponding
var refillToken : Double = (0).toDouble()
var tweetStored : BooleanArray = BooleanArray(20)
var tweetActive : BooleanArray = BooleanArray(20)
var userID: MutableList<String> = mutableListOf("")
var textViewToken = 0
while (refillToken > 0) {
var token: Int = 0
while (token < (tweetStored.size)) {
if (tweetStored[token] == true) {
tweetActive[token] = true
textView[textViewToken].text = userID[token]
textViewToken++
refillToken--
token++
if (refillToken < 0) {
break
}
}
}
}
}
I know my loop is probably messy by sane people standards but it makes sense to me and (hopefully) isn't the issue at play. Have found a few articles or ideas searching for the past two hours but they're either 10 years old (and I think deprecated), for java or don't work for whatever reason.
You need to get a value and then add it to the textview and change this value after every action on the page.
Use variable assignment for this task

Starts comparing from the first number, not the whole number in kotlin

Hello I need to compare 2 numbers and I used >, => but it doesn't compare whole number, it looks for the leftest(left) number and compare
for example the number is 92,236 and i want to compare it with 100,000, it says 92236 is bigger than 100,000 and it is because of the first number which is 9 and the first number of second number that is 1 so it says 100,000 is not bigger than 9236
here what I had done
class IncreaseMoneyFragment : Fragment() {
var decide = ""
val increaseEditText = mIncreaseMoneyBinding.increaseEdt.text.toString() (get value of edit text)
val currentPayment = it.payment (get loanPayment from database)
if (increaseEditText > currentPayment) {
Toast.makeText(activity, "more", Toast.LENGTH_SHORT).show()
val more = "بیشتر"
decide = more
} else {
Toast.makeText(activity, "less", Toast.LENGTH_SHORT).show()
val less = "کمتر"
decide = less
}
builder.setTitle(" مبلغ مورد نظر از مبلغ قسط وام $decide است. ادامه میدهید؟")
THANKS FOR HELPING ME :)
You are most likely comparing strings (text) and not numbers here. That's why it's using the alphabetical order instead of the integer order:
println("92236" > "100000") // true
println(92236 > 100000) // false
You probably want to convert your strings into integers instead:
if (increaseEditText.toInt() > currentPayment.toInt()) {
// ...
}
Note that toInt will crash if the strings are not actual numbers (for instance empty).
You can use toIntOrNull if you want more safety. It returns null if the string is not a number, so you can simply check for null and deal with this problem separately before comparing.

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

Identifying Unknown/Private/Restricted calls in my Android app

I use a simple projection in my contentObserver to detect missed calls.
String[] projection = new String[] {Calls.NUMBER, Calls.DATE};
and later ...
String number = cursor.getString(0);
I would like to be able to identify calls with no caller ID. A quick experiment showed that the number returned was "-2" for a "Restricted" call (from a real phone, using #31#). On the emulator using "#" as phone number, shows up as a call from "-1", reported as "Unknown".
I cannot find any documentation to confirm this. Is simply looking for a negative number or a "-" prefix a reliable way of identifying such calls?
You can use another colum: Calls.NUMBER_PRESENTATION that have the following possible values:
PRESENTATION_ALLOWED
Number is allowed to display for caller id. Constant Value: 1 (0x00000001)
PRESENTATION_RESTRICTED
Number is blocked by user. Constant Value: 2 (0x00000002)
PRESENTATION_UNKNOWN
Number is not specified or unknown by network. Constant Value: 3 (0x00000003)
PRESENTATION_PAYPHONE
Number is a pay phone. Constant Value: 4 (0x00000004)
A call from a restricted ou unknown number the field value will be 2 or 3. So you can do something like that:
String[] projection = new String[] {
Calls.NUMBER,
Calls.DATE,
Calls.NUMBER_PRESENTATION
};
and later ...
String number = cursor.getString(0);
String type = cursor.getString(2);
if(type == "2" || type == "3") {
number = "RESTICTED OR UNKNOWN";
}

Categories

Resources