자기 개발과 IT 프로그래밍을 위한 여행

물처럼 흐르는 시간, 그 속에서의 여행

안드로이드 기반 앱 개발부

주소록 데이터 가져오기

창조의 새싹 2018. 8. 7. 11:33

안녕하세요~ 커피백작 입니다~

한 1,2주 만인것 같네요.

바빴습니다 하하..( 바쁜때 넌 짬내서 롤 하니!? 퍽! )

하하.. 네, 서두는 슬슬 접고, 오늘은 안드로이드 스튜디오에서 주소록에 저장된 이름과 번호들을 불러오는 소스를 구하던 중, 공유하고자 올렸습니다.


즉, 구해서 공유하는 것이므로 먼저 이 글의 소스는 퍼온글임을 밝힙니다.


http://ramsandroid4all.blogspot.com/2014/01/display-all-contacts-from-contacts.html


출처 링크 구용. 아래의 칸은 해당 소스입니다.


*********************************************************************************************************************************


Display All Contacts from Contacts application in ListView



Above output checked in Real Device.

xml files under values folder:
strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Display All Contacts</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="btitle">Load Contacts</string>

</resources>

 

xml files under layout folder:
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/btitle"
        android:textSize="25sp" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:cacheColorHint="#ffccff"
        android:divider="#00ffff"
        android:dividerHeight="2sp" >
    </ListView>

</LinearLayout>


text.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textColor="#ff0000"
    android:textSize="25sp" >

</TextView>


Java Code:
MainActivity.java:
package com.ram.displayallcontacts;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;

public class MainActivity extends Activity {
    ListView list;
    LinearLayout ll;
    Button loadBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ll = (LinearLayout) findViewById(R.id.LinearLayout1);

        list = (ListView) findViewById(R.id.listView1);

        loadBtn = (Button) findViewById(R.id.button1);
        loadBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                LoadContactsAyscn lca = new LoadContactsAyscn();
                lca.execute();
            }
        });

    }

    class LoadContactsAyscn extends AsyncTask<Void, Void, ArrayList<String>> {
        ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            pd = ProgressDialog.show(MainActivity.this, "Loading Contacts",
                    "Please Wait");
        }

        @Override
        protected ArrayList<String> doInBackground(Void... params) {
            // TODO Auto-generated method stub
            ArrayList<String> contacts = new ArrayList<String>();

            Cursor c = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    null, null, null);
            while (c.moveToNext()) {

                String contactName = c
                        .getString(c
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String phNumber = c
                        .getString(c
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                contacts.add(contactName + ":" + phNumber);

            }
            c.close();

            return contacts;
        }

        @Override
        protected void onPostExecute(ArrayList<String> contacts) {
            // TODO Auto-generated method stub
            super.onPostExecute(contacts);

            pd.cancel();

            ll.removeView(loadBtn);

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                    getApplicationContext(), R.layout.text, contacts);

            list.setAdapter(adapter);

        }

    }
}

 

AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ram.displayallcontacts"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.READ_CONTACTS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ram.displayallcontacts.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>  

 

*********************************************************************************************************************************



자 위의 부분이 소스 긁어온 내용이구요.


이대로 안드로이드 스튜디오에서 소스 복붙 하고 스마트폰에서 바로실행하면?


에러뜹니다.

에러구문을 좀 보니 퍼미션 문제더라구요.

분명 manifests 에서 권한 설정을 해주었는데도 불구하고 권한 에러가 뜨길래,


설정 -> 앱 


에서 만든 앱의 주소록 권한을 봐보았습니다.

네, 꺼져있더군요.

켜주고 다시 실행해서 버튼 눌러보니 잘 불러 왔습니다.


아무래도 이 소스에, 앱을 키면 사용자가 권한을 승인하도록 하는 소스를 붙여줘야 할 것 같네요.

다음 포스트는 그 부분 까지 해서 되는지 봐보도록 하겠습니다.





 +++ 추가

 ArrayList 의 정렬에 대해서.


 주소록을 불러왔는데, 너무 난잡하고 정렬이 안되어 있더군요.

 해서 정렬할 방법을 찾다 간단한 소스를 찾았습니다.

 

 그냥 MainActivity.java 에서 doInBackground() 에서 while(c.moveToNext()) 문이 끝난 바로 아래와 c.close() 사이에.


Collections.sort(contacts);


 를 추가해 주시면됩니다.

 contacts 라는 arraylist 에 갑을 모두 add 시켜주고, 해당 list 안의 값을 정렬해 주는 명령어 입니다.


 해당 명령어를 추가하고 돌려보니 아우~ 깔금하니 좋네요 ㅎㅎㅎ