Duplicated values in listview fetched from database - android

I have an incoming call history app. Every time I call it takes the number and save it in the database, after that it adds it to the list which in turn added to the listview. But I have one problem which is it never checks for old values and it adds duplicated numbers to the database, is there any way to avoid this? Here is my try.
public class Incoming_call_history extends Activity {
private ListView lv;
private ArrayAdapter<String> adapter;
private ArrayList<String>list;
DataSourceCall DS;
boolean duplicated=false;
String temp="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_incoming_call_history);
DS= new DataSourceCall(this);
DS.open();
lv=(ListView)findViewById(R.id.callHistory);
registerForContextMenu(lv);
list=(ArrayList<String>) DS.getAllCalls();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
#SuppressWarnings("deprecation")
Cursor mCursor = managedQuery(CallLog.Calls.CONTENT_URI, null, null,
null, null);
int number = mCursor.getColumnIndex(CallLog.Calls.NUMBER);
int date = mCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = mCursor.getColumnIndex(CallLog.Calls.DURATION);
int type = mCursor.getColumnIndex(CallLog.Calls.TYPE);
while (mCursor.moveToNext()) {
String num = mCursor.getString(number);
String dur = mCursor.getString(duration);
String datee = mCursor.getString(date);
String calltype = mCursor.getString(type);
Date d = new Date(Long.valueOf(datee));
String callTypeStr = "";
switch (Integer.parseInt(calltype)) {
case CallLog.Calls.MISSED_TYPE:
callTypeStr = "Missed";
break;
case CallLog.Calls.OUTGOING_TYPE:
callTypeStr = "Outgoing";
break;
case CallLog.Calls.INCOMING_TYPE:
callTypeStr = "Incoming";
break;
}
boolean found = false;
for (int ndx = 0; ndx < list.size(); ndx++)
{
if (num.equals(list.contains(num)))
{
found = true;
DS.deleteCall(num);
adapter.notifyDataSetChanged();
break;
}
}
if (!found)
{
DS.createCall(num);
temp=num;
Log.d("added succesfuly ", num);
}
// list.add("Phone number: "+num+"\n"+"Duration: " + dur+"\n"+"Type: " + callTypeStr+"\n"+"Call date: " + d+"\n");
}
mCursor.close();
adapter.notifyDataSetChanged();
}}

If you don't want to insert already inserted mobile number in the table,Just check whether the mobile number is already inserted not
public int isUserAvailable(int number)
{
int numberCount = 0;
Cursor c = null;
try
{
c = db.rawQuery("select p_number from user_table where p_number = ?", new String[] {String.valueOf(number)});
if(c.getCount() != 0)
numberCount = c.getCount();
}
catch(Exception e) {
e.printStackTrace();
} finally {
if(c!=null) c.close();
}
return numberCount ;
}
If it does not suits with your requirement let me know,I will try to give some other solution.

Related

How to get dual sim number call logs?

