2012-05-01 41 views
5

Estoy intentando implementar un AutoCompleteTextView personalizado para elegir el número de teléfono de un contacto de una lista de sugerencias que muestran el nombre del contacto, el tipo de número de teléfono y el número de teléfono. Creé un CursorAdapter personalizado que define y establece mi diseño y TextViews para cada sugerencia y consulta los contactos basados ​​en el texto ingresado por el usuario a través de runQueryOnBackgroundThread. Me encuentro con un problema donde las sugerencias parecen correctas para los dos primeros valores ingresados ​​(por ejemplo, "ab" sugiere "abcd" y "abyz") pero no para nada más allá (por ejemplo, "abc" sugiere "abyz"). Para este último, cuando se selecciona la sugerencia "abyz", se devuelven los valores de "abcd".Android - Custom AutoCompleteTextView CursorAdaptor - Comportamiento de sugerencia

Código para la actividad:

final ContactInfo cont = new ContactInfo(ctx); 
    Cursor contacts = cont.getContacts2(null); 
    startManagingCursor(contacts); 

    ContactsAutoCompleteCursorAdapter adapter = new ContactsAutoCompleteCursorAdapter(this, contacts); 
    mPersonText.setAdapter(adapter); 
    mPersonText.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
      long arg3) { 
      Cursor cursor = (Cursor) arg0.getItemAtPosition(arg2); 
      String number = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
      mPersonNum.setText(number); 
     } 
    }); 

Código para mi clase de contactos que devuelve un cursor para todos los contactos:

public Cursor getContacts2(String where) 
{ 
    Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; 
    String[] projection = new String[] { 
      ContactsContract.CommonDataKinds.Phone._ID, 
      ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, 
      ContactsContract.CommonDataKinds.Phone.TYPE, 
      ContactsContract.CommonDataKinds.Phone.NUMBER}; 

    Cursor people = ctx.getContentResolver().query(uri, projection, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC"); 

    return people; 
} 
Código

para mi CursorAdapter:

public class ContactsAutoCompleteCursorAdapter extends CursorAdapter implements Filterable { 

private TextView mName, mType, mNumber; 
private ContentResolver mContent; 

public ContactsAutoCompleteCursorAdapter(Context context, Cursor c) { 
    super(context, c); 
    mContent = context.getContentResolver(); 
} 

@Override 
public View newView(Context context, Cursor cursor, ViewGroup parent) { 

    final LayoutInflater mInflater = LayoutInflater.from(context); 
    final View ret = mInflater.inflate(R.layout.contacts_auto_list, null); 

    mName = (TextView) ret.findViewById(R.id.name); 
    mType = (TextView) ret.findViewById(R.id.phonetype); 
    mNumber = (TextView) ret.findViewById(R.id.phonenum); 

    return ret; 
} 

@Override 
public void bindView(View view, Context context, Cursor cursor) { 

    int nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME); 
    int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE); 
    int numberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); 

    String name = cursor.getString(nameIdx); 
    int type = cursor.getInt(typeIdx); 
    String number = cursor.getString(numberIdx); 

    mName.setText(name); 
    if (type == 1) {mType.setText("Home");} 
    else if (type == 2) {mType.setText("Mobile");} 
    else if (type == 3) {mType.setText("Work");} 
    else {mType.setText("Other");} 
    mNumber.setText(number); 

} 

@Override 
public String convertToString(Cursor cursor) { 
    int nameCol = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME); 
    String name = cursor.getString(nameCol); 
    return name; 
} 

@Override 
public Cursor runQueryOnBackgroundThread(CharSequence constraint) { 
    // this is how you query for suggestions 
    // notice it is just a StringBuilder building the WHERE clause of a cursor which is the used to query for results 
    if (getFilterQueryProvider() != null) { return getFilterQueryProvider().runQuery(constraint); } 

    String[] projection = new String[] { 
      ContactsContract.CommonDataKinds.Phone._ID, 
      ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, 
      ContactsContract.CommonDataKinds.Phone.TYPE, 
      ContactsContract.CommonDataKinds.Phone.NUMBER}; 

    return mContent.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, 
      "UPPER(" + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + ") LIKE '" + constraint.toString().toUpperCase() + "%'", null, 
      ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"); 
} 

}

Como dije anteriormente, cuando el usuario ingresa "ab" en AutoCompleteTextView, las sugerencias son "abcd" y "abyz", sin embargo, cuando el usuario escribe "abc", la sugerencia es simplemente "abyz". Cuando el usuario selecciona "abyz" en ese caso, se devuelven los valores de "abcd". Aquí hay dos capturas de pantalla que muestran lo que estoy tratando de describir:

enter image description hereenter image description here

