public class AutocompleteMain extends Activity implements OnItemClickListener, OnItemSelectedListener {
// Initialize variables
AutoCompleteTextView textView=null;
private ArrayAdapter<String> adapter;
// Store contacts values in these arraylist
public static ArrayList<String> phoneValueArr = new ArrayList<String>();
public static ArrayList<String> nameValueArr = new ArrayList<String>();
EditText toNumber=null;
String toNumberValue="";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.autocomplete_main);
final Button Send = (Button) findViewById(R.id.Send);
// Initialize AutoCompleteTextView values
textView = (AutoCompleteTextView) findViewById(R.id.toNumber);
//Create adapter
adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_dropdown_item_1line, new ArrayList<String>());
textView.setThreshold(1);
//Set adapter to AutoCompleteTextView
textView.setAdapter(adapter);
textView.setOnItemSelectedListener(this);
textView.setOnItemClickListener(this);
// Read contact data and add data to ArrayAdapter
// ArrayAdapter used by AutoCompleteTextView
readContactData();
/********** Button Click pass textView object ***********/
Send.setOnClickListener(BtnAction(textView));
}
private OnClickListener BtnAction(final AutoCompleteTextView toNumber) {
return new OnClickListener() {
public void onClick(View v) {
String NameSel = "";
NameSel = toNumber.getText().toString();
final String ToNumber = toNumberValue;
if (ToNumber.length() == 0 ) {
Toast.makeText(getBaseContext(), "Please fill phone number",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), NameSel+" : "+toNumberValue,
Toast.LENGTH_LONG).show();
}
}
};
}
// Read phone contact name and phone numbers
private void readContactData() {
try {
/*********** Reading Contacts Name And Number **********/
String phoneNumber = "";
ContentResolver cr = getBaseContext()
.getContentResolver();
//Query to get contact name
Cursor cur = cr
.query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
null);
// If data data found in contacts
if (cur.getCount() > 0) {
Log.i("AutocompleteContacts", "Reading contacts........");
int k=0;
String name = "";
while (cur.moveToNext())
{
String id = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//Check contact have phone number
if (Integer
.parseInt(cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
//Create query to get phone number by contact id
Cursor pCur = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?",
new String[] { id },
null);
int j=0;
while (pCur
.moveToNext())
{
// Sometimes get multiple data
if(j==0)
{
// Get Phone number
phoneNumber =""+pCur.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Add contacts names to adapter
adapter.add(name);
// Add ArrayList names to adapter
phoneValueArr.add(phoneNumber.toString());
nameValueArr.add(name.toString());
j++;
k++;
}
} // End while loop
pCur.close();
} // End if
} // End while loop
} // End Cursor value check
cur.close();
} catch (Exception e) {
Log.i("AutocompleteContacts","Exception : "+ e);
}
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
//Log.d("AutocompleteContacts", "onItemSelected() position " + position);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
InputMethodManager imm = (InputMethodManager) getSystemService(
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
// Get Array index value for selected name
int i = nameValueArr.indexOf(""+arg0.getItemAtPosition(arg2));
// If name exist in name ArrayList
if (i >= 0) {
// Get Phone Number
toNumberValue = phoneValueArr.get(i);
InputMethodManager imm = (InputMethodManager) getSystemService(
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
// Show Alert
Toast.makeText(getBaseContext(),
"Position:"+arg2+" Name:"+arg0.getItemAtPosition(arg2)+" Number:"+toNumberValue,
Toast.LENGTH_LONG).show();
Log.d("AutocompleteContacts",
"Position:"+arg2+" Name:"+arg0.getItemAtPosition(arg2)+" Number:"+toNumberValue);
}
}
protected void onResume() {
super.onResume();
}
protected void onDestroy() {
super.onDestroy();
}
}
其实我的目标是获取联系人姓名和电话号码,但我的代码显示输出如此请填写电话号码这令我很烦,所以如果有人知道,请告诉我。提前致谢
答案 0 :(得分:0)
在列表视图中显示名称和号码的活动...
public class FirstActivity extends Activity {
ListView list;
ArrayList<HashMap<String, String>> al = new ArrayList<HashMap<String,String>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
list = (ListView) findViewById(R.id.list);
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while(phones.moveToNext())
{
HashMap<String, String> nameNumberMap = new HashMap<String, String>();
String contactName = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String contactNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
nameNumberMap.put("Name",contactName);
nameNumberMap.put("Number",contactNumber);
al.add(nameNumberMap);
}
Log.e("check","as2");
customAdapter adapter = new customAdapter(this, al);
list.setAdapter(adapter);
Log.e("check","as2"+al.size());
}
}
自定义适配器类
public class customAdapter extends BaseAdapter {
ArrayList<HashMap<String, String>> al = new ArrayList<HashMap<String,String>>();
Activity activity;
private static LayoutInflater inflater = null;
public customAdapter(Activity a, ArrayList<HashMap<String, String>> al) {
Log.e("check", "");
activity = a;
this.al = al;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return al.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
{
vi = inflater.inflate(R.layout.row_layout, null);
}
TextView name = (TextView) vi.findViewById(R.id.Name);
TextView number = (TextView) vi.findViewById(R.id.Number);
HashMap<String, String> contains = new HashMap<String, String>();
contains = al.get(position);
Log.e("value check:----", contains.get("Name"));
name.setText(contains.get("Name"));
number.setText(contains.get("Number"));
return vi;
}
}
首次活动的XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".FirstActivity"
android:orientation="vertical">
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
</LinearLayout>
行布局的XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="@+id/Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
/>
<TextView
android:id="@+id/Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
/>
</LinearLayout>
修改强>
此代码用于联系人的搜索功能
我在这里做的是当用户继续输入编辑文本时,从联系人列表中搜索姓名联系人并显示在edittext下面的列表视图中......这类似于联系人列表中的默认联系人搜索功能或我们设备的电话簿
EditText edit_text=(EditText)findViewById(R.id.txtItem);
edit_text.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable changed_text) {
// TODO Auto-generated method stub
//String search_value=getText(R.id.txtItem).toString();
//Toast.makeText(getApplicationContext(), changed_text,Toast.LENGTH_SHORT).show();
display_list(changed_text.toString(),changed_text.length(), NAME[0]);
}
});
}
/** displaying the list of the best match contacts */
public void display_list(final String searchString,int searchStringLength, final String actionTOPerform)
{
listview =(ListView)findViewById(android.R.id.list);
/** Defining the ArrayAdapter to set items to ListView */
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
adapter.clear();
try {
phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
phones.moveToFirst();
while(phones.moveToNext())
{
Name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if( (Name.toLowerCase()).contains(searchString.toLowerCase()) )
{
adapter.notifyDataSetChanged();
}
}
} catch (StringIndexOutOfBoundsException e) {
//Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show();
// TODO: handle exception
}
/** Setting the adapter to the ListView */
setListAdapter(adapter);
/** Setting up the call on item click from the list */
OnItemClickListener selectedItem = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View selectedContact, int arg2,
long arg3) {
String callcontact = ((TextView)selectedContact).getText().toString();
phones.moveToFirst();
while (phones.moveToNext())
{
String Name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String Number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if(Name.compareToIgnoreCase(callcontact)== 0)
{
String url = "tel:"+Number;
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
startActivity(intent);
}
}
}
};
listview.setOnItemClickListener(selectedItem);
}//end of display_list