Guest User

Untitled

a guest
Apr 20th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.97 KB | None | 0 0
  1. package test.agenda;
  2.  
  3. import android.Manifest;
  4. import android.app.Activity;
  5. import android.app.ProgressDialog;
  6. import android.content.ContentResolver;
  7. import android.content.ContentUris;
  8. import android.content.Context;
  9. import android.content.pm.PackageManager;
  10. import android.database.Cursor;
  11. import android.net.Uri;
  12. import android.os.Build;
  13. import android.os.Bundle;
  14. import android.os.Handler;
  15. import android.provider.ContactsContract;
  16. import android.support.annotation.NonNull;
  17. import android.support.annotation.Nullable;
  18. import android.support.v4.app.Fragment;
  19. import android.support.v7.widget.LinearLayoutManager;
  20. import android.support.v7.widget.RecyclerView;
  21. import android.view.LayoutInflater;
  22. import android.view.View;
  23. import android.view.ViewGroup;
  24. import android.widget.Toast;
  25.  
  26. import java.util.ArrayList;
  27.  
  28. import test.agenda.adapter.ContactAdapter;
  29. import test.agenda.model.Contact;
  30. import test.agenda.model.Phone;
  31.  
  32.  
  33. /**
  34. * A simple {@link Fragment} subclass.
  35. * Activities that contain this fragment must implement the
  36. * {@link ContactFragment.OnFragmentInteractionListener} interface
  37. * to handle interaction events.
  38. * Use the {@link ContactFragment#newInstance} factory method to
  39. * create an instance of this fragment.
  40. */
  41. public class ContactFragment extends Fragment {
  42. private static final int REQUEST_READ_CONTACTS = 444;
  43. private RecyclerView contacts;
  44. private Context context;
  45. private ProgressDialog pDialog;
  46. private OnFragmentInteractionListener mListener;
  47. private Handler updateBarHandler;
  48.  
  49. public ContactFragment() {
  50. // Required empty public constructor
  51. }
  52.  
  53. /**
  54. * Use this factory method to create a new instance of
  55. * this fragment using the provided parameters.
  56. *
  57. * @return A new instance of fragment ContactFragment.
  58. */
  59. public static ContactFragment newInstance() {
  60. ContactFragment fragment;
  61. fragment = new ContactFragment();
  62. return fragment;
  63. }
  64.  
  65. @Override
  66. public void onCreate(Bundle savedInstanceState) {
  67. super.onCreate(savedInstanceState);
  68. context = getContext();
  69.  
  70. pDialog = new ProgressDialog(context);
  71. pDialog.setMessage(context.getString(R.string.message_notice_reading_contact));
  72. pDialog.setCancelable(false);
  73. pDialog.show();
  74.  
  75. }
  76.  
  77. @Override
  78. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  79. Bundle savedInstanceState) {
  80. View view = inflater.inflate(R.layout.fragment_contact, container, false);
  81. contacts = view.findViewById(R.id.contact_list);
  82. return view;
  83. }
  84.  
  85. @Override
  86. public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
  87. super.onViewCreated(view, savedInstanceState);
  88. updateBarHandler = new Handler();
  89. loadContacts(getActivity());
  90.  
  91. }
  92.  
  93. @Override
  94. public void onAttach(Context context) {
  95. super.onAttach(context);
  96. if (context instanceof OnFragmentInteractionListener) {
  97. mListener = (OnFragmentInteractionListener) context;
  98. } else {
  99. Toast.makeText(context, "Contact Fragment Attach", Toast.LENGTH_LONG).show();
  100. }
  101. }
  102.  
  103. @Override
  104. public void onDetach() {
  105. super.onDetach();
  106. mListener = null;
  107. }
  108.  
  109. /**
  110. * This interface must be implemented by activities that contain this
  111. * fragment to allow an interaction in this fragment to be communicated
  112. * to the activity and potentially other fragments contained in that
  113. * activity.
  114. * <p>
  115. * See the Android Training lesson <a href=
  116. * "http://developer.android.com/training/basics/fragments/communicating.html"
  117. * >Communicating with Other Fragments</a> for more information.
  118. */
  119. public interface OnFragmentInteractionListener {
  120. void onFragmentInteraction(Uri uri);
  121. }
  122.  
  123.  
  124. private boolean canRequestContacts() {
  125. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
  126. return true;
  127. }
  128. if (context.checkSelfPermission(android.Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
  129. return true;
  130. }
  131. if (shouldShowRequestPermissionRationale(android.Manifest.permission.READ_CONTACTS)) {
  132. requestPermissions(new String[]{android.Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS);
  133. } else {
  134. requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS);
  135. }
  136. return false;
  137. }
  138.  
  139.  
  140. /**
  141. * Callback received when a permissions request has been completed.
  142. */
  143. @Override
  144. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  145. if (requestCode == REQUEST_READ_CONTACTS && grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  146. getContacts(getActivity());
  147. }
  148. }
  149.  
  150. public void getContacts(Activity activity) {
  151. if (!canRequestContacts()) {
  152. return;
  153. }
  154.  
  155. ArrayList<Contact> list = new ArrayList<>();
  156. int read = 0;
  157. Cursor cursor = null;
  158. Cursor pCur = null;
  159. try {
  160. ContentResolver cr = context.getContentResolver();
  161. cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
  162. if (cursor == null || !cursor.moveToFirst()) {
  163. throw new Exception("Cursor is empty");
  164. }
  165. int total = cursor.getCount();
  166. while (cursor.moveToNext()) {
  167. if (read >= 5) {
  168. break;
  169. }
  170. read++;
  171. this.onUpdateRead(read, total);
  172. Contact c = new Contact();
  173. String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
  174. c.setName(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
  175. c.setPicture(getPhotoUri(Long.valueOf(id)));
  176.  
  177. if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) < 1) {
  178. continue;
  179. }
  180. pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
  181. if (pCur == null || !pCur.moveToFirst()) {
  182. continue;
  183. }
  184. ArrayList<Phone> phones = new ArrayList<>();
  185. do {
  186. Phone p = new Phone();
  187. p.setNumber(pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
  188. p.setType(pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL)));
  189. phones.add(p);
  190. } while (pCur.moveToNext());
  191. pCur.close();
  192. c.setPhones(phones);
  193. list.add(c);
  194. }
  195. } catch (Exception ex) {
  196. Toast.makeText(context, ex.getMessage(), Toast.LENGTH_SHORT).show();
  197. } finally {
  198. if (cursor != null && !cursor.isClosed()) {
  199. cursor.close();
  200. }
  201. if (pCur != null && !pCur.isClosed()) {
  202. pCur.close();
  203. }
  204. onCompletedRead(activity, list);
  205. }
  206. }
  207.  
  208. private Uri getPhotoUri(long contactId) {
  209. Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
  210. return Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
  211. }
  212.  
  213. private void loadContacts(final Activity activity) {
  214. try {
  215. new Thread(new Runnable() {
  216. @Override
  217. public void run() {
  218. getContacts(activity);
  219. }
  220. }).start();
  221. } catch (Exception ex) {
  222. Toast.makeText(context, ex.getMessage(), Toast.LENGTH_SHORT).show();
  223. }
  224. }
  225.  
  226.  
  227. private void onUpdateRead(final int read, final int total) {
  228. updateBarHandler.post(new Runnable() {
  229. public void run() {
  230. pDialog.setMessage("Reading contacts : " + read + "/" + total);
  231. }
  232. });
  233. }
  234.  
  235. private void onCompletedRead(Activity activity, final ArrayList<Contact> list) {
  236. // ListView has to be updated using a ui thread
  237. activity.runOnUiThread(new Runnable() {
  238. @Override
  239. public void run() {
  240. refreshContacts(list);
  241. }
  242. });
  243.  
  244. updateBarHandler.postDelayed(new Runnable() {
  245. @Override
  246. public void run() {
  247. pDialog.cancel();
  248. }
  249. }, 500);
  250. }
  251.  
  252. private void refreshContacts(ArrayList<Contact> list) {
  253. RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
  254. ContactAdapter adapter = new ContactAdapter(list);
  255. contacts.setLayoutManager(layoutManager);
  256. contacts.setAdapter(adapter);
  257. }
  258. }
Add Comment
Please, Sign In to add comment