Android songs fetching from SD card - android

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();
}
});
}
}
}

Related

how to remove duplicate contacts from arraylist

I have created an app in which I am getting the contacts from a device.
But I want to remove the duplicate contacts from the results.
How could I do it?
MainActivity
public class MainActivity extends Activity implements OnItemClickListener {
EditText searchText;
ArrayList<String> phno0 = new ArrayList<String>();
List<String> arrayListNames;
public List<ProfileBean> list;
public SearchableAdapter adapter;
//ProfileBean bean;
String[] cellArray = null;
String contacts;
ListView lv;
String phoneNumber, name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
lv = (ListView) findViewById(R.id.listview);
list = new ArrayList<ProfileBean>();
getAllCallLogs(this.getContentResolver());
adapter = new SearchableAdapter(getApplication(), list);
lv.setAdapter(adapter);
lv.setItemsCanFocus(false);
lv.setOnItemClickListener(this);
lv.setTextFilterEnabled(true);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
public void getAllCallLogs(ContentResolver cr) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
while (phones.moveToNext()) {
phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
list.add(new ProfileBean(name, phoneNumber));
}
phones.close();
}
}
If you want to get rid of duplicates, consider using a HashSet instead.
If you can't/don't want to use it, simply check before adding whether the contact is already there.
if (!myList.contains(newContact))
myList.add(newContact);
Add the following checking in the place of list.add(new ProfileBean(name, phoneNumber)); before adding into list:
int flag = 0
if(list.size() == 0){
list.add(new ProfileBean(name, phoneNumber));
}
for(int i=0;i<list.size();i++){
if(!list.get(i).getProfileName().trim().equals(name)){
flag = 1;
}else{
flag =0;
break;
}
}
if(flag == 1){
list.add(new ProfileBean(name, phoneNumber));
}
The following function can be used for removing duplicates from String ArrayList Change it according to your requirement
public ArrayList<String> listWithoutDuplicates(ArrayList<String> duplicateList) {
// Converting ArrayList to HashSet to remove duplicates
LinkedHashSet<String> listToSet = new LinkedHashSet<String>(duplicateList);
// Creating Arraylist without duplicate values
ArrayList<String> listWithoutDuplicates = new ArrayList<String>(listToSet);
return listWithoutDuplicates;
}
use below code list=removeDuplicates(list);
public List<ProfileBean> removeDuplicates(List<ProfileBean> list) {
// Set set1 = new LinkedHashSet(list);
Set set = new TreeSet(new Comparator() {
#Override
public int compare(Object o1, Object o2) {
if (((ProfileBean) o1).getName().equalsIgnoreCase(((ProfileBean) o2).getName()) &&
((ProfileBean)o1).getPhoneNumber().equalsIgnoreCase(((ProfileBean)o2).getPhoneNumber())) {
return 0;
}
return 1;
}
});
set.addAll(list);
final List newList = new ArrayList(set);
return newList;
}
Try to get ContactsContract.Contacts.NAME_RAW_CONTACT_ID) its unique id and its used for update contacts compare your contacts with raw id is same or not as below
private void getAllContactsBackground() {
ContentResolver contentResolver = getActivity().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()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor cursorInfo = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getActivity().getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id));
Uri pURI = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Bitmap photo = null;
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
}
while (cursorInfo.moveToNext()) {
ContactsModel info = new ContactsModel();
info.contacts_id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
info.contacts_raw_id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.NAME_RAW_CONTACT_ID));
info.contacts_name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
info.contacts_mobile = cursorInfo.getString(cursorInfo.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceFirst("[^0-9]" + "91", "");
info.contacts_photo = photo;
info.contacts_photoURI = String.valueOf(pURI);
Cursor emailCur = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
info.contacts_email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.e("email==>", "" + info.contacts_email);
}
emailCur.close();
int flag = 0;
if (arrayListAllContacts.size() == 0) {
arrayListAllContacts.add(info);
}
for (int i = 0; i < arrayListAllContacts.size(); i++) {
if (!arrayListAllContacts.get(i).getContacts_raw_id().trim().equals(info.contacts_raw_id)) {
flag = 1;
} else {
flag = 0;
break;
}
}
if (flag == 1) {
arrayListAllContacts.add(info);
}
}
cursorInfo.close();
}
}
cursor.close();
}
}

