Retrieve contact list in Sketchware
To read contact list in Sketchware pro, follow the steps given below.
1. In the Sketchware project, in main.xml, add a ListView. Also add a custom view for ListView items. For the ListView, select the custom view.
2. Switch on AppCompat and design.
3. In permission manager, select android.permission.READ_CONTACTS.
4. In Activity, add Import event. Put following codes in the import event:
import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.provider.ContactsContract;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
5. Create a more block getAllContacts of type List Map. In this more block, put following codes:
ArrayList<HashMap<String, Object>> contactList = new ArrayList<>();
ContentResolver contentResolver = MainActivity.this.getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
HashMap<String, Object> contact = new HashMap<>();
contact.put("name", name);
contact.put("number", phoneNumber);
contactList.add(contact);
}
cursor.close();
}
return contactList;
In above code, the name and number of contacts is retrieved and added to a map variable using keys "name" and "number". This map variable is added to a Map list, which is returned as the result.
6. Create another more block readContacts of type regular (Void). In this more block, put following blocks which retrieve contacts and display in ListView:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.READ_CONTACTS}, 100);
}
else {
_readContacts();
}
}
@Override
public void onRequestPermissionsResult(int _requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(_requestCode, permissions, grantResults);
if (_requestCode == 100) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
_readContacts();
}
else {
SketchwareUtil.showMessage(getApplicationContext(), "Permission denied to read contacts");
}
}
Comments
Post a Comment