List of Mp3 files from a specific folder - Android - android

How i get list of all Mp3 files from a specific folder?
My folder is
FILE_PATH = Environment.getExternalStorageDirectory().getPath() + "/my folder/"
This following code show all mp3 from all Folder .. i want sow mp3 from my folder only
Cursor createCursor(String filter) {
ArrayList<String> args = new ArrayList<String>();
String selection;
if (mShowAll) {
selection = "(_DATA LIKE ?)";
args.add("%");
} else {
selection = "(";
for (String extension : CheapSoundFile.getSupportedExtensions()) {
args.add("%." + extension);
if (selection.length() > 1) {
selection += " OR ";
}
selection += "(_DATA LIKE ?)";
selection = selection + "AND (IS_MUSIC=1)";
}
selection += ")";
selection = "(" + selection + ") AND (_DATA NOT LIKE ?)";
args.add("%espeak-data/scratch%");
}
if (filter != null && filter.length() > 0) {
filter = "%" + filter + "%";
selection =
"(" + selection + " AND " +
"((TITLE LIKE ?) OR (ARTIST LIKE ?) OR (ALBUM LIKE ?)))";
args.add(filter);
args.add(filter);
args.add(filter);
}

Use the below code to get the list of mp3 files from the desired folder :-
private ArrayList<String> listmp3 = new ArrayList<String>();
String[] extensions = { "mp3" };
private void loadmp3(String YourFolderPath) {
File file = new File(YourFolderPath);
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null && files.length > 0) {
for (File f : files) {
if (f.isDirectory()) {
loadmp3(f.getAbsolutePath());
} else {
for (int i = 0; i < extensions.length; i++) {
if (f.getAbsolutePath().endsWith(extensions[i])) {
listmp3.add(f.getAbsolutePath());
}
}
}
}
}
}
}

This one is Working fine
Cursor createCursor(String filter) {
ArrayList<String> args = new ArrayList<String>();
String path = Environment.getExternalStorageDirectory().getPath();
String selection = MediaStore.Audio.Media.IS_MUSIC + " !=" + 0
+ " AND " + MediaStore.Audio.Media.DATA + " LIKE '" + path
+ "/Fast Mp3 Downloader/%'";
if (filter != null && filter.length() > 0) {
filter = "%" + filter + "%";
selection =
"(" + selection + " AND " +
"((TITLE LIKE ?) OR (ARTIST LIKE ?) OR (ALBUM LIKE ?)))";
args.add(filter);
args.add(filter);
args.add(filter);
}
String[] argsArray = args.toArray(new String[args.size()]);
getExternalAudioCursor(selection, argsArray);
getInternalAudioCursor(selection, argsArray);
Cursor c = new MergeCursor(new Cursor[] {
getExternalAudioCursor(selection, argsArray),
getInternalAudioCursor(selection, argsArray)});
startManagingCursor(c);
return c;
}

Related

How to query specific hidden folder for images in android