How to get dual sim number call logs in android. I followed below link to get the dual sim call logs but this method returns -1 always.
I tried other stackoverflow not much answers for dual sim call logs which is available from api 21.
https://stackoverflow.com/a/23907166/6891712
I have tried using the below method which give only the call details but not able to find that from which sim the call is dialed or received
private void getCalldetailsNow() {
#SuppressLint("MissingPermission") Cursor managedCursor=c.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, CallLog.Calls.DATE + " DESC");
int number = 0;
if (managedCursor != null) {
number = managedCursor.getColumnIndex( CallLog.Calls.NUMBER );
}
int duration1 = managedCursor.getColumnIndex( CallLog.Calls.DURATION);
int type1=managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date1=managedCursor.getColumnIndex(CallLog.Calls.DATE);
int idSimId = getSimIdColumn(managedCursor);
if( managedCursor.moveToFirst() == true ) {
String phNumber = managedCursor.getString(number);
String callDuration = managedCursor.getString(duration1);
String type=managedCursor.getString(type1);
String date=managedCursor.getString(date1);
String gettSimNumber=managedCursor.getString(idSimId);
String dir = null;
int dircode = Integer.parseInt(type);
switch (dircode)
{
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
default:
dir = "MISSED";
break;
}
}
managedCursor.close();
}
public static int getSimIdColumn(final Cursor c) {
for (String s : new String[] { "sim_id", "simid", "sub_id" }) {
int id = c.getColumnIndex(s);
if (id >= 0) {
Log.d(" Simmmm", "sim_id column found: " + s);
return id;
}
}
Log.d(" Simmmm", "no sim_id column found");
return -1;
}
Try this method to read sim card contact ..
if you want to read first device store contact then implement to implements LoaderManager.LoaderCallbacks into class..
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(),
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, ProfileQuery.PROJECTION,
// Select only email addresses
null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
List<String> numbers = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String phoneNumber = cursor.getString(ProfileQuery.NUMBER).replaceAll("\\D", "");
CustomLogHandler.printDebuglog(TAG, "onLoadFinished: " + phoneNumber);
if (!TextUtils.isEmpty(phoneNumber) && !phoneNumber.startsWith(Constants.SP_COUNTRY_CODE)) {
mCountryCodeList.add(new StringBuilder().append(Constants.SP_COUNTRY_CODE).toString());
alPhoneNumbers.add(new StringBuilder().append(Constants.SP_COUNTRY_CODE).append(phoneNumber).toString());
} else {
mCountryCodeList.add(new StringBuilder().append(Constants.SP_COUNTRY_CODE).toString());
alPhoneNumbers.add(phoneNumber);
}
names.add(cursor.getString(ProfileQuery.NAME));
cursor.moveToNext();
}
allPhoneNumberName.addAll(names);
}
this below class read sim card data..
private class ReadContactFromSIMCard extends AsyncTask<Object, Object, Object> {
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
requestForContact();
}
#Override
protected Object doInBackground(Object[] params) {
Cursor cursorSim = null;
try {
String phoneNo;
String name;
Uri simUri = Uri.parse("content://icc/adn");
cursorSim = getActivity().getContentResolver().query(simUri, null, null, null, null);
if (cursorSim != null) {
while (cursorSim.moveToNext()) {
name = cursorSim.getString(cursorSim.getColumnIndex("name"));
phoneNo = cursorSim.getString(cursorSim.getColumnIndex("number"));
if (!TextUtils.isEmpty(name)) {
allPhoneNumberName.add(name);
}
if (!TextUtils.isEmpty(phoneNo)) {
phoneNo.replaceAll("\\D", "");
phoneNo.replaceAll("&", "");
if (!TextUtils.isEmpty(phoneNo) && !phoneNo.startsWith(Constants.SP_COUNTRY_CODE)) {
mCountryCodeList.add(Constants.SP_COUNTRY_CODE);
alPhoneNumbers.add(Constants.SP_COUNTRY_CODE + phoneNo);
} else {
mCountryCodeList.add(Constants.SP_COUNTRY_CODE);
alPhoneNumbers.add(phoneNo);
}
}
}
}
} catch (Throwable e) {
CustomLogHandler.printErrorlog(e);
} finally {
if (cursorSim != null) {
cursorSim.close();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
getLoaderManager().initLoader(0, null, FindFriendsFragment.this);
}
}
get call log details...
private void getCallDetails() {
StringBuffer sb = new StringBuffer();
Uri contacts = CallLog.Calls.CONTENT_URI;
Cursor managedCursor = this.getContentResolver().query(contacts, null, null, null, null);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Details :");
while (managedCursor.moveToNext()) {
HashMap rowDataCall = new HashMap<String, String>();
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
String callDayTime = new Date(Long.valueOf(callDate)).toString();
// long timestamp = convertDateToTimestamp(callDayTime);
String callDuration = managedCursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- " + dir + " \nCall Date:--- " + callDayTime + " \nCall duration in sec :--- " + callDuration);
sb.append("\n----------------------------------");
Uri allCalls = Uri.parse("content://call_log/calls");
Cursor c = managedQuery(allCalls, null, null, null, null);
String id = c.getString(c.getColumnIndex(CallLog.Calls.PHONE_ACCOUNT_ID));
Log.d("sim",id);
}
managedCursor.close();
System.out.println(sb);
}
and i hope you add below permission into android manifest file ..
<uses-permission android:name="android.permission.READ_CALL_LOG" />
Maybe you can get subscription_id by get "Calls.PHONE_ACCOUNT_ID" item, which called "The identifier for the account used to place or receive the call."
And after you get the subscription_id, which is match slot id, for example, slot 0 is subscription_id 0, and slot id 1 is subscription_id 1, then you can getSlotIndex using giveb subid, then you can using this slotid to query calls from this slot or to this slot.

Display each row from Database on a new line in a TextView

I have created a database that stores all the correct values. I need for each row stored in the database to be displayed on a new line in one TextView.
Current Output
Current Output
After adding to database it adds on and updates current values instead of going to new line.
Required Output
Required Output
Each row from the database displayed on a new line in TextView
Insert data to database
public static void InsertOrUpdateRatingPoints(Context context, int point, SelfToSelfActivity.Rating activity) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
String[] projection = {ID, TIME, TYPE,};
String where = TYPE + " = ?";
String[] whereArgs = {String.valueOf(activity)};
String orderBy = TIME + " DESC";
Cursor cursor = db.query(TABLE_NAME, projection, where, whereArgs, null, null, orderBy);
boolean sameDay = false;
Date currentTime = Calendar.getInstance().getTime();
int StoredPoint = 0;
long lastStored = 0;
if (cursor != null) {
if (cursor.moveToFirst()) {
lastStored = cursor.getLong(cursor.getColumnIndex(TIME));
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sameDay = (sdf.format(new Date(lastStored))).equals(sdf.format(currentTime));
if (sameDay) StoredPoint = cursor.getInt(cursor.getColumnIndex(POINT));
}
cursor.close();
}
ContentValues cv = new ContentValues();
cv.put(POINT, point + StoredPoint);
if (sameDay) {
db.update(TABLE_NAME, cv, TIME + " = ?", new String[]{String.valueOf(lastStored)});
} else {
cv.put(TYPE, activity.ordinal());
cv.put(TIME, currentTime.getTime());
cv.put(POINT, point);
db.insert(TABLE_NAME, null, cv);
}
}
Execute
public void execute() {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
Cursor c = TrackerDb.getStoredItems(getApplicationContext());
if (c != null) {
if (c.moveToFirst()) {
WorkoutDetails details = null;
do {
WorkoutDetails temp = getWorkoutFromCursor(c);
if (details == null) {
details = temp;
continue;
}
if (isSameDay(details.getWorkoutDate(), temp.getWorkoutDate())) {
if (DBG) Log.d(LOG_TAG, "isSameDay().. true");
details.add(temp);
} else {
mWorkoutDetailsList.add(details);
details = temp;
}
} while (c.moveToNext());
if (details != null) mWorkoutDetailsList.add(details);
if (DBG)
Log.d(LOG_TAG, "AsyncTask: list size " + mWorkoutDetailsList.size());
runOnUiThread(new Runnable() {
#Override
public void run() {
mWorkoutsAdapter.updateList(mWorkoutDetailsList);
//AVG_THIRTY.setText(String.valueOf(EmotionListAdapter.thirtyday));
//Today_Score.setText(String.valueOf(EmotionListAdapter.day));
}
});
}
c.close();
}
}
});
}
Display Data
#Override
public void onBindViewHolder(RatingListViewHolder holder, int position)
{
WorkoutDetails details = mWorkoutsList.get(position);
holder.textSTS.setText(String.valueOf(totalSTS));
holder.textLoss.setText(String.valueOf(details.getPoints(SelfToSelfActivity.Rating.LOSS)));
holder.textRateLoss.setText(String.valueOf(details.getPoints(SelfToSelfActivity.Rating.RATELOSS)));
}
I assume you want to display every item of ArrayList in separate lines.
Try this, hope this help.
TextView conciergeServicesTv = (TextView) findViewById(R.id.activity_get_quote_final_concierge_services_tv);
if (arrayListConciergeServices.size() != 0) { //ArrayList you are receiving\\
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < arrayListConciergeServices.size(); i++) {
if (i == arrayListConciergeServices.size() - 1) {
stringBuilder.append(arrayListConciergeServices.get(i));
} else {
stringBuilder.append(arrayListConciergeServices.get(i)).append("\n");
}
}
conciergeServicesTv.setText(stringBuilder);
} else {
conciergeServicesTv.setText("No concierge services selected");
}

