can't get the ListView to show contacts

11 Views Asked by At

I'm trying to make a simple app that shows your contacts, for the sake of learning. I don't have any errors, and there are contacts on the phone, but the list is still empty.

My activity_main.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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/TextID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/TextName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="24sp"
        android:textStyle="bold" />
</LinearLayout>

My MainActivity.java:

I'm pretty sure the code should be okay and work, but it doesn't.

package com.example.kontakty01;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.content.CursorLoader;

import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private static final int READ_CONTACTS_PERMISSIONS_REQUESTS = 1;

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getPermission();
        } else {
            getContacts();
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    public void getPermission() {
        if (checkSelfPermission(android.Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            getContacts();
            return;
        }

        if (shouldShowRequestPermissionRationale(android.Manifest.permission.READ_CONTACTS)) {
            //Informacja dla użytkownika, dotycząca uzasadnienia, dlaczego chcemy tego uprawnienia.
        }

        requestPermissions(new String[]{android.Manifest.permission.READ_CONTACTS},
                READ_CONTACTS_PERMISSIONS_REQUESTS);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == READ_CONTACTS_PERMISSIONS_REQUESTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getContacts();
            } else {
                Toast.makeText(this, "Brak uprawnień do odczytania Kontaktów", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void getContacts() {
        Uri uriContacts = ContactsContract.Contacts.CONTENT_URI;
        Cursor cursor;
        String[] projectionFields = new String[]{
                ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME
        };
        String selectionCondition = ContactsContract.Contacts.DISPLAY_NAME + " like ?";
        String[] selectionArguments = {"%ski"};
        String sort = ContactsContract.Contacts.DISPLAY_NAME + " desc";

        CursorLoader cursorLoader = new CursorLoader(this, uriContacts, projectionFields, selectionCondition, selectionArguments, sort);
        cursor = cursorLoader.loadInBackground();

        int[] controls = new int[]{
                R.id.TextID,
                R.id.TextName
        };

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.activity_main, cursor, projectionFields, controls, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        ((ListView)findViewById(R.id.list)).setAdapter(adapter);
    }
}

I added a permission tot he AndroidManifest.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

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

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.Kontakty01"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
0

There are 0 best solutions below