Find all mp3 files in storage in android - java

Im trying to find all mp3 files but a have no idea and I found this code, the only problem is the getActivity() wasn't declared, I don't how know to fix, please help me. If has the better way of to do this, I accept sugestion.
here is my class:
public class SongsManager {
private ArrayList<Song> songsList;
public void getMp3Songs() {
Uri allSongsUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor = getActivity().getContentResolver().query(allSongsUri, null, null, null, selection);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Song song = new Song(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
songsList.add(song);
// album_name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
// int album_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
// int artist_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
} while (cursor.moveToNext());
}
cursor.close();
}
}
}

Set parameter for Method (getMp3Songs) as Context:
public class SongsManager {
private ArrayList<Song> songsList;
public void getMp3Songs(Context ctx) {
Uri allSongsUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor = ctx.getContentResolver().query(allSongsUri, null, null, null, selection);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Song song = new Song(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
songsList.add(song);
// album_name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
// int album_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
// int artist_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
} while (cursor.moveToNext());
}
cursor.close();
}
}
}

create Constructor and put there Context. And then call context instead of getActivity();
public class SongsManager {
private Context context;
public SongsManager(Context context){
this.context = context;
}
}

Related

How to obtain Genres and Display them & songs inside them using recyclerView android?

I want to obtain a genre list using a recycler view and display them in a view pager ass grids. I have done this to retrieve albums but am confused about how to get genre from a track.
My album retrieval code:-
AlbumRetriever
public class AlbumLoader {
public static Album getAlbum(Cursor cursor) {
Album album = new Album();
if (cursor != null) {
if (cursor.moveToFirst())
album = new Album(cursor.getLong(0), cursor.getString(1), cursor.getString(2), cursor.getLong(3), cursor.getInt(4), cursor.getInt(5));
}
if (cursor != null)
cursor.close();
return album;
}
public static List<Album> getAlbumsForCursor(Cursor cursor) {
ArrayList arrayList = new ArrayList();
if ((cursor != null) && (cursor.moveToFirst()))
do {
arrayList.add(new Album(cursor.getLong(0),
cursor.getString(1),
cursor.getString(2),
cursor.getLong(3),
cursor.getInt(4),
cursor.getInt(5)));
}
while (cursor.moveToNext());
if (cursor != null)
cursor.close();
return arrayList;
}
public static List<Album> getAllAlbums(Context context) {
return getAlbumsForCursor(makeAlbumCursor(context, null, null));
}
public static Album getAlbum(Context context, long id) {
return getAlbum(makeAlbumCursor(context, "_id=?", new String[]{String.valueOf(id)}));
}
public static List<Album> getAlbums(Context context, String paramString) {
return getAlbumsForCursor(makeAlbumCursor(context,
"album LIKE ?",
new String[]{"%" + paramString + "%"}));
}
public static Cursor makeAlbumCursor(Context context, String selection, String[] paramArrayOfString) {
final String albumSortOrder = musixone.com.musixplayer.Utils
.PreferencesUtility.getInstance(context).getAlbumSortOrder();
Cursor cursor = context.getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{"_id", "album", "artist", "artist_id", "numsongs", "minyear"},
selection, paramArrayOfString, albumSortOrder);
return cursor;
}
}
I have made an album class object too. How to go about retrieving the genres?

Android Display Songs By Playlist

I'm trying to display a list of songs from a playlist. I was able to get a list of songs, however when I play it, it doesn't work.
It seems it is not getting the right the MediaStore.Audio.Media._ID.
Here's the code on how I display the list:
private ArrayList<Song> listAllSongsByPlaylistId(long playlistId){
Cursor cursor;
ArrayList<Song> songList = new ArrayList<Song>();
ContentResolver musicResolver = getActivity().getContentResolver();
Uri allSongsUri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
if (isSdPresent()) {
cursor = musicResolver.query(allSongsUri, null, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
//Log.d("KO Genres:",cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Genres.NAME))+":"+genres);
Song song = new Song();
String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
String[] res = data.split("\\.");
song.setSongName(res[0]);
song.setSongFullPath(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
song.setSongId(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID)));
song.setSongAlbumName(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM)));
song.setArtist(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
song.setSongUri(ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID))));
String duration = String.valueOf(getDuration(cursor.getLong(cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.DURATION))));
song.setSongDuration(duration);
songList.add(song);
} while (cursor.moveToNext());
return songList;
}
cursor.close();
}
}
return null;
}
I have another method which works fine and play song correctly, it display all songs.
I checked the MediaStore.Audio.Media._ID, the same songs from both method has a different MediaStore.Audio.Media._ID, and that seems to be causing the problem.
private ArrayList<Song> listAllSongs() { //Fetch path to all the files from internal & external storage n store it in songList
Cursor cursor;
ArrayList<Song> songList = new ArrayList<Song>();
ContentResolver musicResolver = getActivity().getContentResolver();
Uri allSongsUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
if (isSdPresent()) {
cursor = musicResolver.query(allSongsUri, null, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Song song = new Song();
String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
String[] res = data.split("\\.");
song.setSongName(res[0]);
song.setSongFullPath(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
song.setSongId(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID)));
song.setSongAlbumName(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM)));
song.setArtist(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
song.setSongUri(ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID))));
String duration = String.valueOf(getDuration(cursor.getLong(cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.DURATION))));
song.setSongDuration(duration);
songList.add(song);
} while (cursor.moveToNext());
return songList;
}
cursor.close();
}
}
return null;
}

