Delete call log in android for particular number - java

I am trying to delete all call logs of particular number.
try {
String strNumberOne[] = {number};
Cursor cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, CallLog.Calls.NUMBER + "=? ", strNumberOne, "");
boolean bol = cursor.moveToFirst();
if (bol) {
do {
int idOfRowToDelete = cursor.getInt(cursor.getColumnIndex(CallLog.Calls._ID));
getContentResolver().delete(Uri.withAppendedPath(CallLog.Calls.CONTENT_URI, String.valueOf(idOfRowToDelete)), "", null);
} while (cursor.moveToNext());
}
} catch (Exception ex) {
System.out.print("Exception here ");
}
I want to fire a LIKE query, because the mobNum saved in callLog is +916666666666 and i am passing number 6666666666. so its not matching. can anybody help me to overcome this issue?

Try this code to delete any particular number from history
String number="4666";//any number
Uri CALLLOG_URI = Uri.parse("content://call_log/calls");
context.getContentResolver().delete(CALLLOG_URI,CallLog.Calls.NUMBER +"=?",new String[]{number});
you can also delete call log by user name by doing this
context.getContentResolver().delete(CALLLOG_URI,CallLog.Calls.CACHED_NAME +"=?",new String[]{name});

Check the following links:
Call log deletion in Android
SO: Delete call from call log after call end

Related

Java unique code generation failed while calling the recurring function

We have to implement a logic to write the unique code generation in Java. The concept is when we generate the code the system will check if the code is already generate or not. If already generate the system create new code and check again. But this logic fails in some case and we cannot able to identify what is the issue is
Here is the code to create the unique code
Integer code = null;
try {
int max = 999999;
int min = 100000;
code = (int) Math.round(Math.random() * (max - min + 1) + min);
PreOrders preObj = null;
preObj = WebServiceDao.getInstance().preOrderObj(code.toString());
if (preObj != null) {
createCode();
}
} catch (Exception e) {
exceptionCaught();
e.printStackTrace();
log.error("Exception in method createCode() - " + e.toString());
}
return code;
}
The function preOrderObj is calling a function to check the code exists in the database if exists return the object. We are using Hibernate to map the database functions and Mysql on the backend.
Here is the function preOrderObj
PreOrders preOrderObj = null;
List<PreOrders> preOrderList = null;
SessionFactory sessionFactory =
(SessionFactory) ServletActionContext.getServletContext().getAttribute(HibernateListener.KEY_NAME);
Session Hibernatesession = sessionFactory.openSession();
try {
Hibernatesession.beginTransaction();
preOrderList = Hibernatesession.createCriteria(PreOrders.class).add(Restrictions.eq("code", code)).list(); // removed .add(Restrictions.eq("status", true))
if (!preOrderList.isEmpty()) {
preOrderObj = (PreOrders) preOrderList.iterator().next();
}
Hibernatesession.getTransaction().commit();
Hibernatesession.flush();
} catch (Exception e) {
Hibernatesession.getTransaction().rollback();
log.debug("This is my debug message.");
log.info("This is my info message.");
log.warn("This is my warn message.");
log.error("This is my error message.");
log.fatal("Fatal error " + e.getStackTrace().toString());
} finally {
Hibernatesession.close();
}
return preOrderObj;
}
Please guide us to identify the issue.
In createCode method, when the random code generated already exist in database, you try to call createCode again. However, the return value from the recursive call is not updated to the code variable, hence the colliding code is still returned and cause error.
To fix the problem, update the method as
...
if (preObj != null) {
//createCode();
code = createCode();
}
...
Such that the code is updated.
By the way, using random number to generate unique value and test uniqueness through query is a bit strange. You may try Auto Increment if you want unique value.

fi.foyt.foursquare.api.FoursquareApiException: org.json.JSONException: JSONObject["icon"] not a string

