I am developing an Android Application to wipe all data from Android including photos, videos, contacts, messages, apps,call logs, application data etc. programmatically. I wish to achieve this with an Android Application only and not through adb.
The approach I am thinking of somehow I manage to Clear data from phone and rewrite the memory with some junk files or binary data 1010 say. (Its just an idea!)
All I have managed to do is delete photos,videos,images,contacts,call logs,messages from Device using Cursor and getContentResolver. But we can recover that using third party Data Recover Softwares.
I have also reset the device using device administrator but the cons of this is the data can be recovered through it.
So, all i need is which approach to follow for hard resetting the device.
I have used below code .
public static void deleteAllContacts(Context activity) {
ContentResolver contentResolver = activity.getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
contentResolver.delete(uri, null, null);
}
}
public static void deleteAllCallLog(Context activity) {
activity.getContentResolver().delete(CallLog.Calls.CONTENT_URI, null, null);
}
/* public static void deleteAllMessages(Context activity) {
ContentResolver localContentResolver = activity.getContentResolver();
Uri localUri = Uri.parse("content://sms");
for (int i = localContentResolver.delete(Telephony.Sms.CONTENT_URI, null, null); i == 1; i = localContentResolver.delete(localUri, null, null)) {
}
}*/
public static void deleteVideoFiles(Activity activity) {
String[] videoProjection = {MediaStore.Video.Media._ID, MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.SIZE};
Cursor videoCursor = activity.managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoProjection, null, null, null);
int count = videoCursor.getCount();
for (int i = 0; i < count; i++) {
int indexID = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
videoCursor.moveToPosition(i);
String path = getVideoFilePath(videoCursor.getString(indexID), activity);
Log.d("Video Path", path);
File file = new File(path);
boolean isDeleted = file.delete();
Log.d("isDELETED", String.valueOf(isDeleted));
}
videoCursor.close();
}
public static void deleteAudioFiles(Activity activity) {
String[] proj = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.SIZE};
Cursor audioCursor = activity.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);
if (audioCursor != null) {
if (audioCursor.moveToFirst()) {
do {
int indexId = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
String path = getAudioFilePath(audioCursor.getString(indexId), activity);
Log.d("Audio Path", path);
File file = new File(path);
boolean isDeleted = file.delete();
Log.d("isDELETED", String.valueOf(isDeleted));
} while (audioCursor.moveToNext());
}
}
if (audioCursor != null) audioCursor.close();
}
public static void deleteImageFiles(Activity activity) {
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.ImageColumns.DATA};
Cursor c = null;
SortedSet<String> dirList = new TreeSet<String>();
String[] directories = null;
if (u != null) {
c = activity.managedQuery(u, projection, null, null, null);
}
if ((c != null) && (c.moveToFirst())) {
do {
String tempDir = c.getString(0);
tempDir = tempDir.substring(0, tempDir.lastIndexOf("/"));
try {
dirList.add(tempDir);
} catch (Exception e) {
}
}
while (c.moveToNext());
directories = new String[dirList.size()];
dirList.toArray(directories);
}
for (int i = 0; i < dirList.size(); i++) {
File imageDir = new File(directories[i]);
File[] imageList = imageDir.listFiles();
if (imageList == null)
continue;
for (File imagePath : imageList) {
try {
if (imagePath.isDirectory()) {
imageList = imagePath.listFiles();
}
if (imagePath.getName().contains(".jpg") || imagePath.getName().contains(".JPG")
|| imagePath.getName().contains(".jpeg") || imagePath.getName().contains(".JPEG")
|| imagePath.getName().contains(".png") || imagePath.getName().contains(".PNG")
|| imagePath.getName().contains(".gif") || imagePath.getName().contains(".GIF")
|| imagePath.getName().contains(".bmp") || imagePath.getName().contains(".BMP")
) {
Log.d("Absolute Path", imagePath.getAbsolutePath());
File file = new File(imagePath.getAbsolutePath());
boolean isDeleted = file.delete();
Log.d("iSDELETED", String.valueOf(isDeleted));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static String getAudioFilePath(String contentId, Activity activity) {
Uri theMediaUri = Uri.withAppendedPath(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, contentId);
String[] projection = {MediaStore.Audio.Media.DATA};
Cursor mCur = activity.getContentResolver().query(theMediaUri, projection, null, null, null);
int column_index = mCur.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
mCur.moveToFirst();
return mCur.getString(column_index);
}
public static String getVideoFilePath(String contentId, Activity activity) {
Uri theMediaUri = Uri.withAppendedPath(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentId);
String[] projection = {MediaStore.Video.Media.DATA};
Cursor mCur = activity.getContentResolver().query(theMediaUri, projection, null, null, null);
int column_index = mCur.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
mCur.moveToFirst();
return mCur.getString(column_index);
}
public static void deleteSMS(Context context) {
/* try {
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = context.getContentResolver().query(uriSms, new String[]{"_id", "body"}, null, null, null);
if (c != null && c.moveToFirst()) {
do {
long id = c.getLong(0);
Log.d("Body : ", c.getString(1));
context.getContentResolver().delete(
Uri.parse("content://sms/" + id), null, null);
Log.e("Message:", "Message is Deleted successfully");
} while (c.moveToNext());
}
if (c != null) {
c.close();
}
} catch (Exception e) {
Log.e("Exception", e.toString());
}*/
Cursor c =context.getContentResolver().query(Uri.parse("content://sms/"), new String[]{"_id", "body"}, null, null,null);
try {
while (c.moveToNext()) {
int id = c.getInt(0);
int isDeleted = context.getContentResolver().delete(Uri.parse("content://sms/" + id), null, null);
Log.d("IS DELETED" , String.valueOf(isDeleted));
}
}catch(Exception e){
Log.e("Delete Sms","Error deleting sms",e);
}finally {
c.close();
}
}
Related
The problem which i'm facing is I am not able to display the fetched value, as I have used a list view to display the values are not reaching it. This is my code snippet which fetches multiple contacts from phone book. Hope any1 help me solve it.
private void chooseContact() {
Intent phonebookIntent = new Intent("intent.action.INTERACTION_TOPMENU");
phonebookIntent.putExtra("additional", "phone-multi");
phonebookIntent.putExtra("maxRecipientCount", MAX_PICK_CONTACT);
phonebookIntent.putExtra("FromMMS", true);
startActivityForResult(phonebookIntent, REQUEST_CODE_PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == RESULT_PICK_CONTACT) {
Uri contractData = data.getData();
ContactRetriever cr = new ContactRetriever(getApplicationContext(), contractData);
Person p = cr.getPerson();
if (p == null)
Toast.makeText(this, "Phone number not found!", Toast.LENGTH_SHORT).show();
else {
PersonManager.savePerson(p, getApplicationContext());
listContacts.setAdapter(new PersonAdapter(this, PersonManager.getSavedPersons(this)));
}
}
}
}}
And the Uri value is called and used in next below class
public class ContactRetriever {
private final String TAG = "ContactRetriever";
private ContentResolver cr;
private Context context;
private Uri contractData;
private String id;
public ContactRetriever(Context context,Uri contractData ) {
this.context = context;
this.cr = context.getContentResolver();
this.contractData = contractData;
}
public Person getPerson() {
String name = getName();
String num = getNumber();
if (name != null && num != null)
return new Person(getNumber(), getName());
else return null;
}
private String getNumber() {
String ret = null;
Cursor cId = cr.query(contractData, new String[]{ContactsContract.Contacts._ID}, null, null, null);
if (cId.moveToFirst()){
id = cId.getString(cId.getColumnIndex(ContactsContract.Contacts._ID));
Log.i(TAG + " IDs: ", id);
}
cId.close();
Cursor cNum = cr.query(contractData, null, null, null, null);
if (cNum.moveToNext()){
ret = cNum.getString(cNum.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i(ret, TAG + " NUMBERS: ");
}
return ret;
}
private String getName() {
String ret = null;
Cursor c = cr.query(contractData, null, null, null, null);
if (c.moveToFirst())
ret = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
c.close();
Log.i(TAG + "NAMES: ", ret);
return ret;
}
}
Here is my working code for mine
//enter code here
private void getAllContacts() {
List<InviteContactInfo> inviteContactList = new ArrayList();
InviteContactInfo inviteContactInfo;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
inviteContactInfo = new InviteContactInfo();
inviteContactInfo.setContactName(name);
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id},
null);
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
inviteContactInfo.setContactNumber(phoneNumber);
}
phoneCursor.close();
Cursor emailCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCursor.moveToNext()) {
String emailId = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
Bitmap photo =null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
inviteContactInfo.setContactImage(photo);
}
else
{
photo =BitmapFactory.decodeResource(getResources(), R.drawable.profilepic);;
inviteContactInfo.setContactImage(photo);
}
assert inputStream != null;
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
inviteContactList.add(inviteContactInfo);
}
}
InviteContactAdapter contactAdapter = new InviteContactAdapter(getApplicationContext(), inviteContactList);
recList.setLayoutManager(new LinearLayoutManager(this));
recList.setAdapter(contactAdapter);
}
}
I want to get all videos path in android (Internal and External storage both), I have tried use:
List<String> paths = new ArrayList<String>();
File directory = new File("/system" OR "/mnt/sdcard");
File[] files = directory.listFiles();
for (int i = 0; i < files.length; ++i) {
if(files[i].getAbsolutePath().contains(".mp4")) {
paths.add(files[i].getAbsolutePath());
}
}
but I can not get all of video lists from my device.
Here is your solution must try if you want to really a actual result.
public ArrayList<String> getAllMedia() {
HashSet<String> videoItemHashSet = new HashSet<>();
String[] projection = { MediaStore.Video.VideoColumns.DATA ,MediaStore.Video.Media.DISPLAY_NAME};
Cursor cursor = getContext().getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
try {
cursor.moveToFirst();
do{
videoItemHashSet.add((cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA))));
}while(cursor.moveToNext());
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
ArrayList<String> downloadedList = new ArrayList<>(videoItemHashSet);
return downloadedList;
}
You need to make your search recursive. Something like:
void findVideos(File dir, ArrayList<String> list){
for (File file : dir.listFiles()) {
if (file.isDirectory()) findVideos(file, list);
else if(file.getAbsolutePath().contains(".mp4")) list.add(file.getAbsolutePath());
}
}
List<VideoClass> videoItems = new ArrayList<VideoClass>();
ContentResolver contentResolver = getContentResolver();
Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = contentResolver.query(uri, null, null, null, null);
//looping through all rows and adding to list
if (cursor != null && cursor.moveToFirst()) {
do {
String title = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE));
Uri contentUri = ContentUris.withAppendedId(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID)));
Bitmap vimage =
null;
try {
vimage = getApplicationContext().getContentResolver().loadThumbnail(
contentUri, new Size(640, 480), null);
} catch (IOException e) {
e.printStackTrace();
}
VideoClass videoModel = new VideoClass();
videoModel.setTitle(title);
videoModel.setMain_video(String.valueOf(contentUri));
videoModel.setImage(vimage);
videoItems.add(videoModel);
} while (cursor.moveToNext());
}
return videoItems;
String title = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE));
Uri contentUri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID)));
Bitmap vimage = null;
try {
vimage = getApplicationContext().getContentResolver().loadThumbnail(contentUri, new Size(640, 480), null);
} catch (IOException e) {
e.printStackTrace();
}
I am trying to get all the file name having audio files in it I have used Mediastore to get the mediastore audio,album,playlist and audio DATA also but how I can get the file or folder titles which contains the audio file .Here is the code that I have tried but it is not correct as I am not able to set the External_Content_uri.
This is the code I have tried.
private void External() {
try {
String[] proj = {MediaStore.Files.FileColumns.TITLE,
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.PARENT,
MediaStore.Files.FileColumns.DATA
};// Can include more data for more details and check it.
String selection =MediaStore.Files.FileColumns.MEDIA_TYPE+"=?";
String[] selectionArgs = {"MediaStore.Files.FileColumns.MEDIA_TYPE_AUDIO"};
String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
Cursor audioCursor = getContentResolver().query(MediaStore.Files.getContentUri("\"external\""), proj, selection, selectionArgs, sortOrder);
if (audioCursor != null) {
if (audioCursor.moveToFirst()) {
do {
int filetitle = audioCursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.TITLE);
int file_id = audioCursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID);
int fileparent = audioCursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.PARENT);
int filedata = audioCursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA);
Mediafileinfo info = new Mediafileinfo();
info.setData(new File(new File(audioCursor.getString(filedata)).getParent()).getName());
info.setTitle(audioCursor.getString(filetitle));
info.set_id(audioCursor.getString(file_id));
info.setParent(audioCursor.getString(fileparent));
// info.setData(audioCursor.getString(filedata));
audioList.add(info);
} while (audioCursor.moveToNext());
}
}
assert audioCursor != null;
audioCursor.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I tried this and this example but I am not able to get the solution.
Writing a fresh answer, since all you want is the folder names of the audio files.
So the best thing to use here is MediaStore.Audio.Media instead of using MediaStore.File. Get the folder names using the below on the audio file path.
new File(new File(audioCursor.getString(filedata)).getParent()).getName()
private void External() {
try {
Uri externalUri= MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
projection=new String[]{MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,;
String selection =null;
String[] selectionArgs = null;
String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
Cursor audioCursor = getContentResolver().query(externalUri, proj, selection, selectionArgs, sortOrder);
if (audioCursor != null) {
if (audioCursor.moveToFirst()) {
do {
int filetitle = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
int file_id = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
int filePath = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
Mediafileinfo info = new Mediafileinfo();
info.setData(new File(new File(audioCursor.getString(filedata)).getParent()).getName());
info.setTitle(audioCursor.getString(filetitle));
info.set_id(audioCursor.getString(file_id));
audioList.add(info);
} while (audioCursor.moveToNext());
}
}
assert audioCursor != null;
audioCursor.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Hi query media file like audio,images and video using Android Media Store and Android Content Resolver, check this tutorial
http://www.androiddevelopersolutions.com/2015/12/android-media-store-tutorial-list-all.html
For Listing All images:
private void parseAllImages() {
try {
String[] projection = {MediaStore.Images.Media.DATA};
cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
null);
int size = cursor.getCount();
/******* If size is 0, there are no images on the SD Card. *****/
if (size == 0) {
} else {
int thumbID = 0;
while (cursor.moveToNext()) {
int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
/**************** Captured image details ************/
/***** Used to show image on view in LoadImagesFromSDCard class ******/
String path = cursor.getString(file_ColumnIndex);
String fileName = path.substring(path.lastIndexOf("/") + 1, path.length());
MediaFileInfo mediaFileInfo = new MediaFileInfo();
mediaFileInfo.setFilePath(path);
mediaFileInfo.setFileName(fileName);
mediaFileInfo.setFileType(type);
mediaList.add(mediaFileInfo);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
For Listing all Video(.mp4)
private void parseAllVideo() {
try {
String name = null;
String[] thumbColumns = {MediaStore.Video.Thumbnails.DATA,
MediaStore.Video.Thumbnails.VIDEO_ID};
int video_column_index;
String[] proj = {MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.SIZE};
Cursor videocursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
proj, null, null, null);
int count = videocursor.getCount();
Log.d("No of video", "" + count);
for (int i = 0; i < count; i++) {
MediaFileInfo mediaFileInfo = new MediaFileInfo();
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
videocursor.moveToPosition(i);
name = videocursor.getString(video_column_index);
mediaFileInfo.setFileName(name);
int column_index = videocursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
videocursor.moveToPosition(i);
String filepath = videocursor.getString(column_index);
mediaFileInfo.setFilePath(filepath);
mediaFileInfo.setFileType(type);
mediaList.add(mediaFileInfo);
// id += " Size(KB):" +
// videocursor.getString(video_column_index);
}
videocursor.close();
} catch (Exception e) {
e.printStackTrace();
}
}
For Listing All Audio
private void parseAllAudio() {
try {
String TAG = "Audio";
Cursor cur = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
null);
if (cur == null) {
// Query failed...
Log.e(TAG, "Failed to retrieve music: cursor is null :-(");
}
else if (!cur.moveToFirst()) {
// Nothing to query. There is no music on the device. How boring.
Log.e(TAG, "Failed to move cursor to first row (no query results).");
}else {
Log.i(TAG, "Listing...");
// retrieve the indices of the columns where the ID, title, etc. of the song are
// add each song to mItems
do {
int artistColumn = cur.getColumnIndex(MediaStore.Audio.Media.ARTIST);
int titleColumn = cur.getColumnIndex(MediaStore.Audio.Media.TITLE);
int albumColumn = cur.getColumnIndex(MediaStore.Audio.Media.ALBUM);
int durationColumn = cur.getColumnIndex(MediaStore.Audio.Media.DURATION);
int idColumn = cur.getColumnIndex(MediaStore.Audio.Media._ID);
int filePathIndex = cur.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
Log.i(TAG, "Title column index: " + String.valueOf(titleColumn));
Log.i(TAG, "ID column index: " + String.valueOf(titleColumn));
Log.i("Final ", "ID: " + cur.getString(idColumn) + " Title: " + cur.getString(titleColumn) + "Path: " + cur.getString(filePathIndex));
MediaFileInfo audio = new MediaFileInfo();
audio.setFileName(cur.getString(titleColumn));
audio.setFilePath(cur.getString(filePathIndex));
audio.setFileType(type);
mediaList.add(audio);
} while (cur.moveToNext());
}
} catch (Exception e) {
e.printStackTrace();
}
}
I am new to android programming . I am trying to fetch all photos (or Image's path) reside in android device Internal Storage. I have written the function like this--
public static ArrayList<String> getImagesPath(Activity activity) {
Uri uri;
ArrayList<String> listOfAllImages = new ArrayList<String>();
Cursor cursor;
int column_index_data;
String PathOfImage = null;
uri = android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA};
cursor = activity.getContentResolver().query(uri, projection, null, null, null);
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
while (cursor.moveToNext()) {
PathOfImage = cursor.getString(column_index_data);
listOfAllImages.add(PathOfImage);
}
return listOfAllImages;
}
Try this, hope it will work for you
public ArrayList<String> getFilePaths()
{
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.ImageColumns.DATA};
Cursor c = null;
SortedSet<String> dirList = new TreeSet<String>();
ArrayList<String> resultIAV = new ArrayList<String>();
String[] directories = null;
if (u != null)
{
c = managedQuery(u, projection, null, null, null);
}
if ((c != null) && (c.moveToFirst()))
{
do
{
String tempDir = c.getString(0);
tempDir = tempDir.substring(0, tempDir.lastIndexOf("/"));
try{
dirList.add(tempDir);
}
catch(Exception e)
{
}
}
while (c.moveToNext());
directories = new String[dirList.size()];
dirList.toArray(directories);
}
for(int i=0;i<dirList.size();i++)
{
File imageDir = new File(directories[i]);
File[] imageList = imageDir.listFiles();
if(imageList == null)
continue;
for (File imagePath : imageList) {
try {
if(imagePath.isDirectory())
{
imageList = imagePath.listFiles();
}
if ( imagePath.getName().contains(".jpg")|| imagePath.getName().contains(".JPG")
|| imagePath.getName().contains(".jpeg")|| imagePath.getName().contains(".JPEG")
|| imagePath.getName().contains(".png") || imagePath.getName().contains(".PNG")
)
{
String path= imagePath.getAbsolutePath();
resultIAV.add(path);
}
}
// }
catch (Exception e) {
e.printStackTrace();
FirebaseCrash.report(e);
}
}
}
return resultIAV;
}
You can add any extension to get the files
It returns null, because cursor == null or cursor.getCount() == 0. Which means you don't have photos in your internal storage.
PS: Cursor should be freed after use.
I am currently working on an Android project where I am attempting to lookup a contact phone number in the device and retrieve the contact information such as contact name and contacts image. Getting the contract name is working fine, however, a null pointer is being thrown when trying to get the photo uri.
Below is the code I am using:
public ContactInformation getContactInfoFromPhoneNumber(String number)
{
ContactInformation contactInformation = new ContactInformation();
if (number == null)
{
return null;
}
number = number.replace(" ", "");
if (number.startsWith("+"))
{
number = number.substring(3);
}
ContentResolver contentResolver = context.getContentResolver();
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[] {ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.DISPLAY_NAME};
String selection = "REPLACE (" + ContactsContract.CommonDataKinds.Phone.NUMBER + ", \" \" , \"\" ) LIKE ?";
String[] selectionArgs = { "%" + number };
Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);
if (cursor.moveToFirst())
{
contactInformation.contactName = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME));
contactInformation.photoUri = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
cursor.close();
return contactInformation;
}
else
{
cursor.close();
return null;
}
}
Update
Below is my updated code based on Itzik Samara's answer.
Below is how I am doing my contact lookup:
public ContactInformation getContactInfoFromPhoneNumber(String number)
{
ContactInformation contactInformation = new ContactInformation();
if (number == null)
{
return null;
}
number = number.replace(" ", "");
if (number.startsWith("+"))
{
number = number.substring(3);
}
ContentResolver contentResolver = context.getContentResolver();
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[] {ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.DISPLAY_NAME};
String selection = "REPLACE (" + ContactsContract.CommonDataKinds.Phone.NUMBER + ", \" \" , \"\" ) LIKE ?";
String[] selectionArgs = { "%" + number };
Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);
if (cursor.moveToFirst())
{
contactInformation.contactName = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME));
contactInformation.photoBase64String = getContactPhoto(cursor.getInt(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID)));
cursor.close();
return contactInformation;
}
else
{
cursor.close();
return null;
}
}
Below is my getContactPhoto function:
private String getContactPhoto(int contactID)
{
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactID);
Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = context.getContentResolver().query(photoUri, new String[]{ContactsContract.Contacts.Photo.PHOTO},
null, null, null);
if (cursor == null)
{
return null;
}
if (cursor.getCount() > 0)
{
while (cursor.moveToNext()) {
byte[] data = cursor.getBlob(0);
String base64String = Base64.encodeToString(data, Base64.DEFAULT);
cursor.close();
return base64String;
}
}
return null;
}
It's failing on the if statement and jumping out of the if straight to return null as if there is nothing in the cursor.
this function works for me :
private byte[] getContactPhoto(Context context,long contact_id) {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contact_id);
Uri photoUri = Uri.withAppendedPath(contactUri,ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = context.getContentResolver().query(photoUri, new String[]{ContactsContract.Contacts.Photo.PHOTO}, null, null, null);
if(cursor == null)
return null;
try {
if(cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
cursor.close();
if (data != null)
return data;
}
}
}
finally {
cursor.close();
}
return null;
}
private void getContacts(Context context) {
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
try {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
long contact_id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Contact friend = new Contact();
String name= cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String email = getContactEmail(context, contact_id);
if(!name.contains("#") && !email.matches("")) {
friend.setName(name);
friend.setEmail(email);
friend.setImage(getContactPhoto(context, contact_id));
friend.setPhone(getContactMobilePhoneNumber(context, contact_id));
mContacts.add(friend);
}
}
}
}
finally {
cursor.close();
}
}