(안드로이드) 연락처를 불러오는 과정에서 팅겨버리네요
조회수 555회
연락처에서 데이터를 가져와서 친구로 등록해주는 기능을 만들려고 합니다. 그런데 연락처로 등록 버튼을 누른 뒤 폰에 등록된 연락처를 보여주고 선택할 수 있는 화면까지 가는데는 문제 없는데, 등록하려는 연락처를 누르는 순간 앱이 종료되버리거나 까만 화면으로 되버리네요.
원인을 좀 알고 싶네요..
밑의 코드는 액티비티 코드입니다. 너무 길어보이니 패키지랑 import는 제외했어요.
public class AddFriendsActivity extends AppCompatActivity {
String name = "";
String number = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_friends);
Button registerWithPhoneNumberButton = (Button) findViewById(R.id.registerWithPhoneNumberButton);
registerWithPhoneNumberButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(v.getContext(), EnteringInformationOfFriendActivity.class);
startActivity(intent);
}
});
Button registerWithAddressBookButton = (Button) findViewById(R.id.registerWithAddressBookButton);
registerWithAddressBookButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
// 연락처 선택 화면
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setData(ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, 0);
}
});
Button registerWithKakaoButton = (Button) findViewById(R.id.registerWithKakaoButton);
registerWithKakaoButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
// 카카오톡과 연동
}
});
EditText nameTestEdit = (EditText) findViewById(R.id.nameTestEdit);
nameTestEdit.setText(name);
EditText numTestEdit = (EditText) findViewById(R.id.numTestEdit);
numTestEdit.setText(number);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK)
{
Cursor cursor = getContentResolver().query(data.getData(),
new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER}, null, null, null);
cursor.moveToFirst();
name = cursor.getString(0); // 0 -> 이름
number = cursor.getString(1); // 1 -> 번호
cursor.close();
}
// 여길 거치지 않고 정지되는 것으로 보임
if(resultCode == RESULT_CANCELED)
{
Toast failToast = Toast.makeText(this.getApplicationContext(), "연락처를 불러오는데 실패했습니다.", Toast.LENGTH_SHORT);
Handler myHandler = new Handler();
myHandler.postDelayed(new Runnable() {
@Override
public void run() {
failToast.show();
}
}, 500); // 0.5초 후 failToast를 보여줌
}
super.onActivityResult(requestCode, resultCode, data);
}
}
혹시 필요할 수 있으니 xml도..
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.tempus.ui.friends.AddFriendsActivity"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:gravity="center"
android:layout_gravity="center|left"
android:layout_marginLeft="20dp"
android:textSize="15dp"
android:textStyle="bold"
android:text="지인 등록"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/layoutborder4">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="30dp"
android:text="원하는 등록 방법을 선택하세요."/>
<Button
android:id="@+id/registerWithPhoneNumberButton"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="30dp"
android:text="전화번호로 등록"/>
<Button
android:id="@+id/registerWithAddressBookButton"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="30dp"
android:text="연락처로 등록"/>
<Button
android:id="@+id/registerWithKakaoButton"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="30dp"
android:text="카카오톡으로 등록"/>
<EditText
android:id="@+id/nameTestEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="30dp"
android:text="test"/>
<EditText
android:id="@+id/numTestEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="30dp"
android:text="test"/>
</LinearLayout>
</LinearLayout>
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
// 여길 거치지 않고 정지되는 것으로 보임
커서에 접근하는데 에러가 있었다고 볼 수 밖에 없습니다. 커서에 너무 조심없이 접근하는 감이 있습니다. moveToFirst() 메서드는 boolean 값을 리턴하여 이것이 false 라면 커서가 비어있다는 뜻입니다. if 문으로 한번 감싸 실행해서 데이터가 잘 넘어오는지 확인하셔야 할 것 같습니다.
데이터가 잘 넘어오지 않는다면 프로젝션 부분에 문제가 있을 수 있습니다.
getContentResolver().query(data.getData(), null, null, null, null);
이렇게 프로젝션을 null 로 하여 모든 데이터를 검색해서 커서에 데이터가 있는지 없는지도 확인해보시기 바랍니다.
댓글 입력