我想从android中的电话簿中选择一个联系人。我按一个按钮,然后显示联系人列表。当我点击我想选择我的活动中显示的点击的联系人号码,但在我的情况下,它返回null。这是我的代码:
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity {
Button b;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_PICK,People.CONTENT_URI);
startActivityForResult(intent, 100);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri contact = data.getData();
Cursor c = managedQuery(contact, null, null, null, null);
c.moveToFirst();
tv.setText(c.getString(c.getColumnIndex(People.NUMBER))+" Added");
}
}
为什么会这样? 提前谢谢。
答案 0 :(得分:6)
而不是使用People.CONTENT_URI使用ContactsContract.Contacts.CONTENT_URI
而不是
Intent intent = new Intent(Intent.ACTION_PICK,People.CONTENT_URI);
使用
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
示例:Getting Contact Phone Number
你的onacitivityResult:
Uri contact = data.getData();
ContentResolver cr = getContentResolver();
Cursor c = managedQuery(contact, null, null, null, null);
// c.moveToFirst();
while(c.moveToNext()){
String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", new String[]{id}, null);
while(pCur.moveToNext()){
String phone = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
tv.setText(name+" Added " + phone);
}
}
}
答案 1 :(得分:0)
您是否尝试选择不同的联系人?这可能是愚蠢的,但也许联系人没有号码?