2013-10-24 60 views
0

嗨,我已經做了一個Android應用程序,我加載了所有的通訊錄聯繫人在列表中,並在它上面我放置了一個edittext,如果我輸入任何字母表,那麼它應該給我所有與列表中的字母表有關的值,我有嘗試如下,但它不工作如何從android中的列表中搜索名稱?

我的代碼如下:

AutocompliteMain.java

package com.example.autocomplite; 

import java.util.ArrayList; 
import android.app.Activity; 
import android.content.ContentResolver; 
import android.content.Intent; 
import android.database.Cursor; 
import android.net.Uri; 
import android.os.Bundle; 
import android.provider.ContactsContract; 
import android.provider.ContactsContract.Contacts; 
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 

    int PICK_CONTACT = 1200; 
    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.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 

      Intent it = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI); 

      startActivityForResult(it, PICK_CONTACT); 

      /* 
      * 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(); 
    } 

} 

autocomplitemain.xml

<?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" 
    > 

    <TableRow> 
     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:textSize="20px" 
      android:text="Write character" 
      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: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> 

回答

0

使用AutoCompleteTextView而不是EditText。所以一旦你輸入任何字符串,它會自動提供具有匹配條目的數據列表。

要不然你可以用TextChangeListener嘗試的EditText

+0

嗨蘇雷什我已經使用自動完成文本視圖。在Auto Complete文本視圖中,還提供了使用此屬性的建議textView.setThreshold(1);但我的闕是當我點擊那個記錄那個時候打開那個特定的聯繫人詳細信息視圖。 –