I'm developing an Android app in Delphi 10.4. My client communicates with the server through web services.
I use a search-by-name service with the GET method to take a list of names depending on what letter, English or Greek, I type in a TEdit. The line of code looks like this:
mydata := IdHTTP1.GET('http://.../Names/search/'+Edit1.Text);
The request is called every time the user types a letter in the TEdit, and returns the names that start with the first letter(s) of the text that the user typed.
When I use English letters, the search works fine, but when I use Greek letters, it doesn't work properly. Instead, it returns all the list of names 1.
I try the path in a browser using Greek letters, like this: http://.../Names/search/Αντ, and it works, it returns the names starting with Αντ. But in the app, it doesn't work.
Is it possible that the encoding of the TEdit or TIdHTTP component are wrong?
It's like it doesn't read the Greek letters and sends an empty string.
1 Because if the path is: http://.../Names/search/, it returns all the list of names.
My code looks like this:
procedure TForm1.Edit1ChangeTracking(Sender: TObject);
var
mydata : string;
jsv,js : TJSONValue;
originalObj,jso : TJSONObject;
jsa : TJSONArray;
i: Integer;
begin
Memo1.Lines.Clear;
try
IdHTTP1.Request.ContentType := 'application/json';
IdHTTP1.Request.CharSet := 'utf-8';
IdHTTP1.Request.AcceptLanguage := 'gr';
IdHTTP1.Request.ContentEncoding := 'UTF-8';
mydata := IdHTTP1.Get('http://.../Names/search/'+Edit1.Text);
except
on E: Exception do
begin
ShowMessage(E.Message);
end;
end;
try
jsv := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(mydata),0) as TJSONValue;
try
jsa := jsv as TJSONArray;
for i := 0 to jsa.Size-1 do
begin
jso := jsa.Get(I) as TJSONObject;
js := jso.Get('Name').JsonValue;
Memo1.Lines.Add(js.Value);
if i=4 then // show the 5 first names of the search
break;
end;
finally
jsv.Free();
end;
except
on E: exception do
begin
ShowMessage(E.Message);
end;
end;
end;
URLs can't contain unencoded non-ASCII characters. You can't just append the TEdit text as-is, you need to url-encode any non-ASCII characters, as well as characters reserved by the URI specs.
If you use your browser's built-in debugger, you will see that it is actually doing this encoding when transmitting the request to the server. For example, a URL like: http://.../Names/search/Αντ sends a request like this:
GET /Names/search/%CE%91%CE%BD%CF%84 HTTP/1.1
Host: ...
...
Notice Αντ => %CE%91%CE%BD%CF%84
In your code, you can use Indy's TIdURI class for this purpose, eg:
uses
..., IdURI;
mydata := IdHTTP1.GET('http://.../Names/search/'+TIdURI.PathEncode(Edit1.Text));
On a side note:
Since you are sending a GET request, you do not need to set the Request.ContentType, Request.CharSet, or Request.ContentEncoding properties (besides, 'UTF-8' is not valid for ContentEncoding anyway).
Also, ParseJSONValue() has an overload that takes a string, so you don't need to use TEncoding.UTF8.GetBytes().
Related
AS. since closing related questions - more examples added below.
The below simple code (which finds a top-level Ie window and enumerates its children) works Ok with a '32-bit Windows' target platform. There's no problem with earlier versions of Delphi as well:
procedure TForm1.Button1Click(Sender: TObject);
function EnumChildren(hwnd: HWND; lParam: LPARAM): BOOL; stdcall;
const
Server = 'Internet Explorer_Server';
var
ClassName: array[0..24] of Char;
begin
Assert(IsWindow(hwnd)); // <- Assertion fails with 64-bit
GetClassName(hwnd, ClassName, Length(ClassName));
Result := ClassName <> Server;
if not Result then
PUINT_PTR(lParam)^ := hwnd;
end;
var
Wnd, WndChild: HWND;
begin
Wnd := FindWindow('IEFrame', nil); // top level IE
if Wnd <> 0 then begin
WndChild := 0;
EnumChildWindows(Wnd, #EnumChildren, UINT_PTR(#WndChild));
if WndChild <> 0 then
..
end;
I've inserted an Assert to indicate where it fails with a '64-bit Windows' target platform. There's no problem with the code if I un-nest the callback.
I'm not sure if the erroneous values passed with the parameters are just garbage or are due to some mis-placed memory addresses (calling convention?). Is nesting callbacks infact something that I should never do in the first place? Or is this just a defect that I have to live with?
edit:
In response to David's answer, the same code having EnumChildWindows declared with a typed callback. Works fine with 32-bit:
(edit: The below does not really test what David says since I still used the '#' operator. It works fine with the operator, but if I remove it, it indeed does not compile unless I un-nest the callback)
type
TFNEnumChild = function(hwnd: HWND; lParam: LPARAM): Bool; stdcall;
function TypedEnumChildWindows(hWndParent: HWND; lpEnumFunc: TFNEnumChild;
lParam: LPARAM): BOOL; stdcall; external user32 name 'EnumChildWindows';
procedure TForm1.Button1Click(Sender: TObject);
function EnumChildren(hwnd: HWND; lParam: LPARAM): BOOL; stdcall;
const
Server = 'Internet Explorer_Server';
var
ClassName: array[0..24] of Char;
begin
Assert(IsWindow(hwnd)); // <- Assertion fails with 64-bit
GetClassName(hwnd, ClassName, Length(ClassName));
Result := ClassName <> Server;
if not Result then
PUINT_PTR(lParam)^ := hwnd;
end;
var
Wnd, WndChild: HWND;
begin
Wnd := FindWindow('IEFrame', nil); // top level IE
if Wnd <> 0 then begin
WndChild := 0;
TypedEnumChildWindows(Wnd, #EnumChildren, UINT_PTR(#WndChild));
if WndChild <> 0 then
..
end;
Actually this limitation is not specific to a Windows API callbacks, but the same problem happens when taking address of that function into a variable of procedural type and passing it, for example, as a custom comparator to TList.Sort.
http://docwiki.embarcadero.com/RADStudio/Rio/en/Procedural_Types
procedure TForm2.btn1Click(Sender: TObject);
var s : TStringList;
function compare(s : TStringList; i1, i2 : integer) : integer;
begin
result := CompareText(s[i1], s[i2]);
end;
begin
s := TStringList.Create;
try
s.add('s1');
s.add('s2');
s.add('s3');
s.CustomSort(#compare);
finally
s.free;
end;
end;
It works as expected when compiled as 32-bit, but fails with Access Violation when compiled for Win64. For 64-bit version in function compare, s = nil and i2 = some random value;
It also works as expected even for Win64 target, if one extracts compare function outside of btn1Click function.
This trick was never officially supported by the language and you have been getting away with it to date due to the implementation specifics of the 32 bit compiler. The documentation is clear:
Nested procedures and functions (routines declared within other routines) cannot be used as procedural values.
If I recall correctly, an extra, hidden, parameter is passed to nested functions with the pointer to the enclosing stack frame. This is omitted in 32 bit code if no reference is made to the enclosing environment. In 64 bit code the extra parameter is always passed.
Of course a big part of the problem is that the Windows unit uses untyped procedure types for its callback parameters. If typed procedures were used the compiler could reject your code. In fact I view this as justification for the belief that the trick you used was never legal. With typed callbacks a nested procedure can never be used, even in the 32 bit compiler.
Anyway, the bottom line is that you cannot pass a nested function as parameter to another function in the 64 bit compiler.
I was able to find two Bcrypt libraries that can be compiled for windows but I am struggling to compile them for Android in Delphi XE8.
The first one is https://github.com/chinshou/bcrypt-for-delphi which doesn't require any modifications to be compiled for Windows.
For the second one https://github.com/PonyPC/BCrypt-for-delphi-lazarus-fpc I had to make some minor adjustments in the checkPassword function to get the same result since it was FreePascal specific:
function checkPassword(const Str: string; const Hash: ansistring): boolean;
var
RegexObj: TRegEx;
match : TMatch;
Salt : String;
begin
RegexObj := TRegEx.Create('^\$2a\$10\$([\./0-9A-Za-z]{22})',[roIgnoreCase]);
match := RegexObj.Match(Hash);
if match.Success then
begin
Salt := Copy(match.Value,8,22);
Result := HashPassword(Str, Salt) = Hash;
end
else
begin
Result := False;
end;
end;
After changing the platform from Win to Android the first one shows a lot of errors since it depends on ComObj, Windows and ActiveX. The second one after replacing RegExpr with RegularExpressions and Types shows only conflicts that results from changes in the String variable. The code uses AnsiString, AnsiChar which I cannot just replace with String and Char since it affects the hashing function.
What am I missing? what other modifications should I do to replace the obsolete AnsiString and AnsiChar declarations, allowing the code to be compiled for Android?
The String declaration problem with the second library was caused by the move command in the HashPassword function
Move(password[1], key[0], Length(password));
since the size of the password variable changed after replacing the declaration from AnsiString to String. Replacing this with a simple for loop and Ord function fixes the problem although there is probably a more elegant way of doing it.
function HashPassword(const Str: string; const salt: string): string;
var
password: String ;
key, saltBytes, Hash: TBytes;
i: Integer;
begin
password := AnsiToUtf8(str);
SetLength(key, Length(password) + 1);
for i := 0 to length(password)-1 do
key[i]:=ord(password[i+1]);
key[high(key)] := 0;
saltBytes := BsdBase64Decode(salt);
Hash := CryptRaw(key, saltBytes);
Result := FormatPasswordHashForBsd(saltBytes, Hash);
end;
To summarize, the conversion of the second library to an Android compatible code requires the following changes:
modifying the regular expression code in the checkPassword function
according to the code posted in the question
altering the uses section by replacing "RegExpr" with "RegularExpressions, Types"
replacing all declarations from AnsiString to String and AnsiChar to Char
modifying the HashPassword function as shown above
I want to list all available raw sensor data in a Memo for Android.
Following code worked over the past years, but it doesn't work with XE8. There is probably an internal compiler bug. Is there anything I can do to make it work again, or is there an alternative solution?
uses
TypInfo;
type
TOrientationSensorAccessor = class(TCustomOrientationSensor);
TLocationSensorAccessor = class(TCustomLocationSensor);
procedure TForm2.Button1Click(Sender: TObject);
var
p_location: TCustomLocationSensor.TProperty;
p_orientation: TCustomOrientationSensor.TProperty;
n, v: string;
begin
Memo1.Lines.Clear;
if Assigned(OrientationSensor1.Sensor) then
begin
if not OrientationSensor1.Sensor.Started then OrientationSensor1.Sensor.Start;
// Error (only in XE8): Incompatible types 'TCustomLocationSensor.TProperty' and 'TCustomOrientationSensor.TProperty'
// In XE7 it works.
for p_orientation in OrientationSensor1.Sensor.AvailableProperties do
begin
n := 'OrientationSensor.'+GetEnumName(TypeInfo(TCustomOrientationSensor.TProperty), integer(p_orientation)) ;
v := FloatToStr(TOrientationSensorAccessor(OrientationSensor1.Sensor).GetDoubleProperty(p_orientation));
Memo1.Lines.Values[n] := v;
end;
end;
if Assigned(LocationSensor1.Sensor) then
begin
if not LocationSensor1.Sensor.Started then LocationSensor1.Sensor.Start;
for p_location in LocationSensor1.Sensor.AvailableProperties do
begin
n := 'LocationSensor.'+GetEnumName(TypeInfo(TCustomLocationSensor.TProperty), integer(p_location)) ;
v := FloatToStr(TLocationSensorAccessor(LocationSensor1.Sensor).GetDoubleProperty(p_location));
Memo1.Lines.Values[n] := v;
end;
end;
end;
Update
Some experiments:
(1) When I comment out the first "for", it will compile:
// for p_orientation in OrientationSensor1.Sensor.AvailableProperties do
// begin
n := 'OrientationSensor.'+GetEnumName(TypeInfo(TCustomOrientationSensor.TProperty), integer(p_orientation)) ;
v := FloatToStr(TOrientationSensorAccessor(OrientationSensor1.Sensor).GetDoubleProperty(p_orientation));
Memo1.Lines.Values[n] := v;
// end;
end;
(2) When I comment out the assigning of "n" and "v", it will compile too:
for p_orientation in OrientationSensor1.Sensor.AvailableProperties do
begin
// n := 'OrientationSensor.'+GetEnumName(TypeInfo(TCustomOrientationSensor.TProperty), integer(p_orientation)) ;
// v := FloatToStr(TOrientationSensorAccessor(OrientationSensor1.Sensor).GetDoubleProperty(p_orientation));
// Memo1.Lines.Values[n] := v;
end;
end;
Since neither "for", nor "n" and "v" is the bad region, where is the error then?
(3) When I comment out the second for-loop, it will compile again. If I comment out the first for-loop, it will compile too. Each for-loop works, but in combination they will not work.
It looks like the error is only happening if 5 factors are combined:
TypInfo
Accessors
for loop
Usage of TypInfo (GetEnumName)
Both for-loops are used.
Update 2
Here is the smallest reproducible code I could find. If any line is commented out, it compiles:
program ProjectCompilerBug;
{$APPTYPE CONSOLE}
uses
System.Sensors, System.Sensors.Components;
var
p_location: TCustomLocationSensor.TProperty;
p_orientation: TCustomOrientationSensor.TProperty;
begin
// Compilation Error (only in XE8):
// "Incompatible types 'TCustomLocationSensor.TProperty' and 'TCustomOrientationSensor.TProperty'"
// In XE7 it compiles
for p_orientation in TOrientationSensor.Create(nil).Sensor.AvailableProperties do
begin
FloatToStr(1.23);
end;
for p_location in TLocationSensor.Create(nil).Sensor.AvailableProperties do
begin
end;
end.
Yes, this looks like an XE8 compiler bug. I think you've done a fine job isolating it, for which I commend you. You'll need to submit bug report to Quality Portal.
To workaround the fault I think you will be able to put the loops in separate functions. My hypothesis is that the key is the presence of two for in loops with differently typed loop variables that is the key. Avoid that and you should be able to avoid the problem.
The following code works on Win32, anyway it is trowing exception if run on Android or iOS. The exception is : "No mapping for the Unicode character exists in the target multi-byte code page"
function GetURLAsString(aURL: string): string;
var
lHTTP: TIdHTTP;
lStream: TStringstream;
begin
lHTTP := TIdHTTP.Create(nil);
lStream := TStringstream.Create(result);//create('',EEncoding.utf8),not work
try
lHTTP.Get(aURL, lStream);
lStream.Position := 0;
result := lStream.readstring(lStream.Size);//error here
finally
FreeAndNil(lHTTP);
FreeAndNil(lStream);
end;
end;
TStringStream is not a suitable class for this situation. It requires you to specify an encoding in its constructor. If you do not, it uses the OS default encoding instead. On Windows, that default is locale-specific to the user account that is running your app. On mobile, that default is UTF-8 instead.
HTTP can transmit text using any number of charsets. If the data does not match the encoding used by the TStringStream, you are going to run into decoding problems.
TIdHTTP knows the charset of the received data and can decode it into a Delphi string for you, eg:
function GetURLAsString(aURL: string): string;
var
lHTTP: TIdHTTP;
begin
lHTTP := TIdHTTP.Create(nil);
try
Result := lHTTP.Get(aURL);
finally
FreeAndNil(lHTTP);
end;
end;
How can I get a phone's contact list in a FireMonkey mobile application?
here you go .. It's not finished as it reads all numbers for one person and if there are two numbers you will have two times this person listed inside list .. but from here I think you can work and adjust it to your needs :))
function GetContact: TStringList;
var
cursorContacts, cursorContactsPhone: JCursor;
hasPhoneNumber: Integer;
id: Int64;
displayName, phoneNumber, contactID: string;
begin
Result := TStringList.Create;
cursorContacts := SharedActivity.getContentResolver.query(TJContactsContract_Contacts.JavaClass.CONTENT_URI, nil, nil, nil, nil);
if (cursorContacts.getCount > 0) then
begin
while (cursorContacts.moveToNext) do
begin
id := cursorContacts.getLong(cursorContacts.getColumnIndex(StringToJString('_ID')));
displayName := JStringToString(cursorContacts.getString(cursorContacts.getColumnIndex(StringToJString('DISPLAY_NAME'))));
hasPhoneNumber := cursorContacts.getInt(cursorContacts.getColumnIndex(StringToJString('HAS_PHONE_NUMBER')));
if (hasPhoneNumber > 0) then
begin
cursorContactsPhone := SharedActivity.getContentResolver.query(TJCommonDataKinds_Phone.JavaClass.CONTENT_URI, nil,StringToJString('CONTACT_ID = ' + IntToStr(id)),nil, nil);
while (cursorContactsPhone.moveToNext) do
begin
phoneNumber := JStringToString(cursorContactsPhone.getString(cursorContactsPhone.getColumnIndex(StringToJString('DATA1'))));
contactID := JStringToString(cursorContactsPhone.getString(cursorContactsPhone.getColumnIndex(StringToJString('CONTACT_ID'))));
Result.Add(displayName + ': ' + phoneNumber);
end;
cursorContactsPhone.close;
end;
end;
end;
cursorContacts.close;
end;
Best Regards,
Kruno
Here's my code (inspired and originally created by #mali kruno, I only changed it to my needs!) to search through all contacts based on TEdit OnChange event:
I use this function in my commonfunctions.pas unit:
function GetContact (Name: string; Number: string; const tip: integer) : TStringList;
var
cursorContactsPhone: JCursor;
Typo1, Typo2: string;
FindBy: JString;
ToFind: TJavaObjectArray<JString>;
CurRec: integer;
begin
Result:=TStringList.Create;
CurRec:=0;
ToFind:= TJavaObjectArray<JString>.Create(2);
if Name <> '' then
begin
ToFind.Items[0] := StringToJString('data1');
ToFind.Items[1] := StringToJString('display_name');
FindBy := StringToJString('display_name LIKE "%' + Name + '%"');
Typo1:='data1';
Typo2:='display_name';
end
else if Number <> '' then
begin
ToFind.Items[0] := StringToJString('display_name');
ToFind.Items[1] := StringToJString('data1');
FindBy := StringToJString('data1 LIKE "%' + Number + '%"');
Typo1:='display_name';
Typo2:='data1';
end;
cursorContactsPhone := SharedActivity.getContentResolver.query(TJCommonDataKinds_Phone.JavaClass.CONTENT_URI, ToFind, FindBy, nil, nil);
while (cursorContactsPhone.moveToNext) do
begin
Result.Add
(JStringToString(cursorContactsPhone.getString(cursorContactsPhone.getColumnIndex(StringToJString(Typo2)))) + ' - ' +
JStringToString(cursorContactsPhone.getString(cursorContactsPhone.getColumnIndex(StringToJString(Typo1)))));
CurRec:=CurRec+1;
end;
cursorContactsPhone.close;
end;
I call it from ContactSearch.Change event (it's TEdit component) like this:
procedure TMainF.ContactsSearch.Change(Sender: TObject);
var ResultNo: integer; SearchContacts: string; Results: TStringList;
begin // begin main procedure
if ContactsSearch.Text.Length > 1 then
begin //begin search and memo update
SearchContacts:=ContactsSearch.Text;
Results:=GetContact(SearchContacts, '', 0);
ResultNo:=0;
Memo1.Lines.Clear;
for ResultNo := 0 to Results.Count-1
do
begin
Memo1.Lines.Add(Results.Strings[ResultNo]);
end;
Results.Free;
end;
end;
Note, that the Result is a TStringList created in a function and freed in a procedure after Memo update.
Note also, that I only search if TEdit length is 2 or more, since otherwise entering just "a" in a tedit would show all contacts that have a letter "a" in their name, and therefore it would freeze a little every time you search, use backspace etc...
The workaround would be to load the phonebook in a TStringList on application start, and then search through the stringlist only, but that would make few other troubles:
a) phonebook update wouldn't be detected, or you'd have to implement "Update" button, which would make no sense to do the workaround at all..
b) app start would take longer
c) haven't tried that and not sure how much would it actually speed-up the search, since the Memo.Lines.Add takes more time than the query itself, so...
As for the duplicates, you can see that here are not handled, because currently I don't have a need to do so, but you can easily handle this using "sort" in a Memo, or, even better if you don't want to lose the entries that would otherwise appear as a duplicate, manage them inside a TStringList itself, so that you merge numbers in the same line, or create sub-stringlists for each name (of course, only if a name appears more than once, if you don't want to end up having twice as much stringlists as you'd actually need).
Hope this helps.
You do it in much the same way as a programmer would who uses the native programming APIs, given that Delphi does not provide a unified/wrapped solution to this problem.
You need to research how the Android SDK surfaces the contact list and how the iOS SDK surfaces its contact list, then make use of the native APIs to access it.
It will differ wildly between the 2 platforms, but it would be feaible to write some OS-independent interface to it once you've established the implementation on the 2 different OSs and seen what is on offer and what is accessible across the two implementations. This is what FMX does in other instances of similar features implemented on the two platforms.
If the required APIs haven't already been imported into Delphi's RTL, which is quite possible, then you'd also need to write the imports for those APIs you need in order to be able to call them in the first place.
Executive summary:
Roll up your sleeves
Get stuck in
Code it up yourself
Bask in the pleasure of having got some cool API stuff working