show songs of an selected album in Listview - android

I want to show the songs of an selected album by overriding the currently used ListView.
But I don't get it. In this code I show all albums and get their songs.
Maybe you can help me.Thanks a lot, Vinzenz :)
public class Albumsshow extends ListActivity {
public ArrayList<HashMap<String, String>> albumsList = new ArrayList<HashMap<String, String>>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.browse);
ArrayList<HashMap<String, String>> albumsListData = new ArrayList<HashMap<String, String>>();
AlbumsManager plm = new AlbumsManager();
// get all songs from sdcard
this.albumsList = plm.getAlbumList(this);
// looping through playlist
for (int i = 0; i < albumsList.size(); i++) {
// creating new HashMap
HashMap<String, String> album = albumsList.get(i);
// adding HashList to ArrayList
albumsListData.add(album);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, albumsListData,
R.layout.playlist_item, new String[] { "album" }, new int[] {
R.id.songTitle });
setListAdapter(adapter);
// selecting single ListView item
final ListView lv = getListView();
final TextView tv =(TextView)findViewById(R.id.umandern);
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int albumIndex = position;
String[] column = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.MIME_TYPE, };
String where = android.provider.MediaStore.Audio.Media.ALBUM + "=?";
String whereVal[] = {albumsList.get(albumIndex).get("album") };
String orderBy = android.provider.MediaStore.Audio.Media.TITLE;
Cursor cursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
column, where, whereVal, orderBy);
if (cursor.moveToFirst()) {
do {
Log.v("music title",
cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
} while (cursor.moveToNext());
}
}
});
}
}

The code your using is the code i had and it's not overly hard, the only problem you may end up having is actually playing the songs but other than that you can list all albums and the songs like this....
public class AlbumsList extends ListActivity{
public ArrayList<HashMap<String,String>> songsList = new ArrayList<HashMap<String, String>>();
int count;
Cursor cursor;
ListView musiclist;
int songAlbum;
int position;
ListView list;
String songTitle = "";
String songPath = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.albums);
list = (ListView) findViewById(android.R.id.list);
String[] columns = { BaseColumns._ID,
AlbumColumns.ALBUM };
cursor = getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
columns, null, null, null);
String[] displayFields = new String[] { AlbumColumns.ALBUM };
int[] displayViews = new int[] { android.R.id.text1 };
#SuppressWarnings("deprecation")
ListAdapter adapter = (new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, cursor, displayFields,
displayViews));
setListAdapter(adapter);
}
public AlbumsList(){
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
if(cursor.moveToPosition(position)){
ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
// get all songs from sdcard
this.songsList = this.getPlayList();
// looping through playlist
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
HashMap<String, String> song = songsList.get(i);
// adding HashList to ArrayList
songsListData.add(song);
}
ListAdapter adapter = new SimpleAdapter(this, songsListData,
android.R.layout.simple_list_item_1, new String[] { "songTitle", "songPath" }, new int[] {
android.R.id.text1});
setListAdapter(adapter);
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int songIndex = position;
// Starting new intent
Intent in = new Intent(AlbumsList.this,
MainActivity.class);
Log.d("TAG","onItemClick");
// Sending songIndex to PlayerActivity
in.putExtra("songPath", songIndex);
startActivityForResult(in, 99);
// Closing PlayListView
finish();
}
});
}
}
public ArrayList<HashMap<String, String>> getPlayList(){
String[] columns = { MediaColumns.DATA,
BaseColumns._ID,
MediaColumns.TITLE,
MediaColumns.MIME_TYPE, };
String where = AudioColumns.ALBUM
+ "=?";
String whereVal[] = { cursor.getString(cursor
.getColumnIndex(AlbumColumns.ALBUM))};
String orderBy = MediaColumns.TITLE;
cursor = this.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,columns,
where, whereVal, orderBy);
if (cursor.moveToFirst()) {
do {
songTitle = cursor.getString(cursor.getColumnIndexOrThrow(MediaColumns.TITLE));
songPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaColumns.DATA));
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", songTitle);
song.put("songPath", songPath);
songsList.add(song);
} while (cursor.moveToNext());
}
cursor.close();
return songsList;
}