make the item Blur and unclickable in List view android

i am having a list view. like this. I want to make the second item in the list view to be burled or color changed when loading the activity.
here is my code
Activity on create method
list_all_visits(schedule_id);
List Adapter
private void list_all_visits(int schedule_id){
mvisitsDAO =new VisitsDAO(getApplicationContext());
ListVisits = mvisitsDAO.getAllvisitsforSchedule(schedule_id);
ArrayAdapter<Visits> adapter = new ArrayAdapter<Visits>(this, R.layout.schedule_layout_list, R.id.tv_text1, ListVisits);
setListAdapter(adapter);
}
visitsDAO
package lk.agent.certislanka.certisagenttracking.data;
/**
* Created by administrator on 7/7/15.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import lk.agent.certislanka.certisagenttracking.model.Visits;
/**
* Created by administrator on 7/6/15.
*/
public class VisitsDAO {
public static final String TAG = "visitsDAO";
// Database fields
private SQLiteDatabase mDatabase;
private DBHelper mDbHelper;
private Context mContext;
private String[] mAllColumns = {
DBHelper.COLUMN_VISITS_ID,
DBHelper.COLUMN_VISITS_SCHEDULE_ID,
DBHelper.COLUMN_VISITS_NAME,
DBHelper.COLUMN_VISITS_TIME,
DBHelper.COLUMN_VISITS_PLACE,
DBHelper.COLUMN_VISITS_ADDRESS,
DBHelper.COLUMN_VISITS_TEL,
DBHelper.COLUMN_VISITS_LOCATION_LAT,
DBHelper.COLUMN_VISITS_LOCATION_LNG,
DBHelper.COLUMN_VISITS_STATUS };
public VisitsDAO(Context context) {
this.mContext = context;
mDbHelper = new DBHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on openning database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public Visits createvisits(int vid, int v_sid, String vname, String vtime, String vplace, String address, String telephone, String vlat, String vlong, int vstatus) {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_VISITS_ID, vid);
values.put(DBHelper.COLUMN_VISITS_SCHEDULE_ID, v_sid);
values.put(DBHelper.COLUMN_VISITS_NAME, vname);
values.put(DBHelper.COLUMN_VISITS_TIME, vtime);
values.put(DBHelper.COLUMN_VISITS_PLACE, vplace);
values.put(DBHelper.COLUMN_VISITS_ADDRESS, address);
values.put(DBHelper.COLUMN_VISITS_TEL, telephone);
values.put(DBHelper.COLUMN_VISITS_LOCATION_LAT, vlat);
values.put(DBHelper.COLUMN_VISITS_LOCATION_LNG, vlong);
values.put(DBHelper.COLUMN_VISITS_STATUS, vstatus);
long insertId = mDatabase
.insert(DBHelper.TABLE_VISITS, null, values);
Cursor cursor = mDatabase.query(DBHelper.TABLE_VISITS, mAllColumns,
DBHelper.COLUMN_VISITS_ID + " = " + insertId, null, null,
null, null);
Visits newvisits = null;
if (cursor != null&& cursor.moveToFirst()) {
cursor.moveToFirst();
newvisits = cursorTovisits(cursor);
}
cursor.close();
return newvisits;
}
public List<Visits> getAllvisits() {
List<Visits> listVisits = new ArrayList<Visits>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_VISITS, mAllColumns,
null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Visits visits = cursorTovisits(cursor);
listVisits.add(visits);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listVisits;
}
public List<Visits> getAllvisitsforSchedule(int id) {
List<Visits> listVisits = new ArrayList<Visits>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_VISITS, mAllColumns,
DBHelper.COLUMN_VISITS_SCHEDULE_ID + " = ?",
new String[]{String.valueOf(id)}, null, null, "visit_time ASC");
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Visits visits = cursorTovisits(cursor);
listVisits.add(visits);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listVisits;
}
public Visits getvisitById(int id) {
Cursor cursor = mDatabase.query(DBHelper.TABLE_VISITS, mAllColumns,
DBHelper.COLUMN_VISITS_ID + " = ?",
new String[]{String.valueOf(id)}, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
Visits visits = cursorTovisits(cursor);
return visits;
}
protected Visits cursorTovisits(Cursor cursor) {
Visits schedule = new Visits();
schedule.setvId(cursor.getInt(0));
schedule.setVschID(cursor.getInt(1));
schedule.setVname(cursor.getString(2));
schedule.setVtime(cursor.getString(3));
schedule.setVplace(cursor.getString(4));
schedule.setVaddress(cursor.getString(5));
schedule.setvtelephone(cursor.getString(6));
schedule.setVlat(cursor.getString(7));
schedule.setVlong(cursor.getString(8));
schedule.setVstatus(cursor.getInt(9));
return schedule;
}
public void deleteVisits(Visits visits) {
int id = visits.getvId();
mDatabase.delete(DBHelper.TABLE_VISITS, DBHelper.COLUMN_VISITS_ID + " = " + id, null);
}
public void deleteAllVisits() {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
db.delete(DBHelper.TABLE_VISITS, null, null);
}
}
You just have to set whatever properties you want for textview, imageview, layout etc. in getView() methos of your list adapter.
For example refer the below code,
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView ;
if( convertView == null ) {
imageView = new ImageView(context);
imageView.setLayoutParams(
new ListView.LayoutParams( 80,80 )
);
}
else {
imageView = (ImageView) convertView;
}
imageView.setImageResource( imageIds[position] );
imageView.setEnabled(false);
return imageView;
}
Where I have written imageView.setEnabled(false), you can give whatever properties to your views ( like layout.setBackground(Color.RED); )

Android: Parcelable object successfully passed to another activity, but now I can't use any of its methods

I was trying to pass an instance of my Music class from one activity to another, and I did get that to work; however, now I can't use any of Music class' methods in the second activity. It keeps throwing a NullPointerException when I try to call any method in Music.
Music Class:
public class Music implements Parcelable{
private static ArrayList<genericSongClass> songs = new ArrayList<genericSongClass>();
Cursor cursor;
Context context;
public Music(){};
public Music(Context context){
this.context = context;
}
public Music(Parcel in){
songs = new ArrayList<genericSongClass>();
in.readTypedList(songs, genericSongClass.CREATOR);
}
public void BindAllSongs() {
/** Making custom drawable */
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
final String[] projection = new String[] {
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM};
final String sortOrder = MediaStore.Audio.AudioColumns.TITLE
+ " COLLATE LOCALIZED ASC";
try {
// the uri of the table that we want to query
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
// query the db
cursor = context.getContentResolver().query(uri,
projection, selection, null, sortOrder);
if (cursor != null) {
songs = new ArrayList<genericSongClass>(cursor.getCount());
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
genericSongClass GSC = new genericSongClass();
GSC.songTitle = cursor.getString(0);
GSC.songArtist = cursor.getString(1);
GSC.songData = cursor.getString(2);
GSC.songAlbum = cursor.getString(3);
songs.add(GSC);
cursor.moveToNext();
}
}
} catch (Exception ex) {
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public static Object[] toArray(ArrayList<Object> list){
Object[] toReturn = new Object[list.size()];
for (int i = 0; i < list.size(); i++){
toReturn[i] = list.get(i);
}
return toReturn;
}
public ArrayList<String> getArtists(){
ArrayList<String> artists = new ArrayList<String>();
for(genericSongClass gsc: songs){
if(!artists.contains(gsc.songArtist)){
artists.add(gsc.songArtist);
}
}
Alphabetize forArtists = new Alphabetize(artists);
return forArtists.getSortedArrayList();
}
public ArrayList<String> getAlbums(String artist){
ArrayList<String> albums = new ArrayList<String>();
Log.e("HEY!", "HEY!");
for(genericSongClass gsc: songs){
if(gsc.songArtist == artist){
albums.add(gsc.songAlbum);
}
}
Alphabetize forAlbums = new Alphabetize(albums);
return forAlbums.getSortedArrayList();
}
//--- Parcel ------------------------------------------------
public static final Parcelable.Creator<Music> CREATOR = new Parcelable.Creator<Music>() {
public Music createFromParcel(Parcel in) {
return new Music(in);
}
#Override
public Music[] newArray(int size) {
return new Music[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeList(songs);
}
}
How I passed the instance of Music from activity one:
Intent in = new Intent(getApplicationContext(), Album_Activity.class);
in.putExtra("Artist", artists.get(button.getId()));
startActivity(in);
in.putExtra("MusicInstance", MainActivity.this.thisInstance);
If I do startActivity after I put MusicInstance in the intent, I get a runtime error that says "unmarshalling unknown type."
How I received the instance in activity two:
Intent in = getIntent();
thisInstance = getIntent().getParcelableExtra("MusicInstance");
artist = (String) in.getExtras().get("Artist");
ArrayList<String> albums = thisInstance.getAlbums(artist);
The line
ArrayList<String> albums = thisInstance.getAlbums(artist);
keeps throwing a NullPointerException. I've tried calling other methods from the class with the same error. I checked to make sure artist wasn't null.
Can anyone point me in the right direction here?
As you can see, you start the activity before you can put "MusicInstance", so you'll always get a NullPointerException.
I think you should try put a Serializable object
See the answer of this post

Android get Media.Images Uri from ID

I am new to Android and Java and this week I've been doing a self-taught crash course. So far what I've learned has not been too complicated as I've already built a number of years of coding experience. So, background history out of the way, onto my question.
The below code is two functions I wrote to take an image ID from a database and parse the correct Uri which I can then use to upload the photo to a website. So could you kind folks look over my code and let me know if I'm doing a terrible job or if I am heading in the right direction or even if there is a better/native way to do what I need.
Also, note: the below code does work. I just don't know if it is the right way to do it.
Thanks!
// Usage Map idPath = ImageIdPathFetcher.getRealIdPathFromID(getApplicationContext(), Integer.valueOf(image_id));
public static Map getRealIdPathFromID(Context context, Integer id) {
Map<String,String> idPath = new HashMap<String, String>();
Uri external_images_uri = MediaStore.Images.Media.getContentUri("external");
Uri internal_images_uri = MediaStore.Images.Media.getContentUri("internal");
// initialize uri
Uri uri = external_images_uri;
String ext_img_uri = external_images_uri.toString()+"/"+id;
String int_img_uri = internal_images_uri.toString()+"/"+id;
if(check_uri(context, ext_img_uri))
{
uri = Uri.parse(ext_img_uri);
}else if(check_uri(context, int_img_uri))
{
uri = Uri.parse(int_img_uri);
}else {
idPath.put("id", "");
idPath.put("path", "");
return idPath;
}
String[] proj = { Media.DATA, Media._ID };
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(Media.DATA);
cursor.moveToFirst();
String filepath = cursor.getString(column_index);
idPath.put("id", id.toString());
idPath.put("path", filepath);
return idPath;
}
public static boolean check_uri(Context context, String uri)
{
try{
ContentResolver cr = context.getContentResolver();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cur = cr.query(Uri.parse(uri), projection, null, null, null);
if(cur != null)
{
cur.moveToFirst();
String filePath = cur.getString(0);
if(! new File(filePath).exists()){
return false;
}
} else {
return false;
}
} catch (Exception e)
{
return false;
}
return true;
}
This is what I use
public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
}
} finally {
cursor.close();
}
}
cursor = context.getContentResolver().query(
MediaStore.Images.Media.INTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
return Uri.withAppendedPath(MediaStore.Images.Media.INTERNAL_CONTENT_URI, String.valueOf(id));
}
} finally {
cursor.close();
}
}
return null;
}
It is possible to query both internal and external MediaStore database also with MergeCursor:
String myIdImgStr = "123"; // the unique ID of the image in the MediaStore
ContentResolver contentResolver = this.getContext().getContentResolver();
String [] proj = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
MergeCursor cursor = new MergeCursor(new Cursor[] {
MediaStore.Images.Media.query(contentResolver,
Uri.parse(MediaStore.Images.Media.INTERNAL_CONTENT_URI + "/" + myIdImgStr),
proj),
MediaStore.Images.Media.query(contentResolver,
Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + myIdImgStr),
proj)
});
if(cursor.getCount() == 1) {
cursor.moveToFirst();
String filepath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}

Categories

Resources