Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package test.agenda;
- import android.Manifest;
- import android.app.Activity;
- import android.app.ProgressDialog;
- import android.content.ContentResolver;
- import android.content.ContentUris;
- import android.content.Context;
- import android.content.pm.PackageManager;
- import android.database.Cursor;
- import android.net.Uri;
- import android.os.Build;
- import android.os.Bundle;
- import android.os.Handler;
- import android.provider.ContactsContract;
- import android.support.annotation.NonNull;
- import android.support.annotation.Nullable;
- import android.support.v4.app.Fragment;
- import android.support.v7.widget.LinearLayoutManager;
- import android.support.v7.widget.RecyclerView;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.Toast;
- import java.util.ArrayList;
- import test.agenda.adapter.ContactAdapter;
- import test.agenda.model.Contact;
- import test.agenda.model.Phone;
- /**
- * A simple {@link Fragment} subclass.
- * Activities that contain this fragment must implement the
- * {@link ContactFragment.OnFragmentInteractionListener} interface
- * to handle interaction events.
- * Use the {@link ContactFragment#newInstance} factory method to
- * create an instance of this fragment.
- */
- public class ContactFragment extends Fragment {
- private static final int REQUEST_READ_CONTACTS = 444;
- private RecyclerView contacts;
- private Context context;
- private ProgressDialog pDialog;
- private OnFragmentInteractionListener mListener;
- private Handler updateBarHandler;
- public ContactFragment() {
- // Required empty public constructor
- }
- /**
- * Use this factory method to create a new instance of
- * this fragment using the provided parameters.
- *
- * @return A new instance of fragment ContactFragment.
- */
- public static ContactFragment newInstance() {
- ContactFragment fragment;
- fragment = new ContactFragment();
- return fragment;
- }
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- context = getContext();
- pDialog = new ProgressDialog(context);
- pDialog.setMessage(context.getString(R.string.message_notice_reading_contact));
- pDialog.setCancelable(false);
- pDialog.show();
- }
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.fragment_contact, container, false);
- contacts = view.findViewById(R.id.contact_list);
- return view;
- }
- @Override
- public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
- super.onViewCreated(view, savedInstanceState);
- updateBarHandler = new Handler();
- loadContacts(getActivity());
- }
- @Override
- public void onAttach(Context context) {
- super.onAttach(context);
- if (context instanceof OnFragmentInteractionListener) {
- mListener = (OnFragmentInteractionListener) context;
- } else {
- Toast.makeText(context, "Contact Fragment Attach", Toast.LENGTH_LONG).show();
- }
- }
- @Override
- public void onDetach() {
- super.onDetach();
- mListener = null;
- }
- /**
- * This interface must be implemented by activities that contain this
- * fragment to allow an interaction in this fragment to be communicated
- * to the activity and potentially other fragments contained in that
- * activity.
- * <p>
- * See the Android Training lesson <a href=
- * "http://developer.android.com/training/basics/fragments/communicating.html"
- * >Communicating with Other Fragments</a> for more information.
- */
- public interface OnFragmentInteractionListener {
- void onFragmentInteraction(Uri uri);
- }
- private boolean canRequestContacts() {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
- return true;
- }
- if (context.checkSelfPermission(android.Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
- return true;
- }
- if (shouldShowRequestPermissionRationale(android.Manifest.permission.READ_CONTACTS)) {
- requestPermissions(new String[]{android.Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS);
- } else {
- requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS);
- }
- return false;
- }
- /**
- * Callback received when a permissions request has been completed.
- */
- @Override
- public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- if (requestCode == REQUEST_READ_CONTACTS && grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- getContacts(getActivity());
- }
- }
- public void getContacts(Activity activity) {
- if (!canRequestContacts()) {
- return;
- }
- ArrayList<Contact> list = new ArrayList<>();
- int read = 0;
- Cursor cursor = null;
- Cursor pCur = null;
- try {
- ContentResolver cr = context.getContentResolver();
- cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
- if (cursor == null || !cursor.moveToFirst()) {
- throw new Exception("Cursor is empty");
- }
- int total = cursor.getCount();
- while (cursor.moveToNext()) {
- if (read >= 5) {
- break;
- }
- read++;
- this.onUpdateRead(read, total);
- Contact c = new Contact();
- String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
- c.setName(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
- c.setPicture(getPhotoUri(Long.valueOf(id)));
- if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) < 1) {
- continue;
- }
- pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
- if (pCur == null || !pCur.moveToFirst()) {
- continue;
- }
- ArrayList<Phone> phones = new ArrayList<>();
- do {
- Phone p = new Phone();
- p.setNumber(pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
- p.setType(pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL)));
- phones.add(p);
- } while (pCur.moveToNext());
- pCur.close();
- c.setPhones(phones);
- list.add(c);
- }
- } catch (Exception ex) {
- Toast.makeText(context, ex.getMessage(), Toast.LENGTH_SHORT).show();
- } finally {
- if (cursor != null && !cursor.isClosed()) {
- cursor.close();
- }
- if (pCur != null && !pCur.isClosed()) {
- pCur.close();
- }
- onCompletedRead(activity, list);
- }
- }
- private Uri getPhotoUri(long contactId) {
- Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
- return Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
- }
- private void loadContacts(final Activity activity) {
- try {
- new Thread(new Runnable() {
- @Override
- public void run() {
- getContacts(activity);
- }
- }).start();
- } catch (Exception ex) {
- Toast.makeText(context, ex.getMessage(), Toast.LENGTH_SHORT).show();
- }
- }
- private void onUpdateRead(final int read, final int total) {
- updateBarHandler.post(new Runnable() {
- public void run() {
- pDialog.setMessage("Reading contacts : " + read + "/" + total);
- }
- });
- }
- private void onCompletedRead(Activity activity, final ArrayList<Contact> list) {
- // ListView has to be updated using a ui thread
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- refreshContacts(list);
- }
- });
- updateBarHandler.postDelayed(new Runnable() {
- @Override
- public void run() {
- pDialog.cancel();
- }
- }, 500);
- }
- private void refreshContacts(ArrayList<Contact> list) {
- RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
- ContactAdapter adapter = new ContactAdapter(list);
- contacts.setLayoutManager(layoutManager);
- contacts.setAdapter(adapter);
- }
- }
Add Comment
Please, Sign In to add comment