Related

Listview shows old and new content after updating

In my application, listview is loaded from SQLite database and it is using SimpleAdapter to set ListView. When user perform longclick on listitem, that item will be deleted from database and it should update listviw. But when i remove item from database, listview shows both old and new data.
Please suggest some solution.
Thanx.
Following is my code:
public class FavouriteListActivity extends ListActivity {
public final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
ListAdapter adapter;
public ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
ArrayList<String> titles = new ArrayList<String>();
String title,artist;
SQLiteAdapter adp;
SimpleCursorAdapter cursoradp;
Cursor cursor,cursorDB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favouritelist);
// Adding menuItems to ListView
final String[] from = {"songTitle", "artist","duration"};
final int[] to={R.id.fav_songTitle,R.id.fav_songArtist,R.id.fav_duration};
ListView lv = getListView();
songsListData = getFavourites();
final ListAdapter adapter = new SimpleAdapter(this,songsListData,
R.layout.favouritelist_item, from, to);
lv.setFastScrollEnabled(true);
setListAdapter(adapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
public boolean onItemLongClick(AdapterView<?> av, View v,
final int pos,final long id) {
final AlertDialog.Builder b = new AlertDialog.Builder(FavouriteListActivity.this);
b.setTitle("Are you sure you want to delete?");
b.setIcon(android.R.drawable.ic_delete);
b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String title = songsListData.get(pos).get("songTitle");
ListAdapter adapter = null;
adp.delete_byTitle(title);
songsListData.clear();
setListAdapter(null);
songsListData = getFavourites();
adapter = new SimpleAdapter(getApplicationContext(), songsListData,R.layout.favouritelist_item, from, to);
setListAdapter(adapter);
Toast.makeText(FavouriteListActivity.this,"Song is removed from Favourites", Toast.LENGTH_SHORT).show();
}
});
b.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
b.show();
return true;
}
});
}
public ArrayList<HashMap<String,String>> getFavourites()
{
ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
ArrayList<String> titles = new ArrayList<String>();
adp = new SQLiteAdapter(this);
adp.openToRead();
cursorDB = adp.queueAll();
if(cursorDB.moveToFirst())
{
for(int i=0;i<cursorDB.getCount();i++)
{
titles.add(cursorDB.getString(cursorDB.getColumnIndex("Title")));
cursorDB.moveToNext();
}
String[] songTitles = new String[titles.size()];
songTitles = titles.toArray(songTitles);
if(songTitles == null)
{
songTitles =null;
}
String whereClause = MediaStore.Audio.Media.TITLE + " IN ( ?";
if (songTitles.length>1)
{
for (int j = 1 ; j < songTitles.length; ++j)
{
whereClause+=", ?";
}
}
whereClause+=")";
Cursor cursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null ,whereClause,songTitles,MediaStore.Audio.Media.TITLE);
if (cursor == null)
{
//Query Failed , Handle error.
}
else if (!cursor.moveToFirst())
{
//No media on the device.
}
else
{
int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = cursor.getColumnIndexOrThrow(android.provider.MediaStore.Audio.Media.DATA);
int artistcolumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
int durationcolumn =cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.DURATION);
for(int i=0;i<cursor.getCount();i++)
{
String thisTitle = cursor.getString(titleColumn);
String path = cursor.getString(idColumn);
String artist = cursor.getString(artistcolumn);
Long duration = cursor.getLong(durationcolumn);
Utilities objUtilities = new Utilities();
String timeDuration = objUtilities.milliSecondsToTimer(duration);
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle",thisTitle);
song.put("songPath", path);
song.put("artist", artist);
song.put("duration",timeDuration);
// Adding each song to SongList
songsList.add(song);
cursor.moveToNext();
}
}
// looping through playlist
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
HashMap<String, String> song = songsList.get(i);
// adding HashList to ArrayList
songsListData.add(song);
}
}
return songsListData;
}
}
You never clear songList, to which therefore is added all your items at each deletion.
Which in turn are all copied to songsListData.
After removing data from the database , call
Listview.invalidateViews();
and reset the adapter to the list .
Actually it gets removed from the database but it shows the older list in the ListView , so invalidate your older views and reset the adapter .
Call adapter.notifyDataSetChanged() every time your data changes.
b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String title = songsListData.get(pos).get("songTitle");
adp.delete_byTitle(title);
songsListData.clear();
setListAdapter(null);
songsListData = getFavourites();
adapter = new SimpleAdapter(getApplicationContext(), songsListData,R.layout.favouritelist_item, from, to);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
Toast.makeText(FavouriteListActivity.this,"Song is removed from Favourites", Toast.LENGTH_SHORT).show();
}
});

Passing info from one intent to the other

I have an app which reads some data from JSON, and I have 2 classes which do this.
Right now both classes display the full list of registered members.
But what I'm trying to achieve is that when a member is clicked I only get to see that member and not the other ones as well.
Here is the code from both classes:
From the listview:
public class Listviewer extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http://de-saksen.nl/deelnemers.txt");
try{
JSONArray deelnemers = json.getJSONArray("deelnemers");
for(int i=0;i<deelnemers.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = deelnemers.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Character Naam: " + e.getString("naamingw2"));
map.put("sex", "Geslacht: " + e.getString("geslacht"));
map.put("rank", "Rang: " + e.getString("rang"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
new String[] { "name", "sex", "rank"},
new int[] { R.id.item_title, R.id.item_subtitle, R.id.item_subtitle2 });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Listviewer.this, Profileviewer.class);
startActivity(intent);
}
});
}
}
And from the profile view:
public class Profileviewer extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http://de-saksen.nl/deelnemers.txt");
try{
JSONArray deelnemers = json.getJSONArray("deelnemers");
for(int i=0;i<deelnemers.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = deelnemers.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Naam: " + e.getString("naamingw2"));
map.put("sex", "Geslacht: " + e.getString("geslacht"));
map.put("rank", "Rang: " + e.getString("rang"));
map.put("race", "Ras: " + e.getString("ras"));
map.put("profession", "Beroep: " + e.getString("beroep"));
map.put("skills", "Hobby's: " + e.getString("hobbys"));
map.put("lvl", "Level: " + e.getString("level"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.profile,
new String[] { "name", "sex", "rank", "race", "profession", "skills", "lvl" },
new int[] { R.id.item_title, R.id.item_subtitle, R.id.item_subtitle2, R.id.item_subtitle3, R.id.item_subtitle4, R.id.item_subtitle5, R.id.item_subtitle6 });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Profileviewer.this, Listviewer.class);
startActivity(intent);
}
});
}
}
I recon I have to pass a variable to the other class containing what member has been clicked, but how do I achieve this?
using the intent:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Profileviewer.this, Listviewer.class);
intent.putExtra("Key", value);
startActivity(intent);
}
});
Then in Listviewer.java:
getIntent().getStringExtra("Key"); //for example
To pass user data, modify like:
String [] users = new String[] { "name", "sex", "rank", "race", "profession", "skills", "lvl" };
int[] ids = new int[] { R.id.item_title, R.id.item_subtitle, R.id.item_subtitle2, R.id.item_subtitle3, R.id.item_subtitle4, R.id.item_subtitle5, R.id.item_subtitle6 };
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.profile,
users, ids);
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Profileviewer.this, Listviewer.class);
intent.putExtra("Key", users[position]);
startActivity(intent);
}
});
If you want to pass int value:
categoryView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(CategoryView.this, "id::" + id,
Toast.LENGTH_SHORT).show();
Intent menuIntent = new Intent(CategoryView.this,MenuListView.class);
Bundle b = new Bundle();
b.putInt("categoryId", (int) id); //Your id
menuIntent.putExtras(b);
menuIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(menuIntent);
//finish();
}
});
you can send basic information when create an Intent object using Extras. Take a look at http://developer.android.com/guide/components/intents-filters.html .
If you had to load a lot of information and Extras is not right enough, you just sent a "key" that you will use to take back all info you need.
For example:
ThisClass
Intent intent = new Intent(thisClass, otherClass);
intent.putExtra("id", "1");
intent.putExtra("model", "model1");
startActivity(inte);
OtherClass
String query = "SELECT * FROM " + T_NAME + " WHERE 'id' = " + getIntent().getIntExtra("id",0);
Cursor c = db.rawQuery(query, null)

Android songs fetching from SD card

I am fetching my songs from the SD card and putting him to the list view.
I am using this method.
but its taking some time and if path is different I didn't get that data.
so ,
QUE Is there any helpfull script that display songs from all my sd card.
If they are into directory/songs .
public ArrayList<HashMap<String, String>> getPlayList(){
File home = new File(MEDIA_PATH);
if (home.listFiles(new FileExtensionFilter()).length > 0) {
for (File file : home.listFiles(new FileExtensionFilter())) {
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
song.put("songPath", file.getPath());
// Adding each song to SongList
songsList.add(song);
}
}
// return songs list array
return songsList;
}
class FileExtensionFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".MP3"));
}
}
Please give your comments on this .
I once used MediaStore for my music application, this is a very more efficient and correct way to retrieve data and then display it using a ListView. This will retrieve any music file stored in any folder on your SDCard.
//your database elect statement
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
//your projection statement
String[] projection = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.ALBUM_ID
};
//query
cursor = this.managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
null,
null);
while(cursor.moveToNext()){
songs.add(cursor.getString(0));
songs.add(cursor.getString(1));
songs.add(cursor.getString(2));
songs.add(cursor.getString(3));
songs.add(cursor.getString(4));
songs.add(cursor.getString(5));
album_id.add((long) cursor.getFloat(6));
}
int a[]= new int[]{R.id.textView1 ,R.id.textView3};//, R.id.textview2};
ListAdapter adapter = new SimpleCursorAdapter(this,
R.layout.items, cursor, new String[]{MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST/*, MediaStore.Audio.Media.DURATION*/} ,a);
setListAdapter(adapter);
}
please use this code to implement this functionality.
public class SdCardSongsFragment extends Fragment {
public File file;
private List<String> myList;
private List<String> mycountList;
private ListView listView;
private TextView pathTextView;
private String mediapath = new String(Environment.getExternalStorageDirectory().getAbsolutePath());
String selection =MediaStore.Audio.Media.DATA +" like ?";
String[] projection = {MediaStore.Audio.Media.DATA , MediaStore.Audio.Media.DISPLAY_NAME};
Cursor cursor2;
//your database elect statement
String selection2 = MediaStore.Audio.Media.IS_MUSIC + " != 0";
//your projection statement
String[] projection2= {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.ALBUM_ID
};
private final static String[] acceptedExtensions= {"mp3", "mp2", "wav", "flac", "ogg", "au" , "snd", "mid", "midi", "kar"
, "mga", "aif", "aiff", "aifc", "m3u", "oga", "spx"};
/** Called when the activity is first created. */
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_sdcrad_song, container, false);
listView=(ListView) rootView.findViewById(R.id.pathlist);
pathTextView=(TextView) rootView.findViewById(R.id.path);
myList = new ArrayList<String>();
mycountList= new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
Log.e("Root",root_sd);
String state = Environment.getExternalStorageState();
File list[] = null ;
/* if ( Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) ) { // we can read the External Storage...
list=getAllFilesOfDir(Environment.getExternalStorageDirectory());
}*/
pathTextView.setText(root_sd);
file = new File( root_sd ) ;
list = file.listFiles(new AudioFilter());
Log.e("Size of list ","" +list.length);
//LoadDirectory(root_sd);
for( int i=0; i< list.length; i++)
{
String name=list[i].getName();
int count = getAudioFileCount(list[i].getAbsolutePath());
Log.e("Count : "+count, list[i].getAbsolutePath());
if(count!=0) {
myList.add(name);
mycountList.add(""+count);
}
}
listView.setAdapter(new SDcardSongListAdapter(getActivity(), myList,mycountList ));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
File temp_file = new File( file, myList.get( position ) );
if( !temp_file.isFile())
{
file = new File( file, myList.get( position ));
File list[] = file.listFiles(new AudioFilter());
myList.clear();
mycountList.clear();
for( int i=0; i< list.length; i++)
{
String name=list[i].getName();
int count = getAudioFileCount(list[i].getAbsolutePath());
Log.e("Count : "+count, list[i].getAbsolutePath());
if(count!=0) {
myList.add(name);
mycountList.add(""+count);
}
}
pathTextView.setText( file.toString());
//Toast.makeText(getApplicationContext(), file.toString(), Toast.LENGTH_LONG).show();
listView.setAdapter(new SDcardSongListAdapter(getActivity(), myList,mycountList ));
}
else {
Log.e("Not dirctory ", file.getAbsolutePath());
Cursor cur=getAudioFileCursor(file.getAbsolutePath());
Log.e("Cur count ", ""+cur.getCount());
MusicUtils.playAll(getActivity(), cur,position);
}
}
});
return rootView;
}
private int getAudioFileCount(String dirPath) {
Log.e("Path : ", dirPath);
String[] selectionArgs={dirPath+"%"};
Cursor cursor = getActivity().managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection2,
selection,
selectionArgs,
null);
cursor2=cursor;
if(cursor!=null)
Log.e("Cur : ", ""+cursor.getCount());
return cursor.getCount();
}
private Cursor getAudioFileCursor(String dirPath) {
String[] selectionArgs={dirPath+"%"};
Cursor cursor = getActivity().managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection2,
selection,
selectionArgs,
null);
return cursor;
}
public void onBack() {
String parent="";
if(file!=null)
parent = file.getParent().toString();
file = new File( parent ) ;
File list[] = file.listFiles(new AudioFilter());
myList.clear();
mycountList.clear();
for( int i=0; i< list.length; i++)
{
String name=list[i].getName();
int count = getAudioFileCount(list[i].getAbsolutePath());
Log.e("Count : "+count, list[i].getAbsolutePath());
if(count!=0) {
myList.add(name);
mycountList.add(""+count);
}
/*int count=getAllFilesOfDir(list[i]);
Log.e("Songs count ",""+count);
if(count!=0)*/
}
pathTextView.setText(parent);
// Toast.makeText(getApplicationContext(), parent, Toast.LENGTH_LONG).show();
listView.setAdapter(new SDcardSongListAdapter(getActivity(), myList,mycountList ));
}
// class to limit the choices shown when browsing to SD card to media files
public class AudioFilter implements FileFilter {
// only want to see the following audio file types
private String[] extension = {".aac", ".mp3", ".wav", ".ogg", ".midi", ".3gp", ".mp4", ".m4a", ".amr", ".flac"};
#Override
public boolean accept(File pathname) {
// if we are looking at a directory/file that's not hidden we want to see it so return TRUE
if ((pathname.isDirectory() || pathname.isFile()) && !pathname.isHidden()){
return true;
}
// loops through and determines the extension of all files in the directory
// returns TRUE to only show the audio files defined in the String[] extension array
for (String ext : extension) {
if (pathname.getName().toLowerCase().endsWith(ext)) {
return true;
}
}
return false;
}
}
}
XML file code :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/title_songs"
android:orientation="vertical" >
<TextView
android:id="#+id/pathDR"
android:layout_width="fill_parent"
android:layout_height="70dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:gravity="bottom"
android:text="Directory"
android:textColor="#ffffff"
android:textSize="19sp"
android:typeface="monospace" />
<TextView
android:id="#+id/path"
android:layout_width="fill_parent"
android:layout_height="18dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:gravity="bottom"
android:text=""
android:textColor="#ffffff"
android:textSize="12sp"
android:typeface="monospace" />
<View
android:layout_width="fill_parent"
android:layout_height="2dp"
android:background="#ffffff" />
<ListView
android:background="#drawable/bg"
android:id="#+id/pathlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
</LinearLayout>
ArrayList<String> names = new ArrayList<String>();
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Uri uri;
int columnIndex;
String[] projection = { MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ALBUM_ID };
ListView lst;
ArrayAdapter<String> adapter;
Cursor cursor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
cursor = this.managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection, selection, null, null);
if (cursor.getCount() == 0) {
Toast.makeText(getBaseContext(),
"cursor value" + cursor.getCount(), Toast.LENGTH_SHORT)
.show();
} else {
cursor.moveToFirst();
do {
names.add(cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
} while (cursor.moveToNext());
adapter = new ArrayAdapter<String>(Home.this,
android.R.layout.simple_list_item_1, names);
lst.setAdapter(adapter);
}
I am getting cursor count 0 actually i added a folder to sdcard but files are not coming
//try this its working code
public ArrayList<HashMap<String, String>> getAudioList() {
ArrayList<HashMap<String, String>> mSongsList = new ArrayList<HashMap<String, String>>();
Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DATA }, null, null, null);
int count = mCursor.getCount();
System.out.println("total no of songs are=" + count);
HashMap<String, String> songMap;
while (mCursor.moveToNext()) {
songMap = new HashMap<String, String>();
songMap.put(
"songTitle",
mCursor.getString(mCursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)));
songMap.put("songPath", mCursor.getString(mCursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));
mSongsList.add(songMap);
}
mCursor.close();
return mSongsList;
}
this will help you to make a listview using that playlist
public class PlayListActivity extends ListActivity {
public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
private Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
EditText search = (EditText) findViewById(R.id.et_search_music);
ListView lv = (ListView) findViewById(android.R.id.list);
context = PlayListActivity.this;
ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
this.songsList = MusicPlayerActivity.songsList;
if (this.songsList.size() > 0) {
final SimpleAdapter adapter = new SimpleAdapter(this,
this.songsList, R.layout.playlist_item,
new String[] { "songTitle" }, new int[] { R.id.songTitle });
setListAdapter(adapter);
lv.setTextFilterEnabled(true);
lv = getListView();
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
adapter.getFilter().filter(s);
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int CurrentSongIndex = position;
Intent in = new Intent();
in.putExtra("songIndex", CurrentSongIndex);
setResult(100, in);
finish();
}
});
}
}
}

