Contact Storage is not cleared after deleting the account - android

I'm writing service to sync contacts with my web service.
I add my account via Account settings. Then I sync it with my web service. Everything is OK. There are no any account on my device before I add my custom account. And Contact Storage app on device has "Data" value as 0.00B.
After syncing, all my contacts appears in Contacts app. Contact Storage app no has "Data" value as 4.53Mb.
Then I remove my account from my device. Contact Storage app now shows "Data" value as 3.74Mb.
After that I re add my account and start to sync it again. After sync if finished, Contact Storage app shows "Data" value ad 7.90Mb.
If I repeat previous steps Contact Storage app "Data" value continues growing.
So why is that? Seems like avatars which I download from my web service doesn't get clean.
How to remove them when I remove my account?
I add avatars like that:
public ContactOperations addAvatar(String avatarUrl) {
contentValues.clear();
if (!TextUtils.isEmpty(avatarUrl)) {
try {
byte[] avatar = NetworkUtils.downloadAvatar(avatarUrl);
byte[] resizedAvatar = resizeBitmap(avatar);
avatar = null;
contentValues.put(Photo.PHOTO, resizedAvatar);
contentValues.put(Photo.MIMETYPE, Photo.CONTENT_ITEM_TYPE);
addInsertOperation();
} catch (IOException e) {
Log.e(ContactOperations.class.toString(), e.getMessage(), e);
}
}
return this;
}
private void addInsertOperation() {
ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withValueBackReference(StructuredName.RAW_CONTACT_ID, 0);
builder.withValue(ContactsContract.Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
builder.withValues(contentValues);
batchOperation.add(builder.build());
}
And after that I call method on BatchOperation class
public List<Uri> execute() {
List<Uri> resultUris = new ArrayList<Uri>();
if (mOperations.size() == 0) {
return resultUris;
}
// Apply the mOperations to the content provider
try {
ContentProviderResult[] results = mResolver.applyBatch(ContactsContract.AUTHORITY,
mOperations);
if ((results != null) && (results.length > 0)){
for (int i = 0; i < results.length; i++){
resultUris.add(results[i].uri);
}
}
} catch (final OperationApplicationException e1) {
Log.e(TAG, "storing contact data failed", e1);
} catch (final RemoteException e2) {
Log.e(TAG, "storing contact data failed", e2);
}
mOperations.clear();
return resultUris;
}

Related

Android Smack MUC 400 Bad Request sending group Chat Message

Hey i am developing Chat Application using XMPP Smack Library. Recently i am working on Group Chat While sending Group message some message will be drop so receiver wouldn't receives message from the sender side. it will gives me 400 bad request.
it is working sometimes. and sometimes not work
here i found this kind of message in 400 bad request.
<?xml version="1.0" encoding="UTF-8"?>
<message to="156#abc.com/Android" id="nXlV6-1144" type="error" from="24#confrence.abc.com/156#abc.com.com">
<received xmlns="urn:xmpp:receipts" id="nXlV6-1142" />
<error code="400" type="modify">
<bad-request xmlns="urn:ietf:params:xml:ns:xmpp-stanzas" />
</error>
</message>
if successfully send message it will give this kind of message.
<?xml version="1.0" encoding="UTF-8"?>
<message to="156#abc.com/Android" id="nXlV6-1411" type="groupchat" from="24#conference.abc.com/156#abc.com">
<body>eyu4u4</body>
<chatDetail xmlns="jabber:x:oob">
<UID>156</UID>
<time>04:20 PM</time>
<user_icon>24_group_icon.jpg</user_icon>
<SentTime>1474368652960</SentTime>
<USERName>vasudev89</USERName>
<user_name>cryan</user_name>
<message>eyu4u4</message>
<type>group</type>
<phone_number>24</phone_number>
</chatDetail>
<request xmlns="urn:xmpp:receipts" />
</message>
how i can send message persistently? Any idea?
Thank You in Advance.
here is my code sending muc message:
public boolean sendGroupMessage(Message message, String strGroupID) {
DeliveryReceiptRequest.addTo(message);
try {
Log.i(TAG, "sendGroupMessage");
//Log.i("JOIN MUC","To join group chat: " + groupChat.getClassId());
// Get the MultiUserChatManager
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(AbstractXMPPConnection);
// Create a MultiUserChat using an XMPPConnection for a room
MultiUserChat muc = manager.getMultiUserChat(strGroupID + AppWSConstants.XMPP_JID_GROUP_CHAT_SUFFIX);
muc.sendMessage(message);
return true;
} catch (NotConnectedException e) {
e.printStackTrace();
}
return false;
}
#LearnPainLess, follow these steps to solve group chat issue
-when creating groups, save the jid of group in the database, like "somegroup#conference.{domain}.com"
-create background task for creating xmpp connection (this way it will always be connected)
-after logging in to xmpp, get the group names from the database and connect to them
also, in openfire, Group Chat > Group Chat Settings > Edit Icon > Default Room Settings > Check "Make Room Persistant"
also, in other settings > Never kick idle users
I have an XmppBase class where i put all my xmpp code
All listeners in seperate folder
Connection is stored in static variable and i retrive it using
Utils.getConnection()
// this function m calling from background service and everywhere if not connectect to xmpp
public static XMPPConnection CreateXmppConnection() {
if (Utils.getConnection() == null) {
try {
Boolean isConnected = new XmppAsync(mUsername, mPassword,context).execute().get();
if (isConnected && Utils.getConnection() != null) {
RegisterConnListeners(Utils.getConnection());
updateMyProfileImg();
// connect to all groups
DBAdapter adapter = new DBAdapter(context);
adapter.openForRead();
List<UserDetail> groups = new ArrayList<>();
adapter.addAllGroups(groups);
adapter.addPastChatGroups(groups);
adapter.close();
for(UserDetail g : groups)
{
CreateXmppMUCSession(g.getGroupTemp());
}
return Utils.getConnection();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
} else
return Utils.getConnection();
}
// get muc chat manager
public static MultiUserChatManager getMucManager() {
if(mucManager != null)
return mucManager;
if (Utils.getConnection() != null) {
return MultiUserChatManager.getInstanceFor(Utils.getConnection());
} else {
if (CreateXmppConnection() != null)
return MultiUserChatManager.getInstanceFor(Utils.getConnection());
else {
Log.v("error", "Some Error Occured");
Toast.makeText(context, "Cant Connect to Xmpp", Toast.LENGTH_SHORT).show();
return null;
}
}
}
// create muc session and m passing group name - call when you open chat page
public static void CreateXmppMUCSession(String gName)
{
RegisterGroupChatListeners(gName);
}
// connect to muc if not already connected
public static void RegisterGroupChatListeners(String groupName)
{
try {
mStateManager = getChatStateManager();
multiUserChat = getMUC(groupName);
// if(multiUserChat != null) {
multiUserChat.addMessageListener(new MyMUCMessageListener());
try {
if (!multiUserChat.isJoined()) {
DiscussionHistory discussionHistory = new DiscussionHistory();
discussionHistory.setMaxStanzas(0);
multiUserChat.join(new MyPrefrence(context).getUsername().split("#")[0], "123",
discussionHistory, SmackConfiguration.getDefaultPacketReplyTimeout());
}
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
// }
}
catch (Exception ex)
{
//
}
}
// get muc
public static MultiUserChat getMUC(String groupName)
{
// Log.v("nick",multiUserChat.getNickname() + " , g = " + groupName);
// if(multiUserChat != null && multiUserChat.getRoom().contains(groupName))
// {
// return multiUserChat;
// }
if (Utils.getConnection() != null) {
MultiUserChatManager chatManager = getMucManager();
if (chatManager != null) {
return chatManager.getMultiUserChat(groupName);
} else {
Toast.makeText(context, "Cannot create Chat", Toast.LENGTH_SHORT).show();
return null;
}
} else {
if (CreateXmppConnection() != null) {
MultiUserChatManager chatManager = getMucManager();
if (chatManager != null) {
return chatManager.getMultiUserChat(groupName);
} else {
Toast.makeText(context, "Cannot create Chat", Toast.LENGTH_SHORT).show();
return null;
}
}
else {
Toast.makeText(context, "Cannot create Chat", Toast.LENGTH_SHORT).show();
return null;
}
}
}
and whenever i want to send message i just call this
public static Boolean sendMUCChatMsg(Message msg)
{
if(multiUserChat != null)
try {
multiUserChat.sendMessage(msg);
return true;
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
return false;
}
Sorry if it looks clumpsy, if I missed any function there let me know, but this is working code which i am using
try this,
I modified your last function
static MultiUserChat multiUserChat;
// call this function when you open the chat window
private void CreateGroupConnection(String strGroupID ) {
// Get the MultiUserChatManager
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(AbstractXMPPConnection);
// Create a MultiUserChat using an XMPPConnection for a room
MultiUserChat multiUserChat = manager.getMultiUserChat(strGroupID + AppWSConstants.XMPP_JID_GROUP_CHAT_SUFFIX);
return multiUserChat;
}
// whenever sending message from chat call this
publilc static void sendMucMessage(Message message){
if(multiUserChat != null)
multiUserChat.sendMessage(message);
}
I am working on "seen and delivered" in MUC and facing with this issue when replying back with the same packet id, still testing but I think in your case you should move your xmpp connection to background service and after connecting to xmpp on device launch up, connect to all the muc in your database. This way you will always be connected to groups.
cause : according to me, when the other user is not connected to the muc and you send a message or when you reply to the group with the same packet id.
Note: I am using multiuserchat.sendmessage to send group message and chat.sendmessage to send message to single user
SMACK 4.1
** update **
I fixed it by creating new packet instead of modifying the one i am receiving
here is the packet
Message msgg = new Message();
msgg.setBody(message.getPacketID());
msgg.setSubject(MessageModel.CHAT_STATUS_SEEN + "");
XmppBase.sendMUCChatMsg(msgg);
in your case, try with simple packet first. if all works well, then add extension one by one and see where you get the error, Thanks

Google account get Token

I have a problem with kitkat api while tringy to get access token of google account services, google music in my case. So, if user trying get token at first by using next method:
public String getAuthToken(Account account)
throws AuthenticatorException, IOException {
String s1;
if (account == null) {
Log.e("MusicAuthInfo", "Given null account to MusicAuthInfo.getAuthToken()", new Throwable());
throw new AuthenticatorException("Given null account to MusicAuthInfo.getAuthToken()");
}
String s = getAuthTokenType(mContext);
try {
s1 = AccountManager.get(mContext).blockingGetAuthToken(account, s, true);
} catch (OperationCanceledException operationcanceledexception) {
throw new AuthenticatorException(operationcanceledexception);
}
if (s1 == null) {
throw new AuthenticatorException("Received null auth token.");
}
return s1;
}
here i get s1 == null and the system push notification:
When user tap on notification, next dialog appear:
When user click "ok", all next iterations getting token get success.
Question: How to circumvent this confirmation or show just dialog, without click to notification ?
It's not a direct answer to your question, but you can use Google Play Services instead.
String token = GoogleAuthUtil.getToken(context, userEmail, "oauth2:https://mail.google.com/");
You just have to specify the oauth2 scope you need. For instance for Google+ you would need "https://www.googleapis.com/auth/plus.login" instead of what I post in the snippet for Gmail. You can also specify multiple scopes in one token request. The permission request pops up right away.
You can read all about it here: Authorizing with Google for REST APIs, Login scopes
Solved. Need use this method:
Bundle result = AccountManager.get(activity).getAuthToken(account, s, new Bundle(), activity, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
Log.e("xxx", future.getResult().toString());
} catch (OperationCanceledException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (AuthenticatorException e) {
e.printStackTrace();
}
}
}, null).getResult();

Error while saving ParseRelation

I'm having some issues while trying to save a ParseRelation. I've tried creating the ParseUser first (I thought that was the problem) but it continued to happen.
Situation: I have 2 tables, one is User (Parse.com default) and a second one called Teams. Inside the latter, there's a ParseRelation to User. After saveInBackground is triggered I check the DataBrowser and I can see that the team was in fact created but the players added not in the relation.
My code:
ParseObject newTeam = new ParseObject(Constants.TABLE_TEAMS);
newTeam.put(Constants.ATTRIB_TEAM_NAME, nombreEquipo);
// FIXME ParseRelation not being saved
ParseRelation<ParseUser> playersRelation = newTeam
.getRelation(Constants.ATTRIB_TEAM_PLAYERS);
// Get Users from ListView
for (int i = 0; i < invitedPlayers.size(); i++) {
ParseUser pu = (ParseUser) viewPlayerList.getItemAtPosition(i);
playersRelation.add(pu);
Log.d(LOG_TAG,
"Player being added: "
+ pu.get(Constants.ATTRIB_USER_NAME));
}
newTeam.put(Constants.ATTRIB_TEAM_PLAYERS, playersRelation);
newTeam.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// setResult(RESULT_OK);
Toast.makeText(getApplicationContext(), "Team created.",
Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(getApplicationContext(),
"ParseException: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
Any ideas ? I've read the docs and also checked a few samples but can't seem to find out what's the problem.
Edit: Using Parse.com v1.5.0 and Android 4.4.2

Android ADD FRIEND using Smack

I am new to the use of smack library and making one chatting application. I have made upto much extent and at this step i want to ask two questions.
when i add a friend the friend got added in my list but there is not any notification sent to the FRIEND whom i have added, How to achieve the same. I have added the code below.
The second thing i want to ask is that how can I check whether the user which I am going to add is a part or member of the app or not ( mean it is on the server or not). So that the user who is not registered to the app should not be added in the friends list.
here is the code
public static boolean addFriend(String jid) {
String nickname = null;
nickname = StringUtils.parseBareAddress(jid);
RosterEntry entry4 = roster.getEntry("samsad");
if (!roster.contains(jid)) {
try {
Presence subscribe = new Presence(Presence.Type.subscribe);
subscribe.setTo(jid);
connection.sendPacket(subscribe);
roster.createEntry(jid, nickname, null);
// Send a roster entry (any) to user2
RosterExchangeManager REM = new RosterExchangeManager(connection);
REM.send(entry4, jid);
return true;
} catch (XMPPException e) {
System.err.println("Error in adding friend");
return false;
}
} else {
return false;
}
}
Roster Exchange manager running in the service in background
/**Remotr Exchange Manager*/
RosterExchangeManager rem = new RosterExchangeManager(connection);
// Create a RosterExchangeListener that will iterate over the received roster entries
RosterExchangeListener rosterExchangeListener = new RosterExchangeListener() {
public void entriesReceived(String from, Iterator remoteRosterEntries) {
notification("Receive==4");
while (remoteRosterEntries.hasNext()) {
try {
// Get the received entry
RemoteRosterEntry remoteRosterEntry = (RemoteRosterEntry) remoteRosterEntries.next();
// Display the remote entry on the console
System.out.println(remoteRosterEntry);
// Add the entry to the user2's roster
roster.createEntry(
remoteRosterEntry.getUser(),
remoteRosterEntry.getName(),
remoteRosterEntry.getGroupArrayNames());
notification("Receive==1");
}
catch (XMPPException e) {
e.printStackTrace();
}
}
}
};
rem.addRosterListener(rosterExchangeListener);
}
else{
showToast("Connection lost-",0);
}
}
1, The problem is you must register a PacketListener for Presence.Type.subscribe before you connect to server. All the process of add and accept friend i answered in here
2, You can use UserSearch class to search for a specific user and if user is not found on server then you can assume that user is not registered on server.

Setting Account sync indicator red (or other colors too)

I'm trying to indicate the authentication / sync status of an account using the AccountAuthenticator and SyncAdapter. I've been through the samples, and can get it working alright.
How can I set the indicator to red just like the GMail account?
I'd also like to add additional status indicators on the sync adapter page. See picture below:
Answering my own question for future team knowledge...
Getting the indicator to change color was fairly easy after some experimentation. Start by creating a project based on thecode supplied in the SDK sample projects, modify as follows:
1) Fake the initial login from the server during the AuthenticationActivity. Once past the initial check, the system will start it's periodic sync attempts.
/**
* Called when the authentication process completes (see attemptLogin()).
*/
public void onAuthenticationResult(boolean result) {
Log.i(TAG, "onAuthenticationResult(" + result + ")");
// Hide the progress dialog
hideProgress();
// Override the result, we don't care right now....
result = true;
if (result) {
if (!mConfirmCredentials) {
finishLogin();
} else {
finishConfirmCredentials(true);
}
} else {
Log.e(TAG, "onAuthenticationResult: failed to authenticate");
if (mRequestNewAccount) {
// "Please enter a valid username/password.
mMessage.setText(getText(R.string.login_activity_loginfail_text_both));
} else {
// "Please enter a valid password." (Used when the
// account is already in the database but the password
// doesn't work.)
mMessage.setText(getText(R.string.login_activity_loginfail_text_pwonly));
}
}
}
2) Modify the "onPerformSync()" method within the SyncAdapter. The key here are the "syncResult.stats" fields. While modifying them, I found that inserting multiple errors didn't get the effect I wanted. Also noting that the counts didn't seem to be recorded across sync attempts (i.e. the fails always come in as zero). The "lifetimeSyncs" is a static variable that keeps count across sync attempts. This modified code will continue to alternate between green and red...
#Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
List<User> users;
List<Status> statuses;
String authtoken = null;
try {
// use the account manager to request the credentials
authtoken = mAccountManager.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true );
// fetch updates from the sample service over the cloud
//users = NetworkUtilities.fetchFriendUpdates(account, authtoken, mLastUpdated);
// update the last synced date.
mLastUpdated = new Date();
// update platform contacts.
Log.d(TAG, "Calling contactManager's sync contacts");
//ContactManager.syncContacts(mContext, account.name, users);
// fetch and update status messages for all the synced users.
//statuses = NetworkUtilities.fetchFriendStatuses(account, authtoken);
//ContactManager.insertStatuses(mContext, account.name, statuses);
if (SyncAdapter.lifetimeSyncs-- <= 0 ){
//mAccountManager.invalidateAuthToken(Constants.ACCOUNT_TYPE, authtoken);
syncResult.stats.numAuthExceptions++;
//syncResult.delayUntil = 60;
lifetimeSyncs = 5;
}
} catch (final AuthenticatorException e) {
syncResult.stats.numParseExceptions++;
Log.e(TAG, "AuthenticatorException", e);
} catch (final OperationCanceledException e) {
Log.e(TAG, "OperationCanceledExcetpion", e);
} catch (final IOException e) {
Log.e(TAG, "IOException", e);
Log.d(TAG, extras.toString());
syncResult.stats.numAuthExceptions++;
syncResult.delayUntil = 60;
//extras.putString(AccountManager.KEY_AUTH_FAILED_MESSAGE, "You're not registered");
} catch (final ParseException e) {
syncResult.stats.numParseExceptions++;
Log.e(TAG, "ParseException", e);
}
}
That's it, enjoy playing with the delays and other variables too...

Categories

Resources