I need to query a specific hidden folder created by my application and need to fetch all the images saved in that hidden folder. I am able to query that very same folder if its not hidden but when I make the folder hidden, the cursor counts returns me 0 even though images are well kept inside the folder.
public static List<MediaData> getHiddenFolderData(Context context) {
Cursor imagecursor = null;
List<MediaData> gallerydata = new ArrayList<MediaData>();
try {
final String orderBy = Images.Media._ID + " DESC";
imagecursor = context.getContentResolver()
.query(Images.Media.EXTERNAL_CONTENT_URI,
projectionImage,
Images.Media.BUCKET_DISPLAY_NAME + "='"
+ ".HiddenFolder" + "'", null,
orderBy);
System.out.println("1026 check log 1");
if (imagecursor != null) {
System.out.println("1026 check log 2");
imagecursor.moveToFirst();
int count = imagecursor.getCount();
System.out.println("1026 check log 3 count"+" "+count);
for (int i = 0; i < count; i++) {
MediaData galData = new MediaData();
galData.setKey_id(i);
galData.setId(imagecursor.getString(0));
galData.setName(imagecursor.getString(1));
galData.setPath(imagecursor.getString(2));
galData.setDate(imagecursor.getString(3));
gallerydata.add(galData);
imagecursor.moveToNext();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (imagecursor != null) {
imagecursor.close();
}
}
return gallerydata;
}
Another approach
private void getHiddenFolderData() {
String path = Environment.getExternalStorageDirectory().toString() + "/Pictures/.HiddenFolder";
System.out.println("here is path" + " " + "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
System.out.println("here is size" + " " + files.length);
for (int i = 0; i < files.length; i++) {
System.out.println("here get file prop"+" "+files[i].getName()+" "+files[i].getPath());
}
}

How to remove duplicate contact number from all type of contact without database?

How to remove duplicate number entry in Android when fetching contact number from contact book?
For example:
In contact book for
one name multiple contact.. ex-type-home-9428060123,
type-work-9428060123, I want to fetch unique contact number from all
type,android problematically? I use below code for fetching
information:
private void getContactsDetails() {
showLoader();
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
Cursor phones = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null/*selection + " AND " +
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1"*/, null, "UPPER("
+ ContactsContract.Contacts.DISPLAY_NAME + ") ASC");
ContactString = new ArrayList<>();
if (phones != null) {
if (phones.getCount() > 0) {
tvNoContact.setVisibility(View.GONE);
while (phones.moveToNext()) {
String Name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
HashSet<String> mobileNoSet = new HashSet<String>();
if (!mobileNoSet.contains(number)){
String s = number.replaceAll("\\W", "");
String lastTenCharContact = null;
if (s != null && s.length() > 10) {
lastTenCharContact = s.substring(s.length() - 10);
} else {
lastTenCharContact = s;
}
// String substring = s.substring(Math.max(s.length() - 10, 0));
Log.d(TAG, "getContactsDetails: " + lastTenCharContact);
String image_uri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
ContactString.add(lastTenCharContact);
DeviceContact contactModel = new DeviceContact(Name.toUpperCase(), lastTenCharContact, image_uri);
contactModelsList.add(contactModel);
mobileNoSet.add(number);
Log.d(TAG, "Name : " + Name + ", Number : " + number + ", Photo : " + image_uri);}
}
hideLoader();
AllContactsyncapiCall();
} else {
tvNoContact.setVisibility(View.VISIBLE);
}
} }
for remove duplicate Number just make hashset before your loop:
HashSet<String> mobileNoSet = new HashSet<String>();
Now when you put contact in model use below code:
if (!mobileNoSet.contains(number)){
String s = number.replaceAll("\\W", "");
String lastTenCharContact = null;
if (s != null && s.length() > 10) {
lastTenCharContact = s.substring(s.length() - 10);
} else {
lastTenCharContact = s;
}
// String substring = s.substring(Math.max(s.length() - 10, 0));
Log.d(TAG, "getContactsDetails: " + lastTenCharContact);
String image_uri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
ContactString.add(lastTenCharContact);
DeviceContact contactModel = new DeviceContact(Name.toUpperCase(), lastTenCharContact, image_uri);
contactModelsList.add(contactModel);
mobileNoSet.add(number);
}
This is new code in which i m getting duplicate number :-
private void getContactsDetails() {
// showLoader();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null/*selection + " AND " + ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1"*/, null, "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ") ASC");
ContactString = new ArrayList<>();
nameString = new ArrayList<>();
if (phones != null) {
if (phones.getCount() > 0) {
tvNoContact.setVisibility(View.GONE);
HashSet<String> mobileNoSet = new HashSet<String>();
while (phones.moveToNext()) {
String Name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (!mobileNoSet.contains(number)) {
// String s = number.replaceAll("\\W", "");
String s = number.replaceAll("[^[+]\\d]", "");
String lastTenCharContact = null;
lastTenCharContact = s;
/*if (s != null && s.length() > 10) {
lastTenCharContact = s.substring(s.length() - 10);
} else {
lastTenCharContact = s;
}*/
// String substring = s.substring(Math.max(s.length() - 10, 0));
Log.d(TAG, "getContactsDetails: " + lastTenCharContact);
String image_uri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
ContactString.add(lastTenCharContact);
// nameString.add(Name);
contactModel = new DeviceContact(Name.toUpperCase(), lastTenCharContact, image_uri);
contactModelsList.add(contactModel);
mobileNoSet.add(number);
Log.d(TAG, "Name : " + Name + ", Number : " + number + ", Photo : " + image_uri);
}
}
// hideLoader();
AllContactsyncapiCall();
} else {
tvNoContact.setVisibility(View.VISIBLE);
}
}
}

How to edit existing Contacts in Android?

I am trying to edit existing phone contacts by using application. By using contact name am getting the corresponding contact id.Then am trying to update the existing contacts by using the contact id. But unfortunately it is not updating.
My code is as follows,
String select = "(" + ContactsContract.Contacts.DISPLAY_NAME + " == \"" + edt_nameDetail.getText() + "\" )";
Cursor c = getActivity().getApplicationContext().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select, null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
getActivity().startManagingCursor(c);
if (c.moveToNext()) {
ContactId = c.getString(0);
Log.e("Tag contact id ","edit contact id "+ ContactId);
}
try
{
String name = edt_nameDetail.getText().toString().trim();
String email = edt_contactEmailDetail.getText().toString().trim();
String number = edt_mobileNumberDetail.getText().toString().trim();
ContentResolver contentResolver = getActivity().getContentResolver();
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] emailParams = new String[]{ContactId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE};
String[] nameParams = new String[]{ContactId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
String[] numberParams = new String[]{ContactId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};
ArrayList<android.content.ContentProviderOperation> ops = new ArrayList<android.content.ContentProviderOperation>();
if(!email.equals("") &&!name.equals("")&& !number.equals(""))
{
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,emailParams)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, email)
.build());
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,nameParams)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
.build());
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,numberParams)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number)
.build());
contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
Toast.makeText(getActivity(), "Contact is successfully edited", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getActivity(), "Fail edit", Toast.LENGTH_SHORT).show();
}
If you are searching with email then update your .withSelection as
.withSelection(ContactsContract.CommonDataKinds.Email.ADDRESS + "=? AND " +
Data.MIMETYPE + "='" +
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE + "'",
new String[]{email})
update all your withselection code corresponding to your search type
Note: after this, contact ID will changed.
public static boolean updateContactName(String contactId, String pre, String first, String mid, String last, String suf)
{
try
{
if (pre == null && first == null && mid == null && last == null && suf == null)
return false;
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] nameParams = new String[]{contactId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
ArrayList<android.content.ContentProviderOperation> ops = new ArrayList<>();
android.content.ContentProviderOperation.Builder t ;
android.content.ContentProviderOperation b ;
t = android.content.ContentProviderOperation.newUpdate(Data.CONTENT_URI);
t = t.withSelection(where, nameParams);
if(pre != null)
t = t.withValue(StructuredName.PREFIX, pre.trim());
if(first != null)
t = t.withValue(StructuredName.GIVEN_NAME, first.trim());
if(mid != null)
t = t.withValue(StructuredName.MIDDLE_NAME, mid.trim());
if(last != null)
t = t.withValue(StructuredName.FAMILY_NAME, last.trim());
if(suf != null)
t = t.withValue(StructuredName.SUFFIX, suf.trim());
b = t.build();
ops.add(b);
ContentManager.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
return true;
}
catch (Exception e) {}
return false;
}