I am taking the foursquare sample java code and the same sample values from git and running in my local machine, but getting the following exception.
Here is my code:
String ll = args.length > 0 ? args[0] : "44.3,37.2";
try {
FourSquareSampleMain fourSquareSample = new FourSquareSampleMain();
fourSquareSample.searchVenues(ll);
} catch (FoursquareApiException e) {
// TODO: Error handling
e.printStackTrace();
}
}
public void searchVenues(String ll) throws FoursquareApiException {
// First we need a initialize FoursquareApi.
FoursquareApi foursquareApi = new FoursquareApi("CLIENT_ID",
"CLIENT_SECRET", null);
// After client has been initialized we can make queries.
Result<VenuesSearchResult> result = foursquareApi.venuesSearch(ll, null, null, null, null, null, null, null,
null, null, null, null, null);
if (result.getMeta().getCode() == 200) {
CompactVenue[] venueList = result.getResult().getVenues();
System.out.println("Compact Venue List size : " + venueList.length);
// if query was ok we can finally we do something with the data
for (CompactVenue venue : venueList) {
// TODO: Do something we the data
System.out.println("Venue Name : " + venue.getName());
}
System.out.println("End of IF Loop: ");
} else {
// TODO: Proper error handling
System.out.println("Error occured: ");
System.out.println(" code: " + result.getMeta().getCode());
System.out.println(" type: " + result.getMeta().getErrorType());
System.out.println(" detail: " + result.getMeta().getErrorDetail());
}
}
The size of the venueList is always "0", but when I debugged it , it throws the below exception:
"org.eclipse.debug.core.DebugException: com.sun.jdi.ClassNotLoadedException: Type has not been loaded occurred while retrieving component type of array."
But strange when I changed the latitude and longitude value,
String ll = "-33.883056 , 151.216667";// latlong surry hills sydney
I get the below exception:
fi.foyt.foursquare.api.FoursquareApiException: org.json.JSONException: JSONObject["icon"] not a string.
at fi.foyt.foursquare.api.JSONFieldParser.parseEntity(JSONFieldParser.java:143)
at fi.foyt.foursquare.api.JSONFieldParser.parseValue(JSONFieldParser.java:194)
at fi.foyt.foursquare.api.JSONFieldParser.parseEntity(JSONFieldParser.java:141)
at fi.foyt.foursquare.api.JSONFieldParser.parseEntities(JSONFieldParser.java:57)
at fi.foyt.foursquare.api.FoursquareApi.venuesSearch(FoursquareApi.java:1017)
at FourSquareSampleMain.searchVenues(FourSquareSampleMain.java:57)
at FourSquareSampleMain.main(FourSquareSampleMain.java:43)
Caused by: org.json.JSONException: JSONObject["icon"] not a string.
at org.json.JSONObject.getString(JSONObject.java:658)
at fi.foyt.foursquare.api.JSONFieldParser.parseValue(JSONFieldParser.java:202)
at fi.foyt.foursquare.api.JSONFieldParser.parseEntity(JSONFieldParser.java:141)
What am I missing here? please suggest.
I found a workaround for that. It's a patch, but it works. Details:
Info was taken from this post where same issue was identified and fixed
Take a look that diff that resolve the issue: https://github.com/wallabyfinancial/foursquare-api-java/compare/master...ganchix:master
Copy those 3 raw classes (Category, GeoCodeFeature and Icon) as they are and add them into your porject under the package fi.foyt.foursquare.api.entities and that's it
Note 1: when you replace classes (same package and class name) in yur project, the clasloader will use yours instead of the classes provided by the jar dependency, so, there is a quick fix.
I did that and it worked like a charm
Note 2: As soon as the sdk is updated, you should remove this patch and upgrade the sdk dependency
Hope it helps

Max 20 Friends Information on Twitter4J

