◎위챗 : speedseoul
http://androidexample.com/Show_Phone_Contacts_In_AutoComplete_Suggestions_-_Android_Example/index.php?view=article_discription&aid=106&aaid=128
n this example reading Phone Contacts and showing these contacts name as Auto suggestions for TextView. After select AutoComplete value showing selected contact phone number and contact name in alert.
AutoCompleteTextView is an editable text view that shows suggestions automatically while the user is entering characters. The list of suggestions is displayed from which the user can choose an item.
<?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#000000" > <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20px" android:text="Write character" android:textColor="#ffffff" android:layout_marginLeft="10dip"></TextView> </TableRow> <TableRow> <AutoCompleteTextView android:id="@+id/toNumber" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dip" android:layout_marginRight="10dip" android:textColor="#000000" android:textColorHighlight="#000000" android:textColorLink="#000000" android:textStyle="bold" android:width="250dip" /> </TableRow> <TableRow android:layout_marginTop="2dip"> <Button android:id="@+id/Send" android:clickable="true" android:width="86dip" android:text="Show Selected Value" android:layout_gravity="center_vertical|center_horizontal"/> </TableRow> </TableLayout>
- Read phone contact and store contact names in nameValueArr ArrayList and contact phone number in phoneValueArr ArrayList.
- Taking AutoCompleteTextView reference from auto_complete_string.xml file.
- Add nameValueArr ArrayList to adapter and add adapter to AutoCompleteTextView.
import java.util.ArrayList; import android.app.Activity; import android.content.ContentResolver; import android.database.Cursor; import android.os.Bundle; import android.provider.ContactsContract; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; 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(); } }
- Gave read contact permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_CONTACTS" />
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidexample.autocompleteedittext" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/Theme.Light.NoTitleBar.Workaround" > <activity android:name="com.androidexample.autocompleteedittext.AutocompleteMain" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission> <uses-permission android:name="android.permission.READ_CONTACTS" /> </manifest>
/**********************************************************************************/
If Checking on Simulator then required come phone contacts, so showing here how to add phone contact.