Suggest me a suitable adapter to pass arraylist containing image url and title to display in listview

i hav to display the thumbnail of the image along with the title of it in a list view by parsing the JSON feed.. My code
public class Main extends ListActivity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
String url;
Bitmap bitmap;
ImageView img;
int im ;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = Json_mysamActivity.getJSONfromURL("http://gdata.youtube.com/feeds/mobile/videos?max-results=3&alt=json");
try {
JSONObject jb = json.getJSONObject("feed");
JSONArray jarr = jb.getJSONArray("entry");
for(int i=0;i<jarr.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jarr.getJSONObject(i);
JSONObject det = e.getJSONObject("title");
map.put("id", String.valueOf(i));
map.put("$t", "t:" + det.getString("$t"));
map.put("type", "type: " + det.getString("type"));
JSONObject det1 = e.getJSONObject("media$group");
JSONArray det12 = det1.getJSONArray("media$thumbnail");
for(int j=0;j<1;j++)
{
JSONObject det12obj = det12.getJSONObject(i);
url = det12obj.getString("url");
map.put("url", "url:"+ det12obj.getString("url"));
mylist.add(map);
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String[] from = new String[] { "$t", "type","url" };
int[] to = new int[] { R.id.item_title, R.id.item_subtitle, R.id.test_image };
MySimpleCursorAdapter adapter = new MySimpleCursorAdapter(this, R.layout.main, mylist ,
from, to);
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
public class MySimpleCursorAdapter extends SimpleCursorAdapter {
// SimpleCursorAdapter requires cursor in the place of ArrayList but I need to pass //arraylist, how should I implement it
public MySimpleCursorAdapter(Context context, int layout, ArrayList<HashMap<String, String>> mylist,
String[] from, int[] to) {
super(context, layout, mylist, from, to);
}
#Override
public void setViewImage(ImageView v, String url) {
String path =url ;
Bitmap b = BitmapFactory.decodeFile(path);
v.setImageBitmap(b);
}
}
}
What you need is a SimpleAdapter. A cursor adapter is used for displaying daat in a list that comes from a database. SimpleAdapter is used for data in RAM (your list after parsing the json).
Check this first google entry, it should do.
In case you are using arraylist as datasource you should use ArrayAdapter, so Extend your adapter from ArrayAdapter. see link for Custom Array Adapter:
http://android-er.blogspot.in/2010/06/custom-arrayadapter-with-with-different.html
When you are loading image views in list, its good practice to use LazyLoading, see below link for Lazy Loading in android:
http://ballardhack.wordpress.com/2010/04/05/loading-remote-images-in-a-listview-on-android/
for this you have to use LayoutInflater, write your own adapter class extends ArrayAdapter,
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
adapter = new CustomAdapter(this, R.layout.list_row, R.id.title, data,
mInflater, imgid);

Database results in a listView is not working

i m trying to get data from my database and present them to a listView.i m using two classes for my database:
1st class is the DBAdapter and the method i use to get data is:
public String[] getData()
{
// String[] columns =new String[]{DBHelper.ROWID, DBHelper.TITLE , DBHelper.AUTHOR, DBHelper.ISBN };
String[] columns =new String[]{DBHelper.TITLE , DBHelper.AUTHOR, DBHelper.ISBN };
Cursor c=ourDatabase.query(DBHelper.DATABASE_TABLE, columns, null, null, null, null, null);
String result="";
String sa = null;
String sb = null;
String sc = null;
//int iRow=c.getColumnIndex(DBHelper.ROWID);
int is1=c.getColumnIndex(DBHelper.TITLE);
int is2=c.getColumnIndex(DBHelper.AUTHOR);
int is3=c.getColumnIndex(DBHelper.ISBN);
for (c.moveToFirst();!c.isAfterLast();c.moveToNext()){
//result=result+c.getString(is1)+" "+c.getString(is2)+" "+c.getString(is3)+"\n";
sa=c.getString(is1);
sb=c.getString(is2);
sc=c.getString(is3);
}
//Toast.makeText(HotOrNot.this, sa, Toast.LENGTH_SHORT).show();
return new String[] {sa,sb,sc};
}
2.The secind class in SQLView and thats the way i m trying to create my list
public class SQLView extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
HotOrNot entry2=new HotOrNot(this);
entry2.open();
String[] data2=entry2.getData();
entry2.close();
Toast.makeText(SQLView.this, data2[1].toString(), Toast.LENGTH_SHORT).show();
ListView list = (ListView) findViewById(R.id.list);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map = new HashMap<String, String>();
map.put("name",data2[0].toString());
map.put("address", data2[1].toString());
map.put("address2", data2[2].toString());
mylist.add(map);
// ...
ListAdapter mSchedule = new SimpleAdapter(this, mylist, R.layout.row,
data2, new int[] {R.id.rtextView1,R.id.rtextView2,R.id.rtextView3});
list.setAdapter(mSchedule);
What i have to do in order to work?This is my first try to use database in android!
Now i just get an empty background...
EDIT:
With my toast i m getting the last item in position 1 that i added to db
Could anybody help me with the return statement in my DBHelper please?
Below is the fixed code. Try this out.
ListAdapter mSchedule = new SimpleAdapter(this, mylist, R.layout.row,
new String[] { "name", "address", "address2"},
new int[] {R.id.rtextView1,R.id.rtextView2,R.id.rtextView3});
list.setAdapter(mSchedule);
Basically you have to specify the columns/key of the map that you added. So it will map key from map to the corresponding view.
For looping issue, this will do the job:
for(int i=0; i<data2.length; i+=3) {
HashMap<String, String> map;
map = new HashMap<String, String>();
map.put("name",data2[i].toString());
map.put("address", data2[i+1].toString());
map.put("address2", data2[i+2].toString());
mylist.add(map);
}
The getData fix:
ArrayList<String> arrForData = new ArrayList<String>();
//int iRow=c.getColumnIndex(DBHelper.ROWID);
int is1=c.getColumnIndex(DBHelper.TITLE);
int is2=c.getColumnIndex(DBHelper.AUTHOR);
int is3=c.getColumnIndex(DBHelper.ISBN);
for (c.moveToFirst();!c.isAfterLast();c.moveToNext()){
//result=result+c.getString(is1)+" "+c.getString(is2)+" "+c.getString(is3)+"\n";
arrForData.add(c.getString(is1));
arrForData.add(c.getString(is2));
arrForData.add(c.getString(is3));
}
//Toast.makeText(HotOrNot.this, sa, Toast.LENGTH_SHORT).show();
return arrForData.toArray();

Categories

Resources