I'm developing a music player. I want to get all .mp3 format files from android device.
But this code is not getting any files. My .mp3 files are in 'sdcard/music' folder. If i change the MEDIA_PATH = new String("sdcard/music"); like this it's getting files only from that music folder. But i need to get all .mp3 files from each and every folder in my external/internal memorycard. Please help me.
this is my code.
final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory());
public void Generate_Database(){
File home = new File(MEDIA_PATH);
if (home.listFiles(new FileExtensionFilter()).length > 0) {
for (File file : home.listFiles(new FileExtensionFilter())) {
String title = file.getName().substring(0, (file.getName().length() - 4));
String path = file.getPath();
mediaInfo.setDataSource(path);
String albumName = "unknown",artist = "unknown",genere = "unknown",duration = "unknown",composer = "unknown";
if(mediaInfo.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM) == null)
albumName = "unknown";
else{
albumName = mediaInfo.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
}
if(mediaInfo.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST) == null)
artist = "unknown";
else{
artist = mediaInfo.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
}
if(mediaInfo.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE) == null)
genere = "unknown";
else{
genere = mediaInfo.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE);
}
if(mediaInfo.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION) == null)
duration = "unknown";
else{
duration = mediaInfo.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
}
if(mediaInfo.extractMetadata(MediaMetadataRetriever.METADATA_KEY_COMPOSER) == null)
composer = "unknown";
else{
composer = mediaInfo.extractMetadata(MediaMetadataRetriever.METADATA_KEY_COMPOSER);
}
//Toast.makeText(getApplicationContext(), title+path+ albumName+artist+ genere+ duration+ composer, Toast.LENGTH_LONG).show();
ds.createEntry2(title, path, albumName, artist, genere, duration, composer);
}
}
this is used to extract the .mp3 files
class FileExtensionFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".MP3"));
}
}
Query the media files
Check if the file is an mp3 by checking its extension
The following method will return all the mp3 audio files in your device:
private List<String> scanDeviceForMp3Files(){
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
String[] projection = {
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DURATION
};
final String sortOrder = MediaStore.Audio.AudioColumns.TITLE + " COLLATE LOCALIZED ASC";
List<String> mp3Files = new ArrayList<>();
Cursor cursor = null;
try {
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
cursor = getContentResolver().query(uri, projection, selection, null, sortOrder);
if( cursor != null){
cursor.moveToFirst();
while( !cursor.isAfterLast() ){
String title = cursor.getString(0);
String artist = cursor.getString(1);
String path = cursor.getString(2);
String displayName = cursor.getString(3);
String songDuration = cursor.getString(4);
cursor.moveToNext();
if(path != null && path.endsWith(".mp3")) {
mp3Files.add(path);
}
}
}
// print to see list of mp3 files
for( String file : mp3Files) {
Log.i("TAG", file);
}
} catch (Exception e) {
Log.e("TAG", e.toString());
}finally{
if( cursor != null){
cursor.close();
}
}
return mp3Files;
}
Related
I am trying to build a Pdf Scanner Android application for api level 21 and above, in the app I have an option to show and manage all the pdf files created by the application through the application.
I want to fetch Pdf files from Documents/PDFScanner folder and show them in a fragment. So far I am getting empty array but I have Pdf files in the folder.
I have tested the code on Android 11 and Android 8.1 devices.
here is my function to get pdf files
private void getPDFFilesFromDirecotry() {
Uri collection = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
} else {
collection = MediaStore.Files.getContentUri("external");
}
String[] projection = {MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DISPLAY_NAME};
Cursor mediaCursor = applicationContext.getContentResolver().query(collection,
projection,
MediaStore.MediaColumns.DATA + " LIKE?",
new String[]{Environment.DIRECTORY_DOCUMENTS + "/PDFScanner"},
null);
Log.e("TAG", "Message: " + mediaCursor.getCount());
if (mediaCursor == null || mediaCursor.getCount() <= 0 || !mediaCursor.moveToFirst()) {
Log.e("tag","No data");
return;
}
String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
MediaScannerConnection.scanFile(applicationContext, new String[]{file.getPath()}, new String[]{mimetype}, null);
while (mediaCursor.moveToNext()) {
Log.e("TAG", "Message: ");
String path = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.MediaColumns.BUCKET_DISPLAY_NAME));
Log.e("TAG", "getPDFFilesFromDirectory Path: " + path);
if (path != null) {
ivNoData.setVisibility(View.GONE);
file = new File(path);
String name = file.getName();
int position = name.lastIndexOf(".");
if (position > 0 && position < name.length() - 1) {
name = name.substring(0, position);
}
Date dateinMillis = new Date(file.lastModified());
#SuppressLint("SimpleDateFormat")
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy hh.mm a");
String date = dateFormat.format(dateinMillis);
String size = formatSize(file.length());
viewFilesArray.add(new ViewFilesModel(path, name, size, date));
}
}
mediaCursor.close();
Log.e("TAG", "getPDFFilesFromDirectory: " + viewFilesArray.size());
filesAdapter.notifyDataSetChanged();
}
Thanks for the help.
I tried other solutions on Stack Overflow, but they are not working with my problem. The below code is working perfectly before Android Q versions, but did not work with Android Q.
Here are the functions which are used to fetch albums and images.
First for fetching AlbumImages:
public static ArrayList<ImageFolder> getPicturePaths(Context context){
ArrayList<ImageFolder> picFolders = new ArrayList<>();
ArrayList<String> picPaths = new ArrayList<>();
Uri allImagesuri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.ImageColumns.DATA, MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME, MediaStore.Images.Media.BUCKET_ID};
Cursor cursor = context.getContentResolver().query(allImagesuri, projection, null, null, null);
try {
if (cursor != null) {
cursor.moveToFirst();
}
do {
ImageFolder folds = new ImageFolder();
String name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME));
String folder = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME));
String datapath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
//String folderpaths = datapath.replace(name,"");
String folderpaths = datapath.substring(0, datapath.lastIndexOf(folder + "/"));
folderpaths = folderpaths + folder + "/";
if (!picPaths.contains(folderpaths)) {
picPaths.add(folderpaths);
folds.setPath(folderpaths);
folds.setFolderName(folder);
folds.setFirstPic(datapath);//if the folder has only one picture this line helps to set it as first so as to avoid blank image in itemview
folds.addpics();
picFolders.add(folds);
} else {
for (int i = 0; i < picFolders.size(); i++) {
if (picFolders.get(i).getPath().equals(folderpaths)) {
picFolders.get(i).setFirstPic(datapath);
picFolders.get(i).addpics();
}
}
}
} while (cursor.moveToNext());
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
return picFolders;
}
And here is the method to fetch images from albums:
public static ArrayList<PhotoItemModel> getAllImagesByFolder(Context context, String path){
ArrayList<PhotoItemModel> images = new ArrayList<>();
Uri allImagesuri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = { MediaStore.Images.ImageColumns.DATA ,MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.SIZE};
Cursor cursor = context.getContentResolver().query( allImagesuri, projection, MediaStore.Images.Media.DATA + " like ? ", new String[] {"%"+path+"%"}, null);
try {
cursor.moveToFirst();
do{
PhotoItemModel pic = new PhotoItemModel();
pic.setPicturName(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)));
pic.setPicturePath(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)));
pic.setPictureSize(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE)));
images.add(pic);
}while(cursor.moveToNext());
cursor.close();
ArrayList<PhotoItemModel> reSelection = new ArrayList<>();
for(int i = images.size()-1;i > -1;i--){
reSelection.add(images.get(i));
}
images = reSelection;
} catch (Exception e) {
e.printStackTrace();
}
return images;
}
How can I fix this?
First check whether the Android Q is getting some problem (permission related) to reach Folder path
String folderpaths = datapath.substring(0, datapath.lastIndexOf(folder + "/"));
folderpaths = folderpaths + folder + "/";
Under Android Q you cannot use the .DATA column.
Instead use .RELATIVE_PATH.
Read the threads tagged mediastore.
I am trying to make an Attendance APP for my college. I have used SQLite for Data Storage(Student's List, Attendance Data, etc) I want the Attendance DATA to be exported as a CSV file. The problem is, when i export the file only the last entry of the SQLite Db is being written to the CSV. I have attached the code below for better understanding.
public void exportExcelSheet() {
DatabaseHandler mDbHandler = new DatabaseHandler(mActivity);
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, "Report.csv");
String[] ColumnNames = {"Roll No.","Name","LA","LT","% age"};
String studentInfoQuery = "SELECT * FROM StudentList";
Cursor studentsListCursor = mDbHandler.execQuery(studentInfoQuery);
studentsListCursor.moveToFirst();
while(!studentsListCursor.isAfterLast()) {
String AttendanceListQuery = "SELECT * FROM AttendanceSheet WHERE StudRoll = '" + studentsListCursor.getPosition() + "';";
String AttendanceQuery = "SELECT * FROM AttendanceSheet WHERE StudRoll = '" + studentsListCursor.getPosition() + "' AND isPresent = 1";
int attendancePercent = 0;
Cursor totalClasses = mDbHandler.execQuery(AttendanceListQuery);
Cursor attendedClasses = mDbHandler.execQuery(AttendanceQuery);
if (totalClasses == null) {
Log.d("profile", "totalClasses null");
}
if (attendedClasses == null) {
Log.d("profile", "attendedClasses null");
}
if (totalClasses != null && attendedClasses != null) {
totalClasses.moveToFirst();
attendedClasses.moveToFirst();
try {
attendancePercent = (int) (((float) attendedClasses.getCount() / totalClasses.getCount()) * 100);
} catch (Exception e) {
attendancePercent = -1;
}
}
assert attendedClasses != null;
assert totalClasses != null;
String showAttendedLectures = String.valueOf(attendedClasses.getCount());
String showTotalLectures = String.valueOf(totalClasses.getCount());
//String showMissedLectures = String.valueOf(totalClasses.getCount() - attendedClasses.getCount());
String AttendancePercentage = String.valueOf(attendancePercent);
try
{
if(!file.exists()){
file.createNewFile();
}
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
csvWrite.writeNext(ColumnNames);
String[] arrStr ={studentsListCursor.getString(1),studentsListCursor.getString(0), showAttendedLectures, showTotalLectures, AttendancePercentage + " %"};
csvWrite.writeNext(arrStr);
studentsListCursor.moveToNext();
csvWrite.close();
}
catch(Exception sqlException)
{
Toast.makeText(mActivity, "FAILED", Toast.LENGTH_SHORT).show();
Log.e("MainActivity", sqlException.getMessage(), sqlException);
}
Toast.makeText(mActivity, "Saved", Toast.LENGTH_SHORT).show();
}
}
}
Here's What the CSV File looks like.
There is just a small mistake in this code that the csvWriter object created whenever the do-while loop executes, so the last output CSV file only had the single and last line fetched from the cursor.
This should fix the issue:
public void exportExcelSheet() {
DatabaseHandler mDbHandler = new DatabaseHandler(mActivity);
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, "Report.csv");
// ============== CHANGE ==============
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
String[] ColumnNames = {"Roll No.", "Name", "LA", "LT", "% age"};
// ============== CHANGE ==============
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
csvWrite.writeNext(ColumnNames);
String studentInfoQuery = "SELECT * FROM StudentList";
Cursor studentsListCursor = mDbHandler.execQuery(studentInfoQuery);
studentsListCursor.moveToFirst();
// ============== CHANGE ==============
do {
String AttendanceListQuery = "SELECT * FROM AttendanceSheet WHERE StudRoll = '" + studentsListCursor.getPosition() + "';";
String AttendanceQuery = "SELECT * FROM AttendanceSheet WHERE StudRoll = '" + studentsListCursor.getPosition() + "' AND isPresent = 1";
int attendancePercent = 0;
Cursor totalClasses = mDbHandler.execQuery(AttendanceListQuery);
Cursor attendedClasses = mDbHandler.execQuery(AttendanceQuery);
if (totalClasses == null) {
Log.d("profile", "totalClasses null");
}
if (attendedClasses == null) {
Log.d("profile", "attendedClasses null");
}
if (totalClasses != null && attendedClasses != null) {
totalClasses.moveToFirst();
attendedClasses.moveToFirst();
try {
attendancePercent = (int) (((float) attendedClasses.getCount() / totalClasses.getCount()) * 100);
} catch (Exception e) {
attendancePercent = -1;
}
}
assert attendedClasses != null;
assert totalClasses != null;
String showAttendedLectures = String.valueOf(attendedClasses.getCount());
String showTotalLectures = String.valueOf(totalClasses.getCount());
//String showMissedLectures = String.valueOf(totalClasses.getCount() - attendedClasses.getCount());
String AttendancePercentage = String.valueOf(attendancePercent);
try {
String[] arrStr = {studentsListCursor.getString(1), studentsListCursor.getString(0), showAttendedLectures, showTotalLectures, AttendancePercentage + " %"};
csvWrite.writeNext(arrStr);
// ============== CHANGE ==============
// studentsListCursor.moveToNext();
} catch (Exception sqlException) {
Toast.makeText(mActivity, "FAILED", Toast.LENGTH_SHORT).show();
Log.e("MainActivity", sqlException.getMessage(), sqlException);
}
Toast.makeText(mActivity, "Saved", Toast.LENGTH_SHORT).show();
}
// ============== CHANGE ==============
while (studentsListCursor.moveToNext());
csvWrite.close();
}
For anyone else looking answer for a similar question, on the basis of Dheeraj's Code and One other minor change, the final WORKING Code would be -
public void exportExcelSheet() throws IOException {
DatabaseHandler mDbHandler = new DatabaseHandler(mActivity);
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, "Report.csv");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
String[] ColumnNames = {"Roll No.", "Name", "LA", "LT", "% age"};
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
csvWrite.writeNext(ColumnNames);
String studentInfoQuery = "SELECT * FROM StudentList";
Cursor studentsListCursor = mDbHandler.execQuery(studentInfoQuery);
studentsListCursor.moveToFirst();
do {
int studentRoll = studentsListCursor.getPosition() + 1;
String AttendanceListQuery = "SELECT * FROM AttendanceSheet WHERE StudRoll = '" + studentRoll + "';";
String AttendanceQuery = "SELECT * FROM AttendanceSheet WHERE StudRoll = '" + studentRoll + "' AND isPresent = 1";
int attendancePercent = 0;
Cursor totalClasses = mDbHandler.execQuery(AttendanceListQuery);
Cursor attendedClasses = mDbHandler.execQuery(AttendanceQuery);
if (totalClasses == null) {
Log.d("profile", "totalClasses null");
}
if (attendedClasses == null) {
Log.d("profile", "attendedClasses null");
}
if (totalClasses != null && attendedClasses != null) {
totalClasses.moveToFirst();
attendedClasses.moveToFirst();
try {
attendancePercent = (int) (((float) attendedClasses.getCount() / totalClasses.getCount()) * 100);
} catch (Exception e) {
attendancePercent = -1;
}
}
assert attendedClasses != null;
assert totalClasses != null;
String showAttendedLectures = String.valueOf(attendedClasses.getCount());
String showTotalLectures = String.valueOf(totalClasses.getCount());
//String showMissedLectures = String.valueOf(totalClasses.getCount() - attendedClasses.getCount());
String AttendancePercentage = String.valueOf(attendancePercent);
try {
String[] arrStr = {studentsListCursor.getString(1), studentsListCursor.getString(0), showAttendedLectures, showTotalLectures, AttendancePercentage + " %"};
csvWrite.writeNext(arrStr);
} catch (Exception sqlException) {
Toast.makeText(mActivity, "FAILED", Toast.LENGTH_SHORT).show();
Log.e("MainActivity", sqlException.getMessage(), sqlException);
}
Toast.makeText(mActivity, "Saved", Toast.LENGTH_SHORT).show();
}
while (studentsListCursor.moveToNext());
csvWrite.close();
}
I search about read song in android and I see a code from you:
private static ArrayList<SongModel> LoadSongsFromCard() {
ArrayList<SongModel> songs = new ArrayList<SongModel>();
// Filter only mp3s, only those marked by the MediaStore to be music and longer than 1 minute
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0"
+ " AND " + MediaStore.Audio.Media.MIME_TYPE + "= 'audio/mpeg'"
+ " AND " + MediaStore.Audio.Media.DURATION + " > 60000";
final String[] projection = new String[] {
MediaStore.Audio.Media._ID, //0
MediaStore.Audio.Media.TITLE, //1
MediaStore.Audio.Media.ARTIST, //2
MediaStore.Audio.Media.DATA, //3
MediaStore.Audio.Media.DISPLAY_NAME
};
final String sortOrder = MediaStore.Audio.AudioColumns.TITLE
+ " COLLATE LOCALIZED ASC";
Cursor cursor = null;
try {
// the uri of the table that we want to query
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; //getContentUriForPath("");
// query the db
cursor = _context.getContentResolver().query(uri,
projection, selection, null, sortOrder);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
//if (cursor.getString(3).contains("AwesomePlaylists")) {
SongModel GSC = new SongModel();
GSC.ID = cursor.getLong(0);
GSC.songTitle = cursor.getString(1);
GSC.songArtist = cursor.getString(2);
GSC.path = cursor.getString(3);
// This code assumes genre is stored in the first letter of the song file name
String genreCodeString = cursor.getString(4).substring(0, 1);
if (!genreCodeString.isEmpty()) {
try {
GSC.genre = Short.parseShort(genreCodeString);
} catch (NumberFormatException ex) {
Random r = new Random();
GSC.genre = (short) r.nextInt(4);
} finally {
songs.add(GSC);
}
}
//}
cursor.moveToNext();
}
}
} catch (Exception ex) {
} finally {
if (cursor != null) {
cursor.close();
}
}
return songs;
}
I'm really learning to program for Android, and modify your code for what I needed , but I have trouble understanding when you assign cursor
cursor = _context.getContentResolver () query ( uri , projection , selection , null, sortOrder ) . ;
Part of _context not understand you kindly explain it please.
If your class extends activity you can use this for _context. If not, you need to pass the context from your activity. The first case mentioned would look like this:
// query the db
cursor = this.getContentResolver().query(uri, projection, selection, null, sortOrder);
__
What is Context in Android?
I'm using "Calls.CONTENT_URI" content provider. I already retrived column names, but now i would like to get let's say, ALL names from column name "name" in this content provider.
I have code below:
uri = Calls.CONTENT_URI;
String[] projection = {"name"};
String selection = null;
String[] selectionArgs = null;
String sort = null;
resolver = getContentResolver();
cursor = resolver.query(uri, projection, selection, selectionArgs, sort);
Log.i("TUTORIAL", "counts :"+cursor.getCount());
String s;
cursor.moveToFirst();
for(int x=0; x<cursor.getCount(); x++){
s = cursor.getString(x);
Log.i("TUTORIAL", ""+s);
//cursor.moveToNext();
}
But this retrives only one name. I would like to have list of all names saved in my phone like:
John
Peter
Mark
Suzy
.
.
X
But now i got just one name like:
Peter.
Hope i've been clear enough.
What's the problem? Thanks for help in advance.
I think this would help you
ArrayList<String> nameList = new ArrayList<String>();
String[] projection = {"name"};
String selection = null;
String[] selectionArgs = null;
String sort = null;
resolver = getContentResolver();
cursor = resolver.query(uri, projection, selection, selectionArgs, sort);
Log.i("TUTORIAL", "counts :"+cursor.getCount());
String s;
if(cursor.moveToFirst()) {
do {
nameList.add(cursor.getString(0));
//your code
//s = cursor.getString(x);
Log.i("TUTORIAL", ""+cursor.getString(0));
}while(cursor.moveToNext());
}
you can try this one , it's working for me :
public void readContacts() {
Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Get contact id (id)
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
// Get contact name (displayName)
String displayName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
}
}
cur.close();
}
This is the code.
public class MainActivity extends AppCompatActivity {
SimpleCursorAdapter mAdapter;
MatrixCursor mMatrixCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// The contacts from the contacts content provider is stored in this cursor
mMatrixCursor = new MatrixCursor(new String[] { "_id","name","photo","details"} );
// Adapter to set data in the listview
mAdapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.lv_layout,
null,
new String[] { "name","photo","details"},
new int[] { R.id.tv_name,R.id.iv_photo,R.id.tv_details}, 0);
// Getting reference to listview
ListView lstContacts = (ListView) findViewById(R.id.lst_contacts);
// Setting the adapter to listview
lstContacts.setAdapter(mAdapter);
// Creating an AsyncTask object to retrieve and load listview with contacts
ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();
// Starting the AsyncTask process to retrieve and load listview with contacts
listViewContactsLoader.execute();
}
/** An AsyncTask class to retrieve and load listview with contacts */
private class ListViewContactsLoader extends AsyncTask<Void, Void, Cursor> {
#Override
protected Cursor doInBackground(Void... params) {
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
// Querying the table ContactsContract.Contacts to retrieve all the contacts
Cursor contactsCursor = getContentResolver().query(contactsUri, null, null, null,ContactsContract.Contacts.DISPLAY_NAME + " ASC ");
if(contactsCursor.moveToFirst()){
do{
long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID"));
Uri dataUri = ContactsContract.Data.CONTENT_URI;
// Querying the table ContactsContract.Data to retrieve individual items like
// home phone, mobile phone, work email etc corresponding to each contact
Cursor dataCursor = getContentResolver().query(dataUri, null,
ContactsContract.Data.CONTACT_ID + "=" + contactId,
null, null);
String displayName="";
String nickName="";
String homePhone="";
String mobilePhone="";
String workPhone="";
//String photoPath="" + R.drawable.blank;
byte[] photoByte=null;
String homeEmail="";
String workEmail="";
String companyName="";
String title="";
if(dataCursor.moveToFirst()){
// Getting Display Name
displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));
do{
// Getting NickName
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE))
nickName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
// Getting Phone numbers
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME :
homePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE :
mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK :
workPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
}
}
// Getting EMails
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE ) ) {
switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
case ContactsContract.CommonDataKinds.Email.TYPE_HOME :
homeEmail = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Email.TYPE_WORK :
workEmail = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
}
}
// Getting Organization details
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)){
companyName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
title = dataCursor.getString(dataCursor.getColumnIndex("data4"));
}
// Getting Photo
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)){
photoByte = dataCursor.getBlob(dataCursor.getColumnIndex("data15"));
if(photoByte != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the contact image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+contactId+".png");
// The FileOutputStream to the temporary file
try {
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Writing the bitmap to the temporary file as png file
bitmap.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
} catch (Exception e) {
e.printStackTrace();
}
// photoPath = tmpFile.getPath();
}
}
}while(dataCursor.moveToNext());
String details = "";
// Concatenating various information to single string
if(homePhone != null && !homePhone.equals("") )
details = "HomePhone : " + homePhone + "\n";
if(mobilePhone != null && !mobilePhone.equals("") )
details += "MobilePhone : " + mobilePhone + "\n";
if(workPhone != null && !workPhone.equals("") )
details += "WorkPhone : " + workPhone + "\n";
if(nickName != null && !nickName.equals("") )
details += "NickName : " + nickName + "\n";
if(homeEmail != null && !homeEmail.equals("") )
details += "HomeEmail : " + homeEmail + "\n";
if(workEmail != null && !workEmail.equals("") )
details += "WorkEmail : " + workEmail + "\n";
if(companyName != null && !companyName.equals("") )
details += "CompanyName : " + companyName + "\n";
if(title != null && !title.equals("") )
details += "Title : " + title + "\n";
// Adding id, display name, path to photo and other details to cursor
mMatrixCursor.addRow(new Object[]{ Long.toString(contactId),displayName,null,details});
}
}while(contactsCursor.moveToNext());
}
return mMatrixCursor;
}
#Override
protected void onPostExecute(Cursor result) {
// Setting the cursor containing contacts to listview
mAdapter.swapCursor(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}