How to load the thumbnails for the pictures stored in particular folder (or with IDs)?

I have an activity with a GridView where I want to show thumbnails for images taken with standard camera activity and stored in a particular folder. This activity implements LoaderManager.LoaderCallbacks interface and here's its onCreateLoader() method's code
...
...
private static final String APP_PICTURES_DIRECTORY_NAME = "Pictures to process";
private String[] mProjection = {
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.Thumbnails.DATA,
MediaStore.Images.Thumbnails.IMAGE_ID
};
private SimpleCursorAdapter mCursorAdapter;
...
...
...
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] imagesProjection = {"_id", "_data"};
Cursor imagesCursor;
imagesCursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
imagesProjection,
MediaStore.Images.Media.DATA + " LIKE '%" + APP_PICTURES_DIRECTORY_NAME + "%'",
null,
null
);
String[] imageIds = new String[imagesCursor.getCount()];
int i = 0;
while (imagesCursor.moveToNext()) {
imageIds[i++] = imagesCursor.getString(imagesCursor.getColumnIndex(MediaStore.Images.Media._ID));
}
String[] selectionArgs = {TextUtils.join(",", imageIds)};
return new CursorLoader(
JourneyAlbumActivity.this,
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
mProjection,
MediaStore.Images.Thumbnails.KIND + " = " + MediaStore.Images.Thumbnails.MINI_KIND +
" AND " + MediaStore.Images.Thumbnails.IMAGE_ID + " IN (?)",
selectionArgs,
MediaStore.Images.Thumbnails.IMAGE_ID + " DESC"
);
}
But the result is empty in the result. If I remove this clause
... + " AND " + MediaStore.Images.Thumbnails.IMAGE_ID + " IN (?)"
Everything's ok but in the result I have a grid of thumbnails of all the images taken with camera while I need only those from my specific directory. How do I select thumbnails for images from a particular folder or with particular IDs?
Actually, to make it work you have to insert your parameter directely inside the clause :
return new CursorLoader(
JourneyAlbumActivity.this,
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
mProjection,
MediaStore.Images.Thumbnails.KIND + " = " + MediaStore.Images.Thumbnails.MINI_KIND +
" AND " + MediaStore.Images.Thumbnails.IMAGE_ID + " IN ("+TextUtils.join(",", ids)+")",
selectionArgs,
MediaStore.Images.Thumbnails.IMAGE_ID + " DESC"
);
Best regards,
Maybe you can try something like this:
System.out.println("getFilePaths()");
File fileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator +"folder_name"+ File.separator + AppConstant.PHOTO_ALBUM);
if(!fileDir.exists()){
System.out.println("fileDir does not exist");
try{
fileDir.mkdir();
} catch (Exception e) {
e.printStackTrace();
}
}
else
System.out.println("fileDir DOES exist");
File directory = fileDir;
// check for directory
if (directory.isDirectory()) {
// getting list of file paths
File[] listFiles = directory.listFiles();
// Check for count
if (listFiles.length > 0) {
// loop through all files
for (int i = 0; i < listFiles.length; i++) {
// get file path
String filePath = listFiles[i].getAbsolutePath();
// check for supported file extension
if (IsSupportedFile(filePath)) {
// Add image path to array list
filePaths.add(filePath);
}
}
} else {
// image directory is empty
Toast.makeText(
_context,
AppConstant.PHOTO_ALBUM
+ " is empty. Please load some images in it !",
Toast.LENGTH_LONG).show();
}
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(_context);
alert.setTitle("Error!");
alert.setMessage(AppConstant.PHOTO_ALBUM
+ " directory path is not valid! Please set the image directory name AppConstant.java class");
alert.setPositiveButton("OK", null);
alert.show();
}