Like you see in this code, I want to get all the information about friends in twitter, people I follow.
But doing this :
PagableResponseList<User> users = twitter.getFriendsList(USER_ID, CURSOR);
... only gives me the first 20 recent friends... What can I do?
Complete code about it :
PagableResponseList<User> users = twitter.getFriendsList(USER_ID, CURSOR);
User user = null;
max = users.size();
System.out.println("Following: "+max);
for (int i = 0 ; i < users.size() ; i++){
user = users.get(i);
System.out.print("\nID: "+user.getId()+" / User: "+user.getName()+" /");
System.out.print("\nFollowers: "+user.getFollowersCount()+"\n");
tid.add(Long.parseLong(String.valueOf(user.getId())));
tusername.add(user.getName());
tfollowers.add(Long.parseLong(String.valueOf(user.getFollowersCount())));
tname.add(user.getScreenName());
}
Thanks..
you can try this code to get the list of people you follow.
long cursor = -1;
PagableResponseList<User> users;
while ((cursor = followers.getNextCursor()) != 0);
{
users = twitter.getFriendsList(userId, cursor);
}
I've taken a peek at the documentation at Twitter4J and Twitter themselves and it's all about that cursor.
To prevent you're getting loaded with a whole bunch of friends at once, Twitter only returns the first 20 results. It doesn't return just the first 20 results, but it also returns a cursor. That cursor is just a random number that's managed by Twitter. When you make a call again and pass this cursor, the next 20 entries (friends) will be returned, again with a cursor that's different now. You can repeat this until the cursor returned is zero. That means there are no more entries available.
In case you want to know more, check these two links: Twitter DEV and Twitter4J documentation.
Concerning your Java, you just need to find a way to get the current cursor, and pass that cursor to your method again, making the app load the next 20 entries. According to this piece of information, that should do the trick.
List<User> allUsers = new ArrayList<User>();
PagableResponseList<User> users;
long cursor = -1;
while (cursor != 0) {
users = twitter.getFriendsList(USER_ID, cursor);
cursor = users.getNextCursor();
allUsers.add(users);
}
You should be able to request up to 200 results at a time:
final PagableResponseList<User> users = twitter.getFriendsList(USER_ID, cursor, 200);
cursor = users.getNextCursor();
If you need to start from where you left off between invocations of your program then you need to store the value of cursor somewhere.
Improvements to Sander's answer!
You can set a count value to the getFriendsList method as in Jonathan's Answer. The maximum value allowed for count is 200. The loop construct will help to collect more than 200 friends now. 200 friends per page or per iteration!
Yet, there are rate limits for any request you make. The getFriendsList method will use this api endpoint: GET friends/list which has a rate limit of 15 hits per 15 minutes. Each hit can fetch a maximum of 200 friends which equates to a total of 3000 friends (15 x 200 = 3000) per 15 minutes. So, there will be no problem if you have only 3000 friends. If you have more than 3000 friends, an exception will be thrown. You can use the RateLimitStatus class to avoid that exception. The following code is an example implementation to achieve this.
Method 1: fetchFriends(long userId)
public List<User> fetchFriends(long userId) {
List<User> friends = new ArrayList<User>();
PagableResponseList<User> page;
long cursor = -1;
try {
while (cursor != 0) {
page = twitter.getFriendsList(userId, cursor, 200);
friends.addAll(page);
System.out.println("Total number of friends fetched so far: " + friends.size());
cursor = page.getNextCursor();
this.handleRateLimit(page.getRateLimitStatus());
}
} catch (TwitterException e) {
e.printStackTrace();
}
return friends;
}
Method 2: handleRateLimit(RateLimitStatus rls)
private void handleRateLimit(RateLimitStatus rls) {
int remaining = rls.getRemaining();
System.out.println("Rate Limit Remaining: " + remaining);
if (remaining == 0) {
int resetTime = rls.getSecondsUntilReset() + 5;
int sleep = (resetTime * 1000);
try {
if(sleep > 0) {
System.out.println("Rate Limit Exceeded. Sleep for " + (sleep / 1000) + " seconds..");
Thread.sleep(sleep);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
By doing so, your program will sleep for some time period based on the rate limiting threshold. It will continue to run from where it left after the sleep. This way we can avoid our program stopping in the midway of collecting friends counting more than 3000.
I have the solution to my post... thanks to Sander, give me some ideas...
The thing was change the for to while ((CURSOR = ids.getNextCursor()) != 0);.
And... user = twitter.showUser(id);
Playing with showUser makes it possible to get, with a slowly time, all the info about all my friends...
That's all. Don't use user.get(i);

LDAP Not processing showing SchemaViolationException

I am having a LDAP Queue which process a object class.I cant find the exact location why it is giving the exception. The objclass is a concadenation string with pipe symbol. Any program coding to find the exact location in which concadination part is going to the Exception?.Please Assist.
try {
Attributes objClass = null;
try {
objClass = getObjClass(LdapInfo.PER_ID, person.perId);
} catch (NamingException e)
{
DCXError.myInstance().writeError("LdapUpdaterConnection: " + e.getMessage());
}
NamingEnumeration oc = objClass.get("objectclass").getAll();
String baseObjClass = null;
while (oc.hasMoreElements()) {
baseObjClass = (String) oc.nextElement();
if (baseObjClass.equalsIgnoreCase(LdapInfo.NON_EMPLOYEE_PERSON)
|| baseObjClass.equalsIgnoreCase("N/A")||
baseObjClass.equalsIgnoreCase(LdapInfo.EMPLOYEE_PERSON))
break;
}
} catch (SchemaViolationException e4) {
DCXError.myInstance().writeError(
"LdapUpdaterConnection:doUpdate SchemaViolationException "+ e4.getExplanation());
DCXError.myInstance().writeError("LdapUpdaterConnection:update persID = " + personId);
return (LdapUpdaterConnection.BAD_DATA);
}
You can't find the exact location only because you haven't logged the stack trace. You would also need to reformat your code so that each statement is on a separate line to make any use of that information. You should also use variable names that actually correspond to the content.
This is really terrible code.
It's also hard to see why you are doing all this in the first place. A decent query filter would do all that for you far more simply.

Update doesn't work when using ContentResolver to update Contact Groups

I have this code for update:
public Boolean update() {
try {
data.put(ContactsContract.Groups.SHOULD_SYNC, true);
ContentResolver cr = ctx.getContentResolver();
Uri uri = ContentUris.withAppendedId(ContactsContract.Groups.CONTENT_URI, Long.parseLong(getId()));
int mid = cr.update(uri, data,_ID+"="+getId(), null);
// notify registered observers that a row was updated
ctx.getContentResolver().notifyChange(
ContactsContract.Groups.CONTENT_URI, null);
if (-1 == mid)
return false;
return true;
} catch (Exception e) {
Log.v(TAG(), e.getMessage(), e);
return false;
}
}
I have values in data, I double checked, and for some reason the values are nut pushed out. I also ran a cur.requery(); and I am having
<uses-permission android:name="android.permission.WRITE_CONTACTS"></uses-permission>
EDIT 1
One thing to mention, that I need to use:
data.put(ContactsContract.Groups.SHOULD_SYNC, 1);
as the true value there is not accepted, although that is returned when you check the ContentValues.
Ok, I figured it down too:
SQLiteException: no such column: res_package: , while compiling: UPDATE groups SET sync4=?, sync3=?, sync2=?, group_visible=?, system_id=?, sync1=?, should_sync=?, deleted=?, account_name=?, version=?, title=?, title_res=?, _id=?, res_package=?, sourceid=?, dirty=?, notes=?, account_type=? WHERE _id=20
The weird thing is that, this column is returned when you Query the content provider. I made the queries to use all returned columns, so I need to make this work somehow.
I just made something similar work. Instead of
int mid = cr.update(uri, data,_ID+"="+getId(), null);
use
int mid = cr.update(uri, data,null, null)
your uri already has embedded ID information.

Categories