简体   繁体   English

我想显示联系人姓名和电话号码,但失败

[英]I want to display contact name and phone number but it fails

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

}

Actually my goal is to get the contact name and phone number but my code show the output like this please fill the phone number which is irritating me so if anybody knows about it let me know. 实际上,我的目标是获取联系人姓名和电话号码,但是我的代码显示的是这样的输出, 请填写电话号码 ,这很烦我,所以如果有人知道,请告诉我。 Thanks in advance 提前致谢

Activity which shows the name and number in list view... 在列表视图中显示姓名和号码的活动...

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());



}
}

Custom Adapter class 自定义适配器类

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 for first activity 首次活动的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 for row layout 行布局的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>

Edit 编辑

This code is for the search functionality of the contacts 此代码用于联系人的搜索功能

what I do here is when user goes on typing in the edit text the name contacts are searched from the contacts list and are displayed in the listview below edittext...this is similar to our default contacts search functionality in contacts list or phonebook of our device 我在这里所做的是,当用户继续输入编辑文本时,将从联系人列表中搜索联系人姓名并显示在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

像这样的东西在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 按名称提取联系电话号码 - Extract contact phone number by name Android:使用电话号码获取联系人姓名 - Android: Get contact name using phone number 在 Android 中获取给定电话号码的联系人姓名 - Get contact name given a phone number in Android 我想获取联系人姓名和电话号码,但是我的代码只是打印联系人姓名,所以我怎么也可以获取电话号码 - I want to get the contact name and number but my code just prints the contact name so how can I also get the number 我想根据ID号将信息添加到联系人中,但是总是将其添加到错误的名称中。 - I want to add information into the contact according to the ID number, but it always being added to the wrong name. 如果没有国家代码,请使用电话号码联系显示图片? - Get contact display picture with a phone number without a country code? 获取联系电话 - getting contact phone number 我想从电话联系人中检索联系人照片。 我应该如何获取联系人照片? - I want to retrieve the contact photo from the phone contacts. How should i proceed with getting the contact photo? 当我向其中添加新的电话号码时,Android联系人消失 - Android contact disappears when I add new phone number to it 我想获取电话号码时电话返回NULL - The phone return NULL when I want to get the phone number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM