如何读取手机中的所有联系人,包括Google联系人,存入数组列表?

huangapple go评论83阅读模式
英文:

How to read all contacts in phone, including google contacts, into an array list?

问题

我尝试过这个在这里它只读取了4个联系人但没有读取所有联系人

无法启动活动出现以下问题

    ComponentInfo{com.developer.sparty/com.developer.sparty.DashboardActivity}: java.lang.NullPointerException: println 需要一条消息
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3632)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3784)
            at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
            at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
            at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2270)

我的 `DashboardActivity` 代码如下

    public class DashboardActivity extends AppCompatActivity {
    ActionBar actionBar;
    ArrayList<CONTACTS_DATA> listOfContacts;
    public static final int REQUEST_READ_CONTACTS = 79;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);
        actionBar = getSupportActionBar();
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0582CA")));
        //on start default
        actionBar.setTitle(" " + "Chats");
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setLogo(R.drawable.logo);
        actionBar.setDisplayUseLogoEnabled(true);
        actionBar.show();
        listOfContacts = new ArrayList<>();
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS)
                == PackageManager.PERMISSION_GRANTED) {
           ReadContactsAndShowUsers();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_CONTACTS},
                    REQUEST_READ_CONTACTS);
        }
    }

    public class CONTACTS_DATA {
        public String contact_data_name;
        public String contact_data_phoneNo;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_READ_CONTACTS: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                  ReadContactsAndShowUsers();
                } else {
                    Toast.makeText(this, "需要权限", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }

    private void ReadContactsAndShowUsers() {
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
        if ((cur!=null?cur.getCount():0) > 0) {
            while (cur!=null && cur.moveToNext()) {
                CONTACTS_DATA contacts_data=new CONTACTS_DATA();
                String id = cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(
                        ContactsContract.Contacts.DISPLAY_NAME));
                contacts_data.contact_data_name=name;
                if (cur.getInt(cur.getColumnIndex( ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    Cursor pCur = cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        String phoneNo = pCur.getString(pCur.getColumnIndex(
                                ContactsContract.CommonDataKinds.Phone.NUMBER));
                        contacts_data.contact_data_phoneNo=phoneNo;
                    }
                    pCur.close();
                }
                listOfContacts.add(contacts_data);
            }
        }
        if (cur!=null) {
            cur.close();
        }
        for (int i = 0; i < listOfContacts.size(); i++) {
            Log.d("联系人", listOfContacts.get(i).contact_data_phoneNo);
            Log.d("联系人", listOfContacts.get(i).contact_data_name);
        }
    }

    }
英文:

I have tried this where it reads only 4 contacts but does not read all the contacts?

Unable to start activity and getting the below issue:

ComponentInfo{com.developer.sparty/com.developer.sparty.DashboardActivity}: java.lang.NullPointerException: println needs a message
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3632)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3784)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2270)

My DashboardActivity code is

public class DashboardActivity extends AppCompatActivity {
ActionBar actionBar;
ArrayList&lt;CONTACTS_DATA&gt; listOfContacts;
public static final int REQUEST_READ_CONTACTS = 79;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(&quot;#0582CA&quot;)));
//on start default
actionBar.setTitle(&quot; &quot; + &quot;Chats&quot;);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setLogo(R.drawable.logo);
actionBar.setDisplayUseLogoEnabled(true);
actionBar.show();
listOfContacts = new ArrayList&lt;&gt;();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS)
== PackageManager.PERMISSION_GRANTED) {
ReadContactsAndShowUsers();
} else {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_CONTACTS},
REQUEST_READ_CONTACTS);
}
}
public class CONTACTS_DATA {
public String contact_data_name;
public String contact_data_phoneNo;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_READ_CONTACTS: {
if (grantResults.length &gt; 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ReadContactsAndShowUsers();
} else {
Toast.makeText(this, &quot;Permission is required&quot;, Toast.LENGTH_SHORT).show();
}
return;
}
}
}
private void ReadContactsAndShowUsers() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur!=null?cur.getCount():0)&gt;0) {
while (cur!=null&amp;&amp;cur.moveToNext()) {
CONTACTS_DATA contacts_data=new CONTACTS_DATA();
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
contacts_data.contact_data_name=name;
if (cur.getInt(cur.getColumnIndex( ContactsContract.Contacts.HAS_PHONE_NUMBER)) &gt; 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + &quot; = ?&quot;,
new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts_data.contact_data_phoneNo=phoneNo;
}
pCur.close();
}
listOfContacts.add(contacts_data);
}
}
if (cur!=null) {
cur.close();
}
for (int i = 0; i &lt; listOfContacts.size(); i++) {
Log.d(&quot;CONTACT&quot;, listOfContacts.get(i).contact_data_phoneNo);
Log.d(&quot;CONTACT&quot;, listOfContacts.get(i).contact_data_name);
}
}
}

答案1

得分: 0

将这些代码行放在try-catch块中,因为有一些联系人没有与其关联的电话号码,所以可能会出现null值导致崩溃。

for (int i = 0; i < listOfContacts.size(); i++) {
    try{
        Log.d("CONTACT", listOfContacts.get(i).contact_data_phoneNo);
    } catch(Exception e){
        e.printStackTrace();
    }
    try{
        Log.d("CONTACT", listOfContacts.get(i).contact_data_name);
    } catch(Exception e){
        e.printStackTrace();
    }
}
英文:

Put these lines in try catch because there are few contacts which do not have phone number associated with them so, you are getting null and crash.

for (int i = 0; i &lt; listOfContacts.size(); i++) {
try{
Log.d(&quot;CONTACT&quot;, listOfContacts.get(i).contact_data_phoneNo);
} catch(Exception e){
e.printStackTrace();
}
try{
Log.d(&quot;CONTACT&quot;, listOfContacts.get(i).contact_data_name);
} catch(Exception e){
e.printStackTrace();
}
}

huangapple
  • 本文由 发表于 2020年8月13日 13:23:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63388606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定