ClearCallLog not updating listview

I am a school student learning android. I am doing a simple contacts app! When i click on clear calllog button, my recent contacts listview remains the same. Its not getting cleared. But when i close the app and reopen again, the recent contacts fragment is getting cleared! I debugged the code, code is not entering after cursor.movetoNext() line when i click on clearcall log. Kindly help me techies!
I programmed like updateFragment2ListView() gets called when i clear the call log button in menu!
public class RecentContacts extends Fragment {
HashMap contactMap = new HashMap();
View rootView;
RecentAdapter rr;
ListView list;
private static final int PERMISSIONS_REQUEST_READ_CALLLOG = 100;
Cursor cursor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_recent_contacts, container, false);
list = (ListView) rootView.findViewById(R.id.customlist);
getRecentContacts();
rr = new RecentAdapter(contactMap, getActivity());
list.setAdapter(rr);
return rootView;
}
public void updateFragment2ListView() {
getRecentContacts();
rr.notifyDataSetChanged();
list.setAdapter(rr);
System.out.println("Fragment recent updated-updateFragment2listview");
}
#Override
public void onResume() {
getRecentContacts();
rr.notifyDataSetChanged();
System.out.println("Fragment recent updated- onresume");
super.onResume();
}
#Override
public void onStart() {
System.out.println("Fragment recent onstart");
super.onStart();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
void getRecentContacts() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && getContext().checkSelfPermission(Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CALL_LOG}, PERMISSIONS_REQUEST_READ_CALLLOG);
//After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
System.out.println("Security check ok");
} else {
System.out.println("Entered recent onstart");
int i=0;
Uri queryUri = android.provider.CallLog.Calls.CONTENT_URI;
String[] projection = new String[]{
ContactsContract.Contacts._ID,
CallLog.Calls._ID,
CallLog.Calls.NUMBER,
CallLog.Calls.CACHED_NAME,
CallLog.Calls.DATE,
CallLog.Calls.TYPE};
String sortOrder = String.format("%s limit 500 ", CallLog.Calls.DATE + " DESC");
try {
System.out.println("Entering cursor in recent contacts");
cursor = getActivity().getContentResolver().query(queryUri, projection, null, null, sortOrder);
System.out.println("Entered cursor in recent contacts");
} catch (SecurityException e) {
Log.e("", "");
}
while (cursor.moveToNext()) {
System.out.println("Entered cursor.movetoNext recent contacts");
String phoneNumber = cursor.getString(cursor
.getColumnIndex(CallLog.Calls.NUMBER));
System.out.println("Entered phone number in recent contacts");
String title = (cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME)));
int duration1 = cursor.getColumnIndex(CallLog.Calls.DURATION);
System.out.println("Duration" + duration1);
System.out.println("Entered duration in recent contacts");
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
String callDate = cursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
System.out.println("Call Date" + callDayTime);
int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
String callType = cursor.getString(type);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
System.out.println("Call type" + dir);
// if (phoneNumber == null || title == null) continue;
String uri = "tel:" + phoneNumber;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
String intentUriString = intent.toUri(0);
contactMap.put(i, new RecentPojo(title, phoneNumber, duration1, false, callDayTime, dir));
// Toast.makeText(this,title,Toast.LENGTH_SHORT).show();
i++;
}
cursor.close();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if ((requestCode == PERMISSIONS_REQUEST_READ_CALLLOG)) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted
System.out.println("");
getRecentContacts();
} else {
Toast.makeText(getContext(), "Until you grant the permission, we cannot display the names", Toast.LENGTH_SHORT).show();
}
}
}
}
You have to call rr.notifyDataSetChanged(); when you clear it so the ListView is refreshed.

