I'm trying to call contacts through the default contacts application in a simple list form. After it's done and the user presses the back button, the application should get the names of contacts but somehow the Activity Result - resultCode - is now okay so it cannot query anything; when I tried to do it although the result was not Activity.RESULT_OK , then it said the intent as a parameter of onActivityResult() has null value = NullPointerException .
If anyone has an idea to figure out this, would you help me? Below is my code.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
displayContacts();
}
private void displayContacts(){
Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (PICK_CONTACT) :
// The problem happens here. The resultCode is not okay and it throws NullPointerException at data.getData();
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndexOrThrow(Contacts.DISPLAY_NAME));
Log.d("Main", "Name: "+name); // Test: display a name on LogCat
}
}
else{
Log.e("RESULT_OK", "Error");
}
break;
}
}
I guess, when user is not selecting any contact the value in Intent data
is returning as null and you are using data
in your code:
Uri contactData = data.getData();
This is why it is causing a nullPointer Exception. If this is not the case than paste your exception log.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.