show songs of an selected album in Listview

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;
}

get details of contact selected from list view

i am designing application in which i want to allow user to select multiple contact to send messages to. I have successfully retrieved the list of user in the listview with checkbox using the following code. now i want that when the user clicks on the "DONE" button, the PHONE NUMBER of the all selected contact should be retrieved in EDITTEXT in format like John <+919898xxxxxx>, Rick <+919988xxxxxx> and also that all the phone numbers containing just 10 digits i.e "9898xxxxxx" should be stored in a string seperated by comma (9898xxxxxx, 9988xxxxxx) automatically. how can i accomplish the requirement.
public class ContactsActivity extends ListActivity {
protected static final String TAG = null;
public String[] Contacts = {};
public int[] to = {};
public ListView myListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
final Button done_Button = (Button) findViewById(R.id.done_Button);
final Button clear_Button =(Button) findViewById(R.id.clear_Button);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, mCursor,
Contacts = new String[] {ContactsContract.Contacts.DISPLAY_NAME },
to = new int[] { android.R.id.text1 });
setListAdapter(adapter);
myListView = getListView();
myListView.setItemsCanFocus(false);
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
clear_Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Selections Cleared", Toast.LENGTH_SHORT).show();
ClearSelections();
}
});
/** When 'Done' Button Pushed: **/
done_Button.setOnClickListener(new View.OnClickListener() {
public void onClick (View v){
Log.i(TAG,":Done Button Selected:");
SparseBooleanArray selectedPositions = myListView.getCheckedItemPositions();
Log.i(TAG,"Number of Checked Positions: " + selectedPositions.size());
for (int i=0; i<selectedPositions.size(); i++) {
if (selectedPositions.get(selectedPositions.keyAt(i)) == true) {
//do stuff
}
}
}
});
}
private void ClearSelections() {
int count = this.myListView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.myListView.setItemChecked(i, false);
}
}
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME};
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_contacts, menu);
return true;
}
}
configured it finally
done_Button.setOnClickListener(new View.OnClickListener() {
public void onClick (View v){
String name = null;
String number = null;
long [] ids = myListView.getCheckedItemIds();
for(long id : ids) {
Cursor contact = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id + "" }, null);
while(contact.moveToNext()){
name = contact.getString(contact.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//name+=name;
number = contact.getString(contact.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//number+=number;
}
Toast.makeText(getApplicationContext(), "Name: " +name + "\n" + "Number: " + number , Toast.LENGTH_LONG).show();
}
}
});
String numberListString = "";
for (int i=0; i<selectedPositions.size(); i++) {
if (selectedPositions.get(selectedPositions.keyAt(i)) == true) {
//do stuff
numberListString = numberListString + "," + numberAtCurrentSelectedPostion;
}
}
mEditText.setText(numberListString);
Try this on your done button press:-
done_Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
name.clear();
number.clear();
Log.i(TAG, ":Done Button Selected:");
SparseBooleanArray selectedPositions = myListView
.getCheckedItemPositions();
Log.i(TAG,
"Number of Checked Positions: "
+ selectedPositions.size());
Cursor cur = getContacts();
for (int i = 0; i < selectedPositions.size(); i++) {
if (selectedPositions.get(selectedPositions.keyAt(i)) == true) {
// do stuff
cur.moveToPosition(selectedPositions.keyAt(i));
name.add(cur.getString(1));
}
}
for (int i = 0; i < name.size(); i++) {
Cursor lCursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, "DISPLAY_NAME = ? ",
new String[] { name.get(i) }, null);
lCursor.moveToFirst();
number.add(lCursor.getString(lCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
lCursor.close();
}
}
});
where name and number are array list of type String. You will get all selected name and there numbers. Now you can show them in Edit Text as you like.
I think this will help you.

I want to select a number from the contact book in Android