Android sqlite select statement does not work well

I've got three table and i want make a query withe sql statement, but it does not work well because it does not give me all the possible results...
The code:
public void setsuchresultat(String pSearchword)
{
String[] table = new String[]{"tbl_A", "tbl_B", "tbl_C"};
String[] column = new String[]{"columnA", "columnB" }; // Type varchar(50) not null
String[] search = new String[]{"%" + pSearchword+ "%", pSearchword+ "%", "%" + pSearchword, pSearchword};
getdata(table,column,search);
}
public void getdata(String[] pTable, String[] pColumn, String[] pSearch)
{
for(String t:pTable)
{
for(String s : pColumn)
{
for(String k : pSearch)
{
Cursor c = this.db.rawQuery("SELECT * FROM " + t + " WHERE " + s + " LIKE '"+ k + "'", null);
if ((c.moveToFirst()) || c.getCount() > 0)
{
while(c.moveToNext())// Suchresultat abspeichern
{
String col1 = c.getString(c.getColumnIndex("columnA"));
String col2 = c.getString(c.getColumnIndex("columnB"));
}
}
}
}
}
}
I think problem is in your loop and if check.
Change
if ((c.moveToFirst()) || c.getCount() > 0)
{
while(c.moveToNext())// Suchresultat abspeichern
{
String col1 = c.getString(c.getColumnIndex("columnA"));
String col2 = c.getString(c.getColumnIndex("columnB"));
}
}
to
if (c.moveToFirst() || c.getCount() > 0) /* OR if (c != null && c.moveToFirst())*/ {
do {
String col1 = c.getString(c.getColumnIndex("columnA"));
String col2 = c.getString(c.getColumnIndex("columnB"));
} while(c.moveToNext());
}

Categories

Resources