How to display the duplicate phone number from call log ,contact list and inbox in android

I want to retrieve the phone number from the call log, contact list and inbox to compare that number to a list and display it only once in a listview.
I'm able to get contacts from call log, contact list and inbox but the problem is that I'm not able to compare the number from call log and the contact list because they are stored in a different format.
My question is how can I compare both numbers regardless of their formating?
Current code is as follows:
public class MainActivity extends Activity {
TextView textView = null;
ArrayList<String> call_log_no;
ArrayList<String> call_log_name;
String strStatus = "";
public boolean[] status;
StringBuffer sb;
String phNum,cname,details;
MatrixCursor mMatrixCursor;
ArrayList<String> choiceList;
ListView lvCountries;
HashMap<String,Object> hm;
int pos;
List<HashMap<String,Object>> aList = new ArrayList<HashMap<String,Object>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
/** Restore from the previous state if exists */
if(savedInstanceState!=null){
status = savedInstanceState.getBooleanArray("status");
}
call_log_no = new ArrayList<String>();
call_log_name = new ArrayList<String>();
choiceList = new ArrayList<String>();
lvCountries = (ListView) findViewById(R.id.lv_countries);
OnItemClickListener itemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> lv, View item, int position, long id) {
ListView lView = (ListView) lv;
SimpleAdapter adapter = (SimpleAdapter) lView.getAdapter();
HashMap<String,Object> hm = (HashMap) adapter.getItem(position);
/** The clicked Item in the ListView */
RelativeLayout rLayout = (RelativeLayout) item;
/** Getting the toggle button corresponding to the clicked item */
ToggleButton tgl = (ToggleButton) rLayout.getChildAt(0);
String strStatus = "";
if(tgl.isChecked()){
tgl.setChecked(false);
strStatus = "Off";
status[position]=false;
}else{
tgl.setChecked(true);
strStatus = "On";
status[position]=true;
}
Toast.makeText(getBaseContext(), (String) hm.get("no") + " : " + strStatus, Toast.LENGTH_SHORT).show();
}
};
lvCountries.setOnItemClickListener(itemClickListener);
// Each row in the list stores country name and its status
List<HashMap<String,Object>> aList = new ArrayList<HashMap<String,Object>>();
// The contacts from the contacts content provider is stored in this cursor
mMatrixCursor = new MatrixCursor(new String[] { "_id","name","details"} );
getCallDetails();
//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 homePhone="";
String mobilePhone="";
String workPhone="";
if(dataCursor.moveToFirst()){
// Getting Display Name
displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));
do{
// Getting NickName
// 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"));
boolean isStringExists = (call_log_no.contains(homePhone)||(call_log_no.contains("+91"+homePhone)));
if(isStringExists==true)
{
}
else{
call_log_no.add(homePhone);
call_log_name.add(displayName);
}
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE :
mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
boolean isStringE = (call_log_no.contains(mobilePhone)||(call_log_no.contains("+91"+mobilePhone)));
if(isStringE==true)
{
}
else{
call_log_no.add(mobilePhone);
call_log_name.add(displayName);
}
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK :
workPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
boolean isStringExis = (call_log_no.contains(workPhone)||(call_log_no.contains("+91"+workPhone)));
if(isStringExis==true)
{
}
else{
call_log_no.add(workPhone);
call_log_name.add(displayName);
}
break;
}
}
}while(dataCursor.moveToNext());
String details = "";
// Adding id, display name, path to photo and other details to cursor
mMatrixCursor.addRow(new Object[]{ Long.toString(contactId),displayName,details});
}
}while(contactsCursor.moveToNext());
}
return mMatrixCursor;
}
#Override
protected void onPostExecute(Cursor result) {
status = new boolean[call_log_name.size()];
for(int i = 0,j = 0,k=0; i < call_log_name.size() ; i++,j++,k++)
{
HashMap<String, Object> hm = new HashMap<String,Object>();
status[k]=false;
// choiceList.add("\nName: "+call_log_name.get(i)+"\nPhone Number: " + call_log_no.get(j));
hm.put("no", call_log_no.get(i));
hm.put("txt", call_log_name.get(j));
hm.put("stat",status[k]);
aList.add(hm);
}
// Keys used in Hashmap
String[] from = {"txt","no","stat" };
// Ids of views in listview_layout
int[] to = {R.id.tv_item,R.id.tv_no, R.id.tgl_status};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.activity_main, from, to);
lvCountries.setAdapter(adapter);
}
}
private void getCallDetails() {
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
/* Query the CallLog Content Provider */
Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,
null, null, strOrder);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
int name= managedCursor.getColumnIndex(CallLog.Calls.CACHED_NAME);
while (managedCursor.moveToNext()) {
phNum = managedCursor.getString(number);
String callTypeCode = managedCursor.getString(type);
String strcallDate = managedCursor.getString(date);
Date callDate = new Date(Long.valueOf(strcallDate));
String callDuration = managedCursor.getString(duration);
cname=managedCursor.getString(name);
String callType = null;
int callcode = Integer.parseInt(callTypeCode);
switch (callcode) {
case CallLog.Calls.OUTGOING_TYPE:
callType = "Outgoing";
break;
case CallLog.Calls.INCOMING_TYPE:
callType = "Incoming";
break;
case CallLog.Calls.MISSED_TYPE:
callType = "Missed";
break;
}
boolean isStringExists = (call_log_no.contains(phNum)|| (call_log_no.contains("+91"+phNum)));
if(isStringExists==true)
{
}
else{
call_log_no.add(phNum);
call_log_name.add(cname);
} }
managedCursor.close();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBooleanArray("status", status);
}
}
please help me...
You can achieve what you want using the following library libphoneNumber
which has a method called isNumberMatch which takes into consideration the country code. example :
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumberUtil.MatchType match = phoneUtil.isNumberMatch(firstNumber, secondNumber);
if(match.name().equals("NSN_MATCH")){
//Its a match!
}