This Code shows the List of Contact Numbers, but i want to select cell number from selected contact display name--->
Cursor cursor= managedQuery(intent.getData(), null, null, null, null);
while(cursor.moveToNext()) {
String contactId=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
System.out.println("---------ContactId---------"+contactId);
String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println("---------NAME---------"+name);
String hasPhone=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
System.out.println("---------HAS Phone---------"+hasPhone);
ArrayList one= new ArrayList();
ArrayList two= new ArrayList();
// if(Boolean.parseBoolean(hasPhone)) {
Cursor phones=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+" = "+ contactId, null, null);
while(phones.moveToNext()) {
phoneNumber= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("---------Number---------"+phoneNumber);
one.add(phoneNumber);
System.out.println("---------email Address---------"+one);
} phones.close();
// }
Display Names
public class ContentProviderActivity extends Activity {
ListView lv;
Map<String, List<String>> mymap;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.listContact);
mymap = new HashMap<String, List<String>>();
Uri allContacts = Uri.parse("content://contacts/people/");
Cursor mCursor = managedQuery(allContacts, null, null, null, ContactsContract.Contacts._ID + " ASC");
final String[] contacts = new String[]{ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts._ID};
int [] view = new int[]{R.id.txtName,R.id.txtID};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.main, mCursor, contacts, view);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
//displayContacts(position+1);
int id1 = (int) adapter.getItemId(position);
Intent i = new Intent(getApplicationContext(),ShowContactNo.class);
i.putExtra("ID", id1);
startActivity(i);
}
});
}
}
ShowContactNo: TO display associated contact numbers
public class ShowContactNo extends ListActivity{
Map<String, List<String>> mymap;
String name;
List<String> Phone_No;
String select_Number;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mymap = new HashMap<String, List<String>>();
ListView listView = getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_NONE);
Intent i = getIntent();
int position = i.getIntExtra("ID", 0);
displayContacts(position);
Phone_No = new ArrayList<String>();
Phone_No = mymap.get(name);
System.out.println(Phone_No);
if(Phone_No!=null)
{
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, Phone_No));
}
final String [] items = new String [] {"Make Call", "Send Text SMS"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Option");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
if (item == 0) {
Intent i = new
Intent(android.content.Intent.ACTION_CALL,
Uri.parse("tel:"+select_Number));
startActivity(i);
dialog.cancel();
} else {
Intent i = new
Intent(android.content.Intent.ACTION_SENDTO,
Uri.parse("smsto:"+select_Number));
i.putExtra("sms_body", "Krishnakant Dalal");
startActivity(i);
}
}
} );
final AlertDialog dialog = builder.create();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
select_Number = String.valueOf(Phone_No.get(arg2));
dialog.show();
}
});
}
private void displayContacts(int position) {
if(position!=0)
{
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, ContactsContract.Contacts._ID +" = ?",
new String[]{String.valueOf(position)}, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
List<String> numberlist = new ArrayList<String>();
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Toast.makeText(this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
numberlist.add(phoneNo);
}
pCur.close();
mymap.put(name, numberlist);
}
}
}
}
}
}
Dont forget to add Permissions:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
Try this,
public void getPhoneNumber(String conatctname)
{
try
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
FirstName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if(FirstName!=null)
{
try
{
String[] splitval=FirstName.split(" ");
if(splitval.length>=1)
{
FirstName=splitval[0];
if(FirstName.equals(conatctname))
{
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{id}, null);
while (pCur.moveToNext())
{
PhoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
PhoneNumberArray.add(PhoneNumber);
}
pCur.close();
}
}
}
catch(Exception error)
{
Log.d("SplitError", error.getMessage());
}
}
cursor.close();
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
}

Multiple Contact Picker List [getCheckedItemPositions()]

