Android实例-读取设备联系人(XE8+小米2)

 

相关资料:

http://www.colabug.com/thread-1071065-1-1.html

 

结果:

1.将权限打开Read contacts设置为True,不然报图一的错误。

2.搜索空没有问题,但搜索名字时报错了,占时没跟踪,哪位大神了解的M我,多谢了。

 

实例代码:

 1 unit Unit1;
 2 
 3 interface
 4 
 5 uses
 6   System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
 7   FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ScrollBox,
 8   FMX.Memo, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit, FMX.Layouts;
 9 
10 type
11   TForm1 = class(TForm)
12     Button1: TButton;
13     Label1: TLabel;
14     Memo1: TMemo;
15     Layout1: TLayout;
16     Label2: TLabel;
17     Edit1: TEdit;
18     procedure Button1Click(Sender: TObject);
19   private
20     { Private declarations }
21   public
22     { Public declarations }
23   end;
24 
25 var
26   Form1: TForm1;
27 
28 implementation
29 uses
30  FMX.Helpers.Android, //需要引入
31  Androidapi.JNI.JavaTypes,//需要引入
32  Androidapi.JNI.GraphicsContentViewText,//需要引入
33  FMX.Platform.Android,//需要引入
34  Androidapi.JNIBridge,//需要引入
35  Androidapi.JNI.Provider,//需要引入
36  Androidapi.Helpers;//需要引入
37 
38 {$R *.fmx}
39 {$R *.NmXhdpiPh.fmx ANDROID}
40 //定义一个查询方法
41 procedure QueryContact(AName: string; AList: TStrings);
42 var
43   cursorContactsPhone: JCursor;
44   selection: string;
45   oprojection: TJavaObjectArray<JString>;
46   oselectionArgs: TJavaObjectArray<JString>;
47   FieldIndex: Integer;
48 begin
49   if AList <> nil then
50   AList.Clear;
51   oprojection := nil;
52   oselectionArgs := nil;
53   if AName.Length > 0 then
54   begin
55     oprojection := TJavaObjectArray<JString>.Create(1);
56     oselectionArgs := TJavaObjectArray<JString>.Create(1);
57     oprojection.Items[0] := TJContacts_PeopleColumns.JavaClass.DISPLAY_NAME;
58     selection := JStringToString(TJContacts_PeopleColumns.JavaClass.DISPLAY_NAME)+' LIKE “%' + AName + '%”';
59   end;
60   //select projection from 联系人数据库 where selection
61   cursorContactsPhone := SharedActivity.getContentResolver.query
62   (TJCommonDataKinds_Phone.JavaClass.CONTENT_URI,
63   oprojection, {要查询的字段名,nil的全部}
64   StringToJString(selection),{Where条件}
65   oselectionArgs, { 这里是Where语句的条件参数们,我上面图方便,写死在Where条件中了,没使用参数 }
66   StringToJString(''));
67 
68   if AList <> nil then
69   while (cursorContactsPhone.moveToNext) do
70   begin
71     //获取字段的ColumnIndex
72     FieldIndex := cursorContactsPhone.getColumnIndex
73     (TJContacts_PeopleColumns.JavaClass.DISPLAY_NAME);
74     //读字段内容
75     AList.Add(JStringToString(cursorContactsPhone.getString(FieldIndex)));
76   end;
77   cursorContactsPhone.close;
78 end;
79 
80 //调用查询方法
81 procedure TForm1.Button1Click(Sender: TObject);
82 var
83   s: TStrings;
84 begin
85   s := TStringList.Create;
86   QueryContact(Edit1.Text, s); //查询姓王的人
87   Memo1.Text := s.Text;
88   s.Free;
89 end;
90 
91 end.

 

posted on 2015-09-17 15:04  疯狂delphi  阅读(1325)  评论(0编辑  收藏  举报

导航