How to get Distinct list of Call log with descending order of date in android using Treeset

In my application, i just want call log with distinct and sorted with descending of date. I tried below code and not getting exact result
my code as follows
public class MainActivity extends Activity {
// List<CLogItem> clogitems = new ArrayList<CLogItem>();
Set clogitems = new TreeSet();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v){
getCallDetails(this);
TextView tv1 = (TextView)findViewById(R.id.tv1);
String str = "";
Iterator sitr=clogitems.iterator();
while(sitr.hasNext())
{
CLogItem clitem=(CLogItem) sitr.next();
str = str + "P: " + clitem.No + "\n";
str = str + "N: " + clitem.Name + "\n";
str = str + "--------------------------------------------\n";
}
tv1.setText(str);
}
private void getCallDetails(Context context) {
StringBuffer stringBuffer = new StringBuffer();
Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
null, null, null, CallLog.Calls.DATE + " DESC");
int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
int iname = cursor.getColumnIndex(CallLog.Calls.CACHED_NAME);
while (cursor.moveToNext()) {
CLogItem clitem = new CLogItem();
clitem.No = cursor.getString(number);
clitem.Name = cursor.getString(iname);
clitem.lDate = Long.valueOf(cursor.getString(date));
clogitems.add(clitem);
}
cursor.close();
}
public static class CLogItem implements Comparable {
String No;
String Name;
long lDate;
public CLogItem(){
this.No = "";
this.Name = "";
this.lDate = 0;
}
#Override
public int compareTo(Object arg0) {
CLogItem l = (CLogItem)arg0;
int fnResult = this.No.compareTo(l.No);
if( fnResult == 0 ){
if (lDate > l.lDate) {
return -1;
}
else if (lDate < l.lDate) {
return 1;
}
else {
return 0;
}
}
return fnResult;
}
}
}
please help me to sort out this issue
thanks in advance
Finally i got a correct solution.
private void getCallDetails(Context context) {
StringBuffer stringBuffer = new StringBuffer();
Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
null, null, null, CallLog.Calls.NUMBER + "," + CallLog.Calls.DATE + " DESC");
int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
int iname = cursor.getColumnIndex(CallLog.Calls.CACHED_NAME);
String curNo = "";
while (cursor.moveToNext()) {
String No = cursor.getString(number);
if( !No.equalsIgnoreCase(curNo) ){
CLogItem clitem = new CLogItem();
clitem.No = cursor.getString(number);
clitem.Name = cursor.getString(iname);
clitem.lDate = Long.valueOf(cursor.getString(date));
clogitems.add(clitem);
curNo = No;
}
}
cursor.close();
Collections.sort(clogitems);
}
Can't we achive this using GROUP BY while querying itself. Because in this case we should get all the values and then checking the possibilities. If I want to get the top 2 distinct items,still i need to get all the values.So,I think GROUP BY will help..

Categories

Resources