que he leído todas las preguntas que pude encontrar aquí y en otros lugares, pero parece que no puede resolver esto. Soy bastante nuevo en el desarrollo de Android, así que me disculpo por adelantado si mi error es simple. ¡Gracias por adelantado!

Respuesta

2

Parece que he respondido a mi propia pregunta después de más investigaciones. Al mover el ajuste de los puntos de vista de mis textViews de la función NEWVIEW a la función Bindview parece haber hecho el truco, que creo que tiene sentido ...

@Override 
public View newView(Context context, Cursor cursor, ViewGroup parent) { 

    final LayoutInflater mInflater = LayoutInflater.from(context); 
    final View ret = mInflater.inflate(R.layout.contacts_auto_list, null); 

    return ret; 
} 

@Override 
public void bindView(View view, Context context, Cursor cursor) { 

    int nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME); 
    int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE); 
    int numberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); 

    String name = cursor.getString(nameIdx); 
    int type = cursor.getInt(typeIdx); 
    String number = cursor.getString(numberIdx); 

    mName = (TextView) view.findViewById(R.id.name); 
    mType = (TextView) view.findViewById(R.id.phonetype); 
    mNumber = (TextView) view.findViewById(R.id.phonenum); 

    mName.setText(name); 
    if (type == 1) {mType.setText("Home");} 
    else if (type == 2) {mType.setText("Mobile");} 
    else if (type == 3) {mType.setText("Work");} 
    else {mType.setText("Other");} 
    mNumber.setText(number); 
} 
0

ya pública Función de cursor runQueryOnBackgroundThread tiene en su adaptador de modo que no es necesario llamar al segundo cursor de tiempo en la actividad

no es necesario utilizar getContacts2 función

actividad

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.sms_send); 

    Cursor contacts = null; 

    mAdapter= new ContactsAutoCompleteCursorAdapter(this, contacts); 
    mTxtPhoneNo = (AutoCompleteTextView) findViewById(R.id.mmWhoNo); 
    mTxtPhoneNo.setAdapter(mAdapter); 

    mTxtPhoneNo.setOnItemClickListener(new OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
       long arg3) { 
      // TODO Auto-generated method stub 
      Cursor cursor = (Cursor) arg0.getItemAtPosition(arg2); 
      String number = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
      mTxtPhoneNo.setText(number); 

     } 
    }); 


} 

adaptador

public class ContactsAutoCompleteCursorAdapter extends CursorAdapter implements Filterable { 

private TextView mName, mType, mNumber; 
private ContentResolver mContent; 

public ContactsAutoCompleteCursorAdapter(Context context, Cursor c) { 
    super(context, c); 
    mContent = context.getContentResolver(); 
} 




@Override 
public View newView(Context context, Cursor cursor, ViewGroup parent) { 

    final LayoutInflater mInflater = LayoutInflater.from(context); 
    final View ret = mInflater.inflate(R.layout.custcontview, null); 

    return ret; 
} 

@Override 
public void bindView(View view, Context context, Cursor cursor) { 

    int nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME); 
    int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE); 
    int numberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); 

    String name = cursor.getString(nameIdx); 
    int type = cursor.getInt(typeIdx); 
    String number = cursor.getString(numberIdx); 

    mName = (TextView) view.findViewById(R.id.ccontName); 
    mType = (TextView) view.findViewById(R.id.ccontType); 
    mNumber = (TextView) view.findViewById(R.id.ccontNo); 

    mName.setText(name); 
    if (type == 1) {mType.setText("Home");} 
    else if (type == 2) {mType.setText("Mobile");} 
    else if (type == 3) {mType.setText("Work");} 
    else {mType.setText("Other");} 
    mNumber.setText(number); 
} 


@Override 
public String convertToString(Cursor cursor) { 
    int nameCol = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME); 
    String name = cursor.getString(nameCol); 
    return name; 
} 




@Override 
public Cursor runQueryOnBackgroundThread(CharSequence constraint) { 
    // this is how you query for suggestions 
    // notice it is just a StringBuilder building the WHERE clause of a cursor which is the used to query for results 



if (constraint==null) 
    return null; 

    if (getFilterQueryProvider() != null) { return getFilterQueryProvider().runQuery(constraint); } 

    String[] projection = new String[] { 
      ContactsContract.CommonDataKinds.Phone._ID, 
      ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, 
      ContactsContract.CommonDataKinds.Phone.TYPE, 
      ContactsContract.CommonDataKinds.Phone.NUMBER}; 

    return mContent.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, 
      "UPPER(" + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + ") LIKE '%" + constraint.toString().toUpperCase() + "%' or UPPER(" + ContactsContract.CommonDataKinds.Phone.NUMBER + ") LIKE '%" + constraint.toString().toUpperCase() + "%' ", null, 
      ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"); 
} 

} 

añado también consulta de búsqueda de número de teléfono en consulta

Cuestiones relacionadas