Below is a my Contact_Picker class. I am going to be using this class to create a list of contacts with checkboxes, giving the user the option to select multiple contacts from their phonebook. I have a layout xml that I am using that has 2 buttons at the bottom: Clear All and Done.
When 'Done' is pressed, I need it to get all of the names that are checked, and save them in a list/preferences file. Right now, I can find what POSITIONS are checked, but I don't know how to retrieve the corresponding information associated with them (the name/phone number of the selected contact). I have searched for days on a method that will work, and have not come up with anything. Any code/pseudo code/ideas are greatly appreciated.
Contact_Picker Class:
public class Contact_Picker extends ListActivity {
protected static final String TAG = null;
public String[] Contacts = {};
public int[] to = {};
public ListView myListView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts_list);
final Button done_Button = (Button) findViewById(R.id.done_Button);
final Button clear_Button =(Button) findViewById(R.id.clear_Button);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, mCursor,
Contacts = new String[] {ContactsContract.Contacts.DISPLAY_NAME },
to = new int[] { android.R.id.text1 });
setListAdapter(adapter);
myListView = getListView();
myListView.setItemsCanFocus(false);
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
clear_Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Selections Cleared", Toast.LENGTH_SHORT).show();
ClearSelections();
}
});
/** When 'Done' Button Pushed: **/
done_Button.setOnClickListener(new View.OnClickListener() {
public void onClick (View v){
Log.i(TAG,":Done Button Selected:");
SparseBooleanArray checkedPositions = myListView.getCheckedItemPositions();
Log.i(TAG,"Number of Checked Positions: " + checkedPositions.size());
if (checkedPositions != null)
{
int count = myListView.getCount();
for ( int i=0;i<count;i++)
{
Log.i(TAG,"Selected items: " + checkedPositions.get(i));
}
}
}
}); //<-- End of Done_Button
} //<-- end of onCreate();
private void ClearSelections() {
int count = this.myListView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.myListView.setItemChecked(i, false);
}
}
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
} //<-- end of getContacts();
}
Will Create Output Such As:
Sele02-12 01:25:09.733: INFO/(219): :Done Button Selected:
02-12 01:25:09.743: INFO/(219): Number of Checked Positions: 2
02-12 01:25:09.743: INFO/(219): Selected items: true
02-12 01:25:09.743: INFO/(219): Selected items: false
02-12 01:25:09.743: INFO/(219): Selected items: true
02-12 01:25:09.752: INFO/(219): Selected items: false
see this
public String[] getlistcontacts() {
// TODO Auto-generated method stub
int i=0;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null, null, null);
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null , null);
int a= cur.getCount();
String[] cttlist=new String[a+1];
cur.moveToFirst();
pCur.moveToFirst();
for (int j=0; j<a;j++){
int nm=cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
//int nb=pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String name=cur.getString(nm);
int nb=pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number=pCur.getString(nb);
cttlist[i]=name.concat("<;>").concat(number);
//Toast.makeText(PizzastimeActivity.this, "alkamkljziha"+name+":"+number, Toast.LENGTH_LONG).show();
i++;
cur.moveToNext();
pCur.moveToNext();
}
return cttlist;
}
in this code i tried to get list of contact in a table of string then u can use it easily
Here is a correct approach:
SparseBooleanArray selectedPositions = listView.getCheckedItemPositions();
for (int i=0; i<selectedPositions.size(); i++) {
if (selectedPositions.get(selectedPositions.keyAt(i)) == true) {
//do stuff
}
}
maybe you can manually keep track of your contacts:
Vector<String> names=new Vector<String>();
private Cursor getContacts() {...
Cursor cur = managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
int col = cur.getColumnIndex("display_name");
while(cur.moveToNext())
names.add(cur.getString(col));
cur.moveToFirst();
return cur;
}
and then output them synchronously:
for ( int i=0;i<count;i++)
{
Log.i(TAG,"Selected items: " + checkedPositions.get(i));
Log.i(TAG,"Selected name: " + names.get(i));
}
I forgot about this post until Team Pannous left an answer. I'm sure that their method would work, but I ended up using this instead:
SparseBooleanArray checked = myListView.getCheckedItemPositions();
for (int i = 0; i < ContactsList.length; i++) {
Log.v(TAG, ContactsList[i] + ": " + checked.get(i)); //<-- Will print every contact with 'true'
if (checked.get(i) == true) {
Object o = getListAdapter().getItem(i);
String name = o.toString();
WriteSettings(self, name);
}
}
Just in case anyone else is having a problem with a multiple-choice listview.

Categories

Resources