I'm using "Calls.CONTENT_URI" content provider. I already retrived column names, but now i would like to get let's say, ALL names from column name "name" in this content provider.
I have code below:
uri = Calls.CONTENT_URI;
String[] projection = {"name"};
String selection = null;
String[] selectionArgs = null;
String sort = null;
resolver = getContentResolver();
cursor = resolver.query(uri, projection, selection, selectionArgs, sort);
Log.i("TUTORIAL", "counts :"+cursor.getCount());
String s;
cursor.moveToFirst();
for(int x=0; x<cursor.getCount(); x++){
s = cursor.getString(x);
Log.i("TUTORIAL", ""+s);
//cursor.moveToNext();
}
But this retrives only one name. I would like to have list of all names saved in my phone like:
John
Peter
Mark
Suzy
.
.
X
But now i got just one name like:
Peter.
Hope i've been clear enough.
What's the problem? Thanks for help in advance.
I think this would help you
ArrayList<String> nameList = new ArrayList<String>();
String[] projection = {"name"};
String selection = null;
String[] selectionArgs = null;
String sort = null;
resolver = getContentResolver();
cursor = resolver.query(uri, projection, selection, selectionArgs, sort);
Log.i("TUTORIAL", "counts :"+cursor.getCount());
String s;
if(cursor.moveToFirst()) {
do {
nameList.add(cursor.getString(0));
//your code
//s = cursor.getString(x);
Log.i("TUTORIAL", ""+cursor.getString(0));
}while(cursor.moveToNext());
}
you can try this one , it's working for me :
public void readContacts() {
Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Get contact id (id)
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
// Get contact name (displayName)
String displayName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
}
}
cur.close();
}
This is the code.
public class MainActivity extends AppCompatActivity {
SimpleCursorAdapter mAdapter;
MatrixCursor mMatrixCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// The contacts from the contacts content provider is stored in this cursor
mMatrixCursor = new MatrixCursor(new String[] { "_id","name","photo","details"} );
// Adapter to set data in the listview
mAdapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.lv_layout,
null,
new String[] { "name","photo","details"},
new int[] { R.id.tv_name,R.id.iv_photo,R.id.tv_details}, 0);
// Getting reference to listview
ListView lstContacts = (ListView) findViewById(R.id.lst_contacts);
// Setting the adapter to listview
lstContacts.setAdapter(mAdapter);
// Creating an AsyncTask object to retrieve and load listview with contacts
ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();
// Starting the AsyncTask process to retrieve and load listview with contacts
listViewContactsLoader.execute();
}
/** An AsyncTask class to retrieve and load listview with contacts */
private class ListViewContactsLoader extends AsyncTask<Void, Void, Cursor> {
#Override
protected Cursor doInBackground(Void... params) {
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
// Querying the table ContactsContract.Contacts to retrieve all the contacts
Cursor contactsCursor = getContentResolver().query(contactsUri, null, null, null,ContactsContract.Contacts.DISPLAY_NAME + " ASC ");
if(contactsCursor.moveToFirst()){
do{
long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID"));
Uri dataUri = ContactsContract.Data.CONTENT_URI;
// Querying the table ContactsContract.Data to retrieve individual items like
// home phone, mobile phone, work email etc corresponding to each contact
Cursor dataCursor = getContentResolver().query(dataUri, null,
ContactsContract.Data.CONTACT_ID + "=" + contactId,
null, null);
String displayName="";
String nickName="";
String homePhone="";
String mobilePhone="";
String workPhone="";
//String photoPath="" + R.drawable.blank;
byte[] photoByte=null;
String homeEmail="";
String workEmail="";
String companyName="";
String title="";
if(dataCursor.moveToFirst()){
// Getting Display Name
displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));
do{
// Getting NickName
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE))
nickName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
// Getting Phone numbers
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME :
homePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE :
mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK :
workPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
}
}
// Getting EMails
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE ) ) {
switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
case ContactsContract.CommonDataKinds.Email.TYPE_HOME :
homeEmail = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Email.TYPE_WORK :
workEmail = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
}
}
// Getting Organization details
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)){
companyName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
title = dataCursor.getString(dataCursor.getColumnIndex("data4"));
}
// Getting Photo
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)){
photoByte = dataCursor.getBlob(dataCursor.getColumnIndex("data15"));
if(photoByte != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the contact image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+contactId+".png");
// The FileOutputStream to the temporary file
try {
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Writing the bitmap to the temporary file as png file
bitmap.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
} catch (Exception e) {
e.printStackTrace();
}
// photoPath = tmpFile.getPath();
}
}
}while(dataCursor.moveToNext());
String details = "";
// Concatenating various information to single string
if(homePhone != null && !homePhone.equals("") )
details = "HomePhone : " + homePhone + "\n";
if(mobilePhone != null && !mobilePhone.equals("") )
details += "MobilePhone : " + mobilePhone + "\n";
if(workPhone != null && !workPhone.equals("") )
details += "WorkPhone : " + workPhone + "\n";
if(nickName != null && !nickName.equals("") )
details += "NickName : " + nickName + "\n";
if(homeEmail != null && !homeEmail.equals("") )
details += "HomeEmail : " + homeEmail + "\n";
if(workEmail != null && !workEmail.equals("") )
details += "WorkEmail : " + workEmail + "\n";
if(companyName != null && !companyName.equals("") )
details += "CompanyName : " + companyName + "\n";
if(title != null && !title.equals("") )
details += "Title : " + title + "\n";
// Adding id, display name, path to photo and other details to cursor
mMatrixCursor.addRow(new Object[]{ Long.toString(contactId),displayName,null,details});
}
}while(contactsCursor.moveToNext());
}
return mMatrixCursor;
}
#Override
protected void onPostExecute(Cursor result) {
// Setting the cursor containing contacts to listview
mAdapter.swapCursor(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Related
I am trying to sort music list by date, name, album, artist, duration and size after I click sort getting life cycle exception
Here is my code
Click action code
I am trying to sort songs by date added this function called.
after saving sorting type I have colsed the bottomsheet and recreate the activity using recreate funstion.
lv_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MPPreferenceManager.setString(MPConstants.SORTING, "sort_by_date");
bottomSheetDialog.dismiss();
MainActivity.this.recreate();
}
});
Sorting code is here
public static ArrayList<SongsModel> getAllAudio(Context context) {
String sortOrder = MPPreferenceManager.getString(MPConstants.SORTING, "");
ArrayList<String> duplicate = new ArrayList<>();
albums.clear();
ArrayList<SongsModel> songsModels = new ArrayList<>();
String order = null;
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Log.e(TAG, "getAllAudio: sort list: " + sortOrder );
switch (sortOrder){
case "sort_by_date":
order = MediaStore.MediaColumns.DATE_ADDED + " ASC" ;
break;
case "sort_by_name":
order = MediaStore.MediaColumns.TITLE + " ASC" ;
break;
case "sort_by_album":
order = MediaStore.MediaColumns.ARTIST + " ASC" ;
break;
case "sort_by_artist":
order = MediaStore.MediaColumns.DURATION + " ASC" ;
break;
case "sort_by_size":
order = MediaStore.MediaColumns.SIZE + " ASC" ;
break;
}
String[] projection = {
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
};
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, order);
if (cursor != null) {
while (cursor.moveToNext()) {
String album = cursor.getString(0);
String artist = cursor.getString(1);
String title = cursor.getString(2);
String duration = cursor.getString(3);
String path = cursor.getString(4);//path
SongsModel songsModel = new SongsModel(path, title, artist, album, duration);
songsModels.add(songsModel);
if (!duplicate.contains(album)) {
albums.add(songsModel);
duplicate.add(album);
}
}
cursor.close();
}
return songsModels;
}
Here is my sort list design
I have gone through a lot of posts but didn't find any answer that answers the question efficiently or even correctly. The closest I came was this How to avoid duplicate contact name (data ) while loading contact info to listview? but this has too much overhead. Is there any simpler or more efficient way to solve this?
I had the same problem you had: I was getting duplicate phone numbers. I solved this problem by obtaining the normalized number for each cursor entry and using a HashSet to keep track of which numbers I'd already found. Try this:
private void doSomethingForEachUniquePhoneNumber(Context context) {
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
//plus any other properties you wish to query
};
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null);
} catch (SecurityException e) {
//SecurityException can be thrown if we don't have the right permissions
}
if (cursor != null) {
try {
HashSet<String> normalizedNumbersAlreadyFound = new HashSet<>();
int indexOfNormalizedNumber = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER);
int indexOfDisplayName = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexOfDisplayNumber = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while (cursor.moveToNext()) {
String normalizedNumber = cursor.getString(indexOfNormalizedNumber);
if (normalizedNumbersAlreadyFound.add(normalizedNumber)) {
String displayName = cursor.getString(indexOfDisplayName);
String displayNumber = cursor.getString(indexOfDisplayNumber);
//haven't seen this number yet: do something with this contact!
} else {
//don't do anything with this contact because we've already found this number
}
}
} finally {
cursor.close();
}
}
}
After API 21 We Write this Query for remove contact duplicacy.
String select = ContactsContract.Data.HAS_PHONE_NUMBER + " != 0 AND " +
ContactsContract.Data.MIMETYPE
+ " = " + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "
AND "+ ContactsContract.Data.RAW_CONTACT_ID + " = " +
ContactsContract.Data.NAME_RAW_CONTACT_ID;
Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, select,
null, null);
ContentResolver cr = this.getContentResolver();
String[] FieldList = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
Cursor c = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,FieldList,
null,null,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String name,phone,ContactID;
HashSet<String> normalizedNumbers = new HashSet<>();
if(c!=null)
{
while(c.moveToNext()!=false)
{
phone = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));
if(normalizedNumbers.add(phone)==true)
{
name = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
ContactID = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
MyContacts m = new MyContacts(name,phone,ContactID);
ContactList.add(m);
}
}
c.close();
I am using Contact picker library for selecting multiple contacts but if a contact doesn't contain any number and if it is selected then it is showing some null pointer exception in the edit text field. How to remove that message and also how to remove trailing comma. Below is my Code.
try {
int pos = 0;
for (Contact contact : contacts) {
String displayName = contact.getDisplayName();
result.append(displayName + ",");
result.setSpan(new BulletSpan(15), pos, pos + displayName.length() + 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//pos += displayName.length() + 1;
}
}
catch (Exception e) {
result.append(e.getMessage());
}
contactsView.setText(result);
please try to check this code
void getAllContacts() {
ArrayList<String> nameList = new ArrayList<>();
ArrayList<String> numberList = new ArrayList<>();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER;
String[] list = new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.Contacts._ID};
Cursor cursor = getContentResolver().query(uri, list, selection, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
String contactNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
contactNuber.add(contactNumber);
contactsName.add(contactName);
nameList.add(contactName);
numberList.add(contactNumber);
} while (cursor.moveToNext());
cursor.close();
myContacts.put("name", nameList);
myContacts.put("number", numberList);
}
}
I search about read song in android and I see a code from you:
private static ArrayList<SongModel> LoadSongsFromCard() {
ArrayList<SongModel> songs = new ArrayList<SongModel>();
// Filter only mp3s, only those marked by the MediaStore to be music and longer than 1 minute
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0"
+ " AND " + MediaStore.Audio.Media.MIME_TYPE + "= 'audio/mpeg'"
+ " AND " + MediaStore.Audio.Media.DURATION + " > 60000";
final String[] projection = new String[] {
MediaStore.Audio.Media._ID, //0
MediaStore.Audio.Media.TITLE, //1
MediaStore.Audio.Media.ARTIST, //2
MediaStore.Audio.Media.DATA, //3
MediaStore.Audio.Media.DISPLAY_NAME
};
final String sortOrder = MediaStore.Audio.AudioColumns.TITLE
+ " COLLATE LOCALIZED ASC";
Cursor cursor = null;
try {
// the uri of the table that we want to query
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; //getContentUriForPath("");
// query the db
cursor = _context.getContentResolver().query(uri,
projection, selection, null, sortOrder);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
//if (cursor.getString(3).contains("AwesomePlaylists")) {
SongModel GSC = new SongModel();
GSC.ID = cursor.getLong(0);
GSC.songTitle = cursor.getString(1);
GSC.songArtist = cursor.getString(2);
GSC.path = cursor.getString(3);
// This code assumes genre is stored in the first letter of the song file name
String genreCodeString = cursor.getString(4).substring(0, 1);
if (!genreCodeString.isEmpty()) {
try {
GSC.genre = Short.parseShort(genreCodeString);
} catch (NumberFormatException ex) {
Random r = new Random();
GSC.genre = (short) r.nextInt(4);
} finally {
songs.add(GSC);
}
}
//}
cursor.moveToNext();
}
}
} catch (Exception ex) {
} finally {
if (cursor != null) {
cursor.close();
}
}
return songs;
}
I'm really learning to program for Android, and modify your code for what I needed , but I have trouble understanding when you assign cursor
cursor = _context.getContentResolver () query ( uri , projection , selection , null, sortOrder ) . ;
Part of _context not understand you kindly explain it please.
If your class extends activity you can use this for _context. If not, you need to pass the context from your activity. The first case mentioned would look like this:
// query the db
cursor = this.getContentResolver().query(uri, projection, selection, null, sortOrder);
__
What is Context in Android?
Actually I am using call logs as an input to database and then I am fetching it in a way that I can't get any duplicate values while displaying it and if i have any duplicate value in data base then it should be taken as integer value count. For example: john(6).
Here john must have entry 6 times in database. Don't get me wrong. I don't need a code.I need help. Here is code:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(android.provider.CallLog.Calls.CONTENT_URI,null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String rawContactId = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls._ID));
Cursor callLogCursor = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, new String[]{
android.provider.CallLog.Calls.CACHED_NAME,
android.provider.CallLog.Calls.CACHED_NUMBER_LABEL,
android.provider.CallLog.Calls.NUMBER,
android.provider.CallLog.Calls.DATE,
android.provider.CallLog.Calls.DURATION,
android.provider.CallLog.Calls.TYPE
},android.provider.CallLog.Calls._ID + "=?", new String[] { rawContactId }, null);;
if (callLogCursor != null) {
while (callLogCursor.moveToNext()) {
//String id = callLogCursor.getString(0);
String name = callLogCursor.getString(0);
String cacheNumber = callLogCursor.getString(1);
String number = callLogCursor.getString(2);
long dateTimeMillis = callLogCursor.getLong(3);
long durationMillis = callLogCursor.getLong(4);
int callType = callLogCursor.getInt(5);
String duration = getDuration(durationMillis * 1000);
String dateString = getDateTime(dateTimeMillis);
if (cacheNumber == null)
cacheNumber = number;
if (name == null)
name = "Unknown";
Uri image = null;
try {
String conId = fetchContactIdFromPhoneNumber(cacheNumber);
long contId = Long.parseLong(conId);
image = getPhotoUri(contId);
}catch(Exception e) {
Log.e("Exception", e.getMessage());
}
//CallLogModel callLogModel = new CallLogModel(image, name, cacheNumber,
// duration, dateString);
ContentValues values = new ContentValues();
values.put(NAME, name);
values.put(NUMBER, cacheNumber);
values.put(DATE, dateString);
values.put(DURATION,duration );
database.insert(CALL_LOG_TABLE, null, values);
Cursor cursor = database.query(CALL_LOG_TABLE, new String [] {LOG_ID, NAME, NUMBER, DATE, DURATION}, null, null, null, null, null);
int row =0;
if(!cursor.isAfterLast()) {
cursor.moveToFirst();
do{
int pId=cursor.getInt(0);
String pName = cursor.getString(1);
String pNumber = cursor.getString(2);
String pDate = cursor.getString(3);
String pDuration = cursor.getString(4);
int value = 0;
CallLogModel callLogModel = new CallLogModel(image, name, cacheNumber, duration, dateString);
if (callType == CallLog.Calls.OUTGOING_TYPE) {
for(int i=0;i<outgoingList.size();i++){
------------------------------Actually i want Logic here what should i do here--------------
}
}
outgoingList.add(callLogModel);
} else if (callType == CallLog.Calls.INCOMING_TYPE) {
incomingList.add(callLogModel);
} else if (callType == CallLog.Calls.MISSED_TYPE) {
missedcallList.add(callLogModel);
}
cursor.moveToNext();
} while (!cursor.isAfterLast());
}
}
callLogCursor.close();
}
}
You could model the outgoing calls in a hashmap, something like:
Map<String, Integer> outgoingCallsMap = new HashMap<String, Integer>();
for (int i = 0; i < outgoingList.size(); i++) {
String nameOfCallee = outgoingList.get(i);
if (!outgoingCallsMap.containsKey(nameOfCallee)) {
outgoingCallsMap.put(nameOfCallee, 1);
} else {
//Increment calls to this person
outgoingCallsMap.put(nameOfCallee, outgoingCallsMap.get(nameOfCallee) + 1);
}
}
Remove the duplicates in your outGoingList, by iterating it and putting the result to a map, with contact name as key and list of CallLogModel object as value.
You can refer this method.
private void convertToOutGoingMap(List<CallLogModel > outGoingList) {
HashMap<String,List<CallLogModel>> outGoingMap = new HashMap<String, List<CallLogModel>>();//map which has CallLogModel.name as key and List<CallLogModel> as value.
for(CallLogModel model : outGoingList){//Iterate thru the list.
if(outGoingMap.containsKey(model.name))
{
outGoingMap.get(model.name).add(model);//if map contains key, add model to the list.
} else {
List<CallLogModel> modelList = new ArrayList<CallLogModel>();//if it does not contains, initialize a list and add model to it.
modelList.add(model);
outGoingMap.put(model.name, modelList);
}
}
}
}
The key set of this map gives you the unique call log names and corresponding value list gives all occurrences and its size gives you number of occurrences.
Hope this help you.