Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/181.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从android联系人列表检索到错误的联系人数据-如何更正?_Java_Android_Android Contacts_Contact_Contactscontract - Fatal编程技术网

Java 从android联系人列表检索到错误的联系人数据-如何更正?

Java 从android联系人列表检索到错误的联系人数据-如何更正?,java,android,android-contacts,contact,contactscontract,Java,Android,Android Contacts,Contact,Contactscontract,我在我的应用程序中遇到了一些不寻常的行为-我无法理解为什么,但当用户从我的listview中选择联系人时,后来从手机中检索到的联系人不知何故不是用户选择的联系人 已更新新代码,仍不工作 public class nominateContactsActivity extends ListActivity { public String strName; public String strTelNo; public static final String PREFS_NAME = "loca

我在我的应用程序中遇到了一些不寻常的行为-我无法理解为什么,但当用户从我的listview中选择联系人时,后来从手机中检索到的联系人不知何故不是用户选择的联系人

已更新新代码,仍不工作

    public class nominateContactsActivity extends ListActivity {
public String strName;
public String strTelNo;
public static final String PREFS_NAME = "locationPrefs";
public static final ArrayList<NameValuePair> contactsArray = new ArrayList<NameValuePair>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);

setContentView(R.layout.nominatecontactsactivitytest);

this.getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
this.getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

//String[] projection = new String[] { ContactsContract.PhoneLookup.NUMBER};
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1'";
Cursor cursor = managedQuery(ContactsContract.Contacts.CONTENT_URI,null, selection, null, null);
startManagingCursor(cursor);
String[] columns = new String[] { 
        ContactsContract.Contacts.DISPLAY_NAME
        };

int[] to = new int[] { android.R.id.text1 };

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, cursor, columns, to);
this.setListAdapter(adapter);

Button finishButton = (Button) this.findViewById(R.id.finishButton);
finishButton.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {

        SimpleCursorAdapter adapter = (SimpleCursorAdapter) nominateContactsActivity.this.getListAdapter();
        ListView lv = nominateContactsActivity.this.getListView();
        SparseBooleanArray selectedItems = lv.getCheckedItemPositions();
        Cursor contactsCursor = adapter.getCursor();

        /*for (long id : lv.getCheckedItemIds()) {
            String selection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?";
            String[] args = new String[] { String.valueOf(contactId) };
            Cursor cursor=managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, selection, args, null);
        }*/


        for (long id : lv.getCheckedItemIds()) {
            long contactId = contactsCursor.getInt(contactsCursor.getColumnIndex(BaseColumns._ID));
            String selection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?";
            String[] args = new String[] { String.valueOf(contactId) };
            Cursor cursor=managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, selection, args, null);
            if (cursor.moveToFirst()) {
                strName=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                strTelNo = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));                                                      
            }
        ;}
            try {
                //Name not operationally useful - why bother storing it - keep this in case later implemented.
                //contactsArray.add(new BasicNameValuePair ("name", strName));
                contactsArray.add(new BasicNameValuePair("number", strTelNo));
            } catch(Exception e){
                e.printStackTrace();
            }

        try {
            storeContacts();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    });
}

public void storeContacts() throws ClientProtocolException, IOException{
    SharedPreferences userPrefs = this.getSharedPreferences("PREFS_NAME", 0);
    Editor edit = userPrefs.edit();
    //edit.remove("contactsData").commit();
    String formattedString = contactsArray.toString()
            .replace("number=", "") //remove number name
            .replace(" ","")        //remove spaces
            .replace("[", "")       //remove the right bracket
            .replace("]", "");      //remove the left bracket
    edit.putString("contactsData", formattedString);
    edit.commit();
    String name = userPrefs.getString("Name", null);
    String test = userPrefs.getString("contactsData", null);
    Log.d("", formattedString);
    Log.d("test = ", test);
    Intent myIntent = new Intent(nominateContactsActivity.this, rootMenuActivity.class);
    startActivity(myIntent);
          String textSMS = "You have been nominated as a contact by " + name +". Check out www.mywebsite.com for info"; 
          String retrievedContacts = userPrefs.getString("contactsData", null);
          String textPhoneNo;
          textPhoneNo = retrievedContacts;
          //textSMS = "My current location is: " + currentLocation;
          String phoneNo = textPhoneNo;
          try {
                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage(phoneNo, null, textSMS, null, null);
                Toast.makeText(getApplicationContext(), "SMS Sent!", Toast.LENGTH_LONG).show();
                Intent myIntent1 = new Intent(nominateContactsActivity.this, rootMenuActivity.class);
                startActivity(myIntent1);       
          } 
          catch (Exception e) {
                Toast.makeText(getApplicationContext(),
                "SMS failed, please try again later!",
                Toast.LENGTH_LONG).show();
                e.printStackTrace();
          } 

onClick
中,您拥有适配器。从中,您可以获得联系人的光标

Cursor contactsCursor = adapter.getCursor();
在循环中,您可以获得联系人id:

contactsCursor.moveToPosition(selectedPosition);
long contactId = contactsCursor.get(contactsCursor.getColumnIndex(BaseColumn._ID));
从那里,您可以按如下方式搜索手机:

String selection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?";
String[] args = new String[] { String.valueOf(contactId) };
Cursor cursor=managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, selection, args, null);
if (cursor.moveToFirst()) {
    // Get content here
}
从那里,您可以使用已获得的光标

编辑-简化(重新编辑,id实际上是contactId) 您可以简单地在此循环:

for (long contactId : lv.getCheckedItemIds()) {
    String selection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?";
    String[] args = new String[] { String.valueOf(contactId) };
    Cursor cursor=managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, selection, args, null);
    if (cursor.moveToFirst()) {
        // Get content here
    }
}

您正在显示联系人,但正在枚举电话。您必须找到联系人id,然后使用此id在电话表上进行查询。谢谢,这非常有用-错误现在非常明显。我该如何解决这个问题呢?花了整整一周的时间才把头发撕成这样!非常感谢您的帮助谢谢-我已尝试集成此代码,但没有logcat显示indexoutofbounds错误。我已经编辑了上面的代码。你能发布这个异常的stacktrace吗?另外,我想简化一下。您可以直接从listview:getCheckedItemIds()获取联系人ID,并循环这些ID查询电话表更新了我的问题。我来换一下contactID部分。再次感谢您的帮助我们遗漏了一个部分:在使用游标之前,在创建游标时必须首先调用cursor.moveToFirst。(我已将其添加到我的答案中)
for (long contactId : lv.getCheckedItemIds()) {
    String selection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?";
    String[] args = new String[] { String.valueOf(contactId) };
    Cursor cursor=managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, selection, args, null);
    if (cursor.moveToFirst()) {
        // Get content here
    }
}