Deleting a contact
I did ask this on my previous issue but got no reply so if someone can close that issue and reply to this one then that would be great!
Also i need to know how to delete a contact from the list because everything i have tried so far hasn't worked and it's beginning to get rather frustrating now especially when i need this app released asap, so any help would be great right now!
Thanks again!
Hello,
Removing contacts is not yet an officially supported feature. However I feel like it belongs in our SDK and am adding it to the next major version. I'd like to work out a hotfix, but we have a backlog and some priority items that need to be addressed.
If you are interested in trying to implement the feature I recommend looking at how we delete threads. It should be possible to adopt the same strategy for deleting contacts. This weekend I will have a bit more time for some tips and suggestions.
Furthermore, we do offer priority support packages for the SDK, and custom integrations.
-- Kyle
Hi,
Thanks for getting back to me! I've had a go at modifying the thread deletion code and i have also tried reversing the way you add a contact but nothing is working so if you do get the time to help me at the weekend then that would be much appreciated! Even if it's just a couple tips on how i can achieve what i need!
Thank you
So i thought I'd share what I've got so far to see if what I've tried is useless or just needs a little improvement!
So i figured i could delete a contact by reversing the addContact method and well i think it's kind of working but i feel like there's slightly more to do to achieve what i need!
@Override
public void deleteContact(BUser user) {
// Retrieve contacts
List contacts = getContacts();
// refresh contact list before updating
resetContactLinks();
List contactLinkList = getContactLinks();
ContactLink contactLink = new ContactLink();
// Set link owner
contactLink.setLinkOwnerBUser(this);
contactLink.setLinkOwnerBUserDaoId(this.getId());
daoSession.delete(user);
myDao.delete(user);
// make the connection to the user
contactLinkList.remove(user);
resetContactLinks();
this.update();
}
And then
BUser currentUser = BNetworkManager.sharedManager().getNetworkAdapter().currentUserModel();
final BUser clickedUser = DaoCore.fetchEntityWithEntityID(BUser.class,adapter.getItem(position).getEntityID());
currentUser.deleteContact(clickedUser);
loadDataOnBackground();
So am i close or really far off?
Hey,
It looks like you are on the right track for removing the user from the local database (managed by GreenDAO ORM). The problem that remains is likely due to us adding users that are in chats.
// Users that are members of threads are shown in contacts
currentUser.addContact(bUser);
So if you have any chats open with the user you are trying to delete, they may be added right back immediately. To take care of this, you should search for all threads that contain this user, and make sure they are deleted / closed as part of your deleteContact(BUser user) command. Make sure you do this before trying to remove the user from the database.
After that, you should be finished! -- Kyle
Well i'm glad i'm finally nearly there but i have yet another annoying question! What would be the best way to search the threads for users? because i'm not having much luck at the moment! Thanks
Don't sell yourself short, questions are welcome!
First, to get a list of threads, retrieve the current user the same way you did above. Then retrieve all private threads using the the BUser object's public List<BThread> getThreads( int type ) method.
BUser currentUser = BNetworkManager.sharedManager().getNetworkAdapter().currentUserModel();
List<BThread> threadsToCheck = currentUser.getThreads(BThread.Type.Private);
The BThread object has a method public List<BUser> getUsers( ) for retrieving users that are a part of its conversation. By looping through this list of BUser object and comparing the userIds to the one of the user you are deleting, you should be able to decide if the thread needs to be deleted or not.
Hope this helps!
So i have decided to give up trying now because it's still not fully working! One minute everything is fine and it deletes the contact properly but then next it doesn't and i just don't know why!. But by all means take the code that I've come up with so far if you feel like it can help you or anyone else but i for one can't do it lol.
I think i will just, for the time being, have to hope i don't get bad reviews for not having the ability to delete contacts! lol.
Thanks for your help though, it's been very helpful!
Hello Sir, I need to ask i have to delete contact using onItemLongClickListener but when I tried to do the same using deleteThread() method the app showing null pointer exception in ChatSDKBaseFragment class's showAlert() method that attempt to invoke virtual method apapter.getItem(position).getEntityId() in ChatSDKAbstractContactsFragment class. so please could you help me to sort out why this problem occurs.
@SimplisticApps Where can I see the your code for the implementation you tried? I will try and take a peek for you.
@kawadkarrocky It sounds like you are calling deleteThread( ) on a null object. Make sure you are properly setting the variable to a real instance of a BThread object.
If you can share a stack trace it would make things a lot easier to debug too.
/************** apology for misconfusion it is DeleteThread class's instance in onItemLongClickListener /***************rather than deleteThread() method
/************now here is the class ChatSDKAbstractContactsFragment in fragment folder in which i added /************onItemLongClickListener to delete contact
public class ChatSDKAbstractContactsFragment extends ChatSDKBaseFragment {
private static final String TAG = ChatSDKAbstractContactsFragment.class.getSimpleName();
private static boolean DEBUG = Debug.ContactsFragment;
/**
* Loading all the current user contacts.
*/
public static final int MODE_LOAD_CONTACTS = 1991;
/**
* Loading all users for given thread id mode
*/
public static final int MODE_LOAD_THREAD_USERS = 1992;
public static final int MODE_LOAD_FOLLOWERS = 1993;
public static final int MODE_LOAD_FOLLOWS = 1994;
/**
* Using the users that was given to the fragment in to initializer;
*/
public static final int MODE_USE_SOURCE = 1995;
public static final int MODE_LOAD_CONTACT_THAT_NOT_IN_THREAD = 1996;
/**
* When a user clicked he will be added to the current thread.
*/
public static final int CLICK_MODE_ADD_USER_TO_THREAD = 2991;
/**
* Used for the share intent, When a user press on a user the attached data from the share intent will be sent to the selected user.
*/
public static final int CLICK_MODE_SHARE_CONTENT = 2992;
/**
* Open profile activity when user is clicked.
*/
public static final int CLICK_MODE_SHOW_PROFILE = 2993;
/**
* Nothing happen on list item click.
*/
public static final int CLICK_MODE_NONE = 2994;
public static final String LOADING_MODE = "Loading_Mode";
public static final String CLICK_MODE = "Click_Mode";
public static final String EVENT_TAG = "EventTag";
public static final String IS_DIALOG = "is_dialog";
/**
* The text color that the adapter will use, Use -1 to set adapter to default color.
*/
protected int textColor = -1991;
protected ChatSDKAbstractUsersListAdapter adapter;
protected ProgressBar progressBar;
protected ListView listView;
private ContactListListener contactListListener;
/**
* Users that will be used to fill the adapter, This could be set manually or it will be filled when loading users for
* {@link #loadingMode}
*/
protected List<BUser> sourceUsers = null;
/**
* Used when the fragment is shown as a dialog
*/
protected String title = "";
/**
* Determine which users will be loaded to this fragment.
*
* @see #MODE_LOAD_CONTACT_THAT_NOT_IN_THREAD,
* #MODE_LOAD_CONTACTS
* #MODE_LOAD_FOLLOWERS
* #MODE_LOAD_FOLLOWS
* #MODE_LOAD_THREAD_USERS
* #MODE_USE_SOURCE
*/
protected int loadingMode;
/**
* Determine what happen after a user is clicked.
*
* @see #CLICK_MODE_ADD_USER_TO_THREAD
* #CLICK_MODE_SHARE_CONTENT
* #CLICK_MODE_SHOW_PROFILE
*/
protected int clickMode;
/**
* Extra data for the loading mode/ click mode, for example this is used as thread id/entityID for loading mode {@link #CLICK_MODE_ADD_USER_TO_THREAD}
* Look in {@link #loadSourceUsers()} or in {@link #setListClickMode()} for more examples.
*/
protected Object extraData = "";
/**
* This is passed to the {@link com.braunster.chatsdk.adapter.abstracted.ChatSDKAbstractUsersListAdapter}, If true the list adapter will remove all duplicates.
*
* @see com.braunster.chatsdk.adapter.abstracted.ChatSDKAbstractUsersListAdapter
*/
protected boolean removeDuplicates = true;
/**
* This is passed to the list adapter, If true the list will be with headers.
*
* @see com.braunster.chatsdk.adapter.abstracted.ChatSDKAbstractUsersListAdapter
*/
protected boolean withHeaders = false;
/**
* If true the fragent will listen to users details change and updates.
*/
protected boolean withUpdates = true;
/**
* Set to false if you dont want any menu item to be inflated for this fragment.
* This should be set before the fragment transaction,
* if you extends the fragment you can call it in {@link #onCreate(android.os.Bundle)}
* <B>see </B>{@link #setInflateMenu(boolean inflate)}
*/
protected boolean inflateMenu = true;
protected String eventTAG;
protected UIUpdater uiUpdater;
private ChatSDKAbstractUsersListAdapter.ProfilePicClickListener profilePicClickListener;
private AdapterView.OnItemClickListener onItemClickListener;
protected AdapterView.OnItemLongClickListener onItemLongClickListener;
/**
* When isDialog = true the dialog will always show the list of users given to him or pulled by the thread id.
*/
private boolean isDialog = false;
public void setEventTAG(String eventTAG) {
this.eventTAG = eventTAG;
}
public void setDialog() {
this.isDialog = true;
}
public void setTitle(String title) {
this.title = title;
}
public void setLoadingMode(int loadingMode) {
this.loadingMode = loadingMode;
}
public void setExtraData(Object extraData) {
this.extraData = extraData;
}
public void setClickMode(int clickMode) {
this.clickMode = clickMode;
}
public void setSourceUsers(List<BUser> sourceUsers) {
this.sourceUsers = sourceUsers;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
loadingMode = savedInstanceState.getInt(LOADING_MODE);
clickMode = savedInstanceState.getInt(CLICK_MODE);
isDialog = savedInstanceState.getBoolean(IS_DIALOG);
eventTAG = savedInstanceState.getString(EVENT_TAG);
}
if (!isDialog) {
setHasOptionsMenu(true);
setRetainInstance(true);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (isDialog) {
if (title.equals(""))
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
else getDialog().setTitle(title);
}
return mainView;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(LOADING_MODE, loadingMode);
outState.putBoolean(IS_DIALOG, isDialog);
outState.putString(EVENT_TAG, eventTAG);
}
@Override
public void initViews() {
listView = (ListView) mainView.findViewById(R.id.chat_sdk_list_contacts);
progressBar = (ProgressBar) mainView.findViewById(R.id.chat_sdk_progressbar);
// Create the adpater only if null,
// This is here so we wont override the adapter given from the extended class with setAdapter.
if (adapter == null)
adapter = new ChatSDKUsersListAdapter(getActivity());
adapter.setProfilePicClickListener(profilePicClickListener);
setTextColor(textColor);
listView.setAdapter(adapter);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
if (!inflateMenu)
return;
MenuItem item =
menu.add(Menu.NONE, R.id.action_chat_sdk_add, 10, "Add Chat");
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
item.setIcon(R.drawable.ic_plus);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
/* Cant use switch in the library*/
int id = item.getItemId();
// Each user that will be found in the search activity will be automatically added as a contact.
if (id == R.id.action_chat_sdk_add) {
Intent intent = new Intent(getActivity(), chatSDKUiHelper.searchActivity);
startActivityForResult(intent, ChatSDKSearchActivity.GET_CONTACTS_ADDED_REQUEST);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void loadData() {
if (mainView == null || getActivity() == null)
return;
loadSourceUsers();
if (BNetworkManager.sharedManager().getNetworkAdapter() != null) {
adapter.setUserItems(adapter.makeList(sourceUsers, withHeaders, removeDuplicates));
setListClickMode();
}
}
@Override
public void loadDataOnBackground() {
if (mainView == null || getActivity() == null) {
return;
}
final boolean isFirst;
if (uiUpdater != null) {
isFirst = false;
uiUpdater.setKilled(true);
ChatSDKThreadPool.getInstance().removeSchedule(uiUpdater);
} else {
isFirst = true;
if (adapter != null && adapter.getUserItems().size() < 2) {
progressBar.setVisibility(View.VISIBLE);
listView.setVisibility(View.INVISIBLE);
}
}
uiUpdater = new UIUpdater() {
@Override
public void run() {
if (isKilled()) {
return;
}
loadSourceUsers();
Message message = new Message();
message.what = 1;
message.obj = adapter.makeList(sourceUsers, withHeaders, removeDuplicates);
handler.sendMessage(message);
uiUpdater = null;
}
};
ChatSDKThreadPool.getInstance().scheduleExecute(uiUpdater, isFirst ? 0 : loadingMode == MODE_LOAD_CONTACTS ? 4 : 0);
}
@Override
public void clearData() {
if (adapter != null) {
if (uiUpdater != null)
uiUpdater.setKilled(true);
adapter.getUserItems().clear();
adapter.notifyDataSetChanged();
}
}
private Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
adapter.setUserItems(((List) msg.obj));
if (progressBar.getVisibility() == View.VISIBLE) {
hideLoading();
}
setListClickMode();
}
}
};
private void setListClickMode() {
if (onItemClickListener != null) {
listView.setOnItemClickListener(onItemClickListener);
} else if (onItemClickListener == null) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (adapter.getItem(position).getType() == ChatSDKUsersListAdapter.TYPE_HEADER)
return;
final BUser clickedUser = DaoCore.fetchEntityWithEntityID(BUser.class, adapter.getItem(position).getEntityID());
switch (clickMode) {
case CLICK_MODE_ADD_USER_TO_THREAD:
BThread thread;
if (extraData instanceof Long)
thread = DaoCore.fetchEntityWithProperty(BThread.class, BThreadDao.Properties.Id, extraData);
else
thread = DaoCore.fetchEntityWithEntityID(BThread.class, extraData);
getNetworkAdapter().addUsersToThread(thread, clickedUser)
.done(new DoneCallback<BThread>() {
@Override
public void onDone(BThread thread) {
showToast(getString(R.string.abstract_contact_fragment_user_added_to_thread_toast_success) + clickedUser.getMetaName());
if (contactListListener != null)
contactListListener.onContactClicked(clickedUser);
if (isDialog) {
getDialog().dismiss();
}
}
})
.fail(new FailCallback<BError>() {
@Override
public void onFail(BError error) {
chatSDKUiHelper.showAlertToast(getString(R.string.abstract_contact_fragment_user_added_to_thread_toast_fail));
}
});
break;
case CLICK_MODE_SHARE_CONTENT:
createAndOpenThreadWithUsers(clickedUser.getMetaName(), clickedUser, getNetworkAdapter().currentUserModel())
.done(new DoneCallback<BThread>() {
@Override
public void onDone(BThread thread) {
Intent intent = new Intent(getActivity(), chatSDKUiHelper.chatActivity);
intent.putExtra(ChatSDKChatActivity.THREAD_ID, thread.getId());
// Checking the kind of the instace data
// Uri is used for images
if (extraData instanceof Uri)
intent.putExtra(ChatSDKChatHelper.SHARED_FILE_URI, ((Uri) extraData));
// String is for text.
else if (extraData instanceof String)
intent.putExtra(ChatSDKChatHelper.SHARED_TEXT, ((String) extraData));
else {
showToast(getString(R.string.abstract_contact_fragment_share_with_contact_toast_fail_unknown_type));
return;
}
if (contactListListener != null)
contactListListener.onContactClicked(clickedUser);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
})
.fail(new FailCallback<BError>() {
@Override
public void onFail(BError error) {
}
});
break;
case CLICK_MODE_NONE:
break;
default:
createAndOpenThreadWithUsers(clickedUser.getMetaName(), clickedUser, getNetworkAdapter().currentUserModel())
.done(new DoneCallback<BThread>() {
@Override
public void onDone(BThread thread) {
if (contactListListener != null)
contactListListener.onContactClicked(clickedUser);
// This listener is used only because that if we dismiss the dialog before the thread creation has been done
// The contact dialog could not open the new chat activity because getActivity() will be null.
if (isDialog)
getDialog().dismiss();
}
})
.fail(new FailCallback<BError>() {
@Override
public void onFail(BError error) {
}
});
}
}
});
}
if (onItemLongClickListener == null) {
onItemLongClickListener = new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
showAlertDialog("", getResources().getString(R.string.alert_delete_thread),
getResources().getString(R.string.delete),
getResources().getString(R.string.cancel),
null, new DeleteThread(adapter.getItem(position).getEntityID()));
adapter.notifyDataSetChanged();
return true;
}
};
}
listView.setOnItemLongClickListener(onItemLongClickListener);
}
public void filterListStartWith(String filter) {
adapter.filterStartWith(filter);
}
private void loadSourceUsers() {
if (loadingMode != MODE_USE_SOURCE)
// If this is not a dialog we will load the contacts of the user.
switch (loadingMode) {
case MODE_LOAD_CONTACTS:
if (DEBUG) Timber.d("Mode - Contacts");
sourceUsers = getNetworkAdapter().currentUserModel().getContacts();
break;
case MODE_LOAD_THREAD_USERS:
if (DEBUG) Timber.d("Mode - Thread Users");
BThread thread = DaoCore.fetchEntityWithEntityID(BThread.class, extraData);
// Remove the current user from the list.
List<BUser> users = thread.getUsers();
users.remove(getNetworkAdapter().currentUserModel());
sourceUsers = users;
break;
case MODE_LOAD_CONTACT_THAT_NOT_IN_THREAD:
List<BUser> users1 = getNetworkAdapter().currentUserModel().getContacts();
thread = DaoCore.fetchEntityWithProperty(BThread.class, BThreadDao.Properties.Id, extraData);
List<BUser> threadUser = thread.getUsers();
users1.removeAll(threadUser);
sourceUsers = users1;
break;
case MODE_LOAD_FOLLOWERS:
if (extraData instanceof String && StringUtils.isNotEmpty((String) extraData)) {
sourceUsers = new ArrayList<BUser>();
showLoading();
getNetworkAdapter().getFollowers((String) extraData)
.done(new DoneCallback<List<BUser>>() {
@Override
public void onDone(List<BUser> users) {
users.remove(getNetworkAdapter().currentUserModel());
hideLoading();
sourceUsers = users;
adapter.addBUsersRows(users);
adapter.notifyDataSetChanged();
}
})
.fail(new FailCallback<BError>() {
@Override
public void onFail(BError error) {
//TODO handle error
}
});
} else
sourceUsers = getNetworkAdapter().currentUserModel().getFollowers();
break;
case MODE_LOAD_FOLLOWS:
if (extraData instanceof String && StringUtils.isNotEmpty((String) extraData)) {
sourceUsers = new ArrayList<BUser>();
showLoading();
getNetworkAdapter().getFollows((String) extraData)
.done(new DoneCallback<List<BUser>>() {
@Override
public void onDone(List<BUser> users) {
users.remove(getNetworkAdapter().currentUserModel());
hideLoading();
sourceUsers = users;
adapter.addBUsersRows(users);
adapter.notifyDataSetChanged();
}
});
} else
sourceUsers = getNetworkAdapter().currentUserModel().getFollows();
break;
}
}
public void showLoading() {
progressBar.setVisibility(View.VISIBLE);
listView.setVisibility(View.INVISIBLE);
}
public void hideLoading() {
progressBar.setVisibility(View.INVISIBLE);
listView.setVisibility(View.VISIBLE);
}
@Override
public void onResume() {
super.onResume();
if (withUpdates) {
BatchedEvent userDetailsBatch = new BatchedEvent(eventTAG, "", Event.Type.UserDetailsEvent, handler);
userDetailsBatch.setBatchedAction(Event.Type.UserDetailsEvent, 1000, new Batcher.BatchedAction<String>() {
@Override
public void triggered(List<String> list) {
loadDataOnBackground();
}
});
if (StringUtils.isNotEmpty(eventTAG)) {
getNetworkAdapter().getEventManager().removeEventByTag(eventTAG);
getNetworkAdapter().getEventManager().addEvent(userDetailsBatch);
}
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ChatSDKSearchActivity.GET_CONTACTS_ADDED_REQUEST)
if (resultCode == Activity.RESULT_OK) {
loadDataOnBackground();
}
}
@Override
public void onDestroy() {
super.onDestroy();
getNetworkAdapter().getEventManager().removeEventByTag(eventTAG);
}
public void setAdapter(ChatSDKAbstractUsersListAdapter adapter) {
this.adapter = adapter;
}
public void setContactListListener(ContactListListener contactListListener) {
this.contactListListener = contactListListener;
}
public interface ContactListListener {
public void onContactClicked(BUser user);
}
public void setRemoveDuplicates(boolean removeDuplicates) {
this.removeDuplicates = removeDuplicates;
}
public void setWithHeaders(boolean withHeaders) {
this.withHeaders = withHeaders;
}
public void setInflateMenu(boolean inflateMenu) {
this.inflateMenu = inflateMenu;
}
public void setTextColor(int textColor) {
this.textColor = textColor;
if (adapter != null) {
adapter.setTextColor(textColor);
adapter.notifyDataSetChanged();
}
}
public ChatSDKAbstractUsersListAdapter getAdapter() {
return adapter;
}
public void setProfilePicClickListener(ChatSDKAbstractUsersListAdapter.ProfilePicClickListener profilePicClickListener) {
this.profilePicClickListener = profilePicClickListener;
if (adapter != null) {
adapter.setProfilePicClickListener(profilePicClickListener);
adapter.notifyDataSetChanged();
}
}
public void withUpdates(boolean withUpdates) {
this.withUpdates = withUpdates;
}
public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public void setOnItemLongClickListener(AdapterView.OnItemLongClickListener onItemLongClickListener) {
this.onItemLongClickListener = onItemLongClickListener;
}
}
/****************now here is the ChatSDKBaseFragment class where i getting Null Pointer Exception /***************in showAlertDialog() method when i set to positive button to true
public abstract class ChatSDKBaseFragment extends android.app.DialogFragment implements ChatSDKBaseFragmentInterface {
private static final String TAG = ChatSDKBaseFragment.class.getSimpleName();
private static final boolean DEBUG = true;
private ProgressDialog progressDialog;
protected View mainView;
protected ChatSDKUiHelper chatSDKUiHelper;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
chatSDKUiHelper = ChatSDKUiHelper.getInstance().get(getActivity());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void refresh() {
loadData();
}
@Override
public void refreshOnBackground() {
loadDataOnBackground();
}
@Override
public void refreshForEntity(Entity entity) {
}
@Override
public void loadData() {
}
@Override
public void loadDataOnBackground() {
}
@Override
public void clearData() {
}
/** Set up the ui so every view and nested view that is not EditText will listen to touch event and dismiss the keyboard if touched.*/
public void setupTouchUIToDismissKeyboard(View view) {
ChatSDKUiHelper.setupTouchUIToDismissKeyboard(view, new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
ChatSDKUiHelper.hideSoftKeyboard(getActivity());
return false;
}
});
}
public void setupTouchUIToDismissKeyboard(View view, final Integer... exceptIDs) {
ChatSDKUiHelper.setupTouchUIToDismissKeyboard(view, new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
ChatSDKUiHelper.hideSoftKeyboard(getActivity());
return false;
}
}, exceptIDs);
}
public void setupTouchUIToDismissKeyboard(View view, View.OnTouchListener onTouchListener, final Integer... exceptIDs) {
ChatSDKUiHelper.setupTouchUIToDismissKeyboard(view, onTouchListener, exceptIDs);
}
@Override
public void initViews() {
}
/** Show a SuperToast with the given text. */
protected void showToast(String text){
if (chatSDKUiHelper==null || StringUtils.isEmpty(text))
return;
chatSDKUiHelper.getToast().setText(text);
chatSDKUiHelper.getToast().show();
}
protected void showAlertToast(String text){
if (chatSDKUiHelper==null || StringUtils.isEmpty(text))
return;
chatSDKUiHelper.getAlertToast().setText(text);
chatSDKUiHelper.getAlertToast().show();
}
/** Start the chat activity for the given thread id.
* @param id is the long value of local db id.*/
public void startChatActivityForID(long id){
if (chatSDKUiHelper != null)
chatSDKUiHelper.startChatActivityForID(id);
}
public void startLoginActivity(boolean loggedOut){
if (chatSDKUiHelper != null)
chatSDKUiHelper.startLoginActivity(loggedOut);
}
public void startMainActivity(){
if (chatSDKUiHelper != null)
chatSDKUiHelper.startMainActivity();
}
public void startSearchActivity() {
if (chatSDKUiHelper != null)
chatSDKUiHelper.startSearchActivity();
}
public void startPickFriendsActivity() {
if (chatSDKUiHelper != null)
chatSDKUiHelper.startPickFriendsActivity();
}
public void startShareWithFriendsActivity() {
if (chatSDKUiHelper != null)
chatSDKUiHelper.startShareWithFriendsActivity();
}
public void startShareLocationActivityActivity() {
if (chatSDKUiHelper != null)
chatSDKUiHelper.startShareLocationActivityActivity();
}
/** Create or fetch chat for users, Opens the chat when done.*/
protected Promise<BThread, BError, Void> createAndOpenThreadWithUsers(String name, BUser...users){
return createThreadWithUsers(name, true, users);
}
/** Create or fetch chat for users. Opens the chat if wanted.*/
protected Promise<BThread, BError, Void> createThreadWithUsers(String name, final boolean openChatWhenDone, BUser... users) {
return getNetworkAdapter().createThreadWithUsers(name, users)
.done(new DoneCallback<BThread>() {
@Override
public void onDone(BThread thread) {
if (thread != null) {
if (openChatWhenDone)
startChatActivityForID(thread.getId());
}
}
})
.fail(new FailCallback<BError>() {
@Override
public void onFail(BError error) {
if (isOnMainThread())
showAlertToast(getString(R.string.create_thread_with_users_fail_toast));
else getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
showAlertToast(getString(R.string.create_thread_with_users_fail_toast));
}
});
}
});
}
protected void showProgDialog(String message){
if (progressDialog == null)
progressDialog = new ProgressDialog(getActivity());
if (!progressDialog.isShowing())
{
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage(message);
progressDialog.show();
}
}
protected void showOrUpdateProgDialog(String message){
if (progressDialog == null)
progressDialog = new ProgressDialog(getActivity());
if (!progressDialog.isShowing())
{
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage(message);
progressDialog.show();
} else progressDialog.setMessage(message);
}
protected void dismissProgDialog(){
try {
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
} catch (Exception e) {
// For handling orientation changed.
e.printStackTrace();
}
}
protected boolean isOnMainThread() {
if (Looper.myLooper() != Looper.getMainLooper()) {
return false;
}
return true;
}
protected void showAlertDialog(String title, String alert, String p, String n, final Callable neg, final Callable pos){
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
// set title if not null
if (StringUtils.isNotBlank(title))
alertDialogBuilder.setTitle(title);
// set dialog message
alertDialogBuilder
.setMessage(alert)
.setCancelable(false)
.setPositiveButton(p, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (pos != null)
try {
pos.call();
} catch (Exception e) {
e.printStackTrace();
}
dialog.dismiss();
}
})
.setNegativeButton(n, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
if (neg != null)
try {
neg.call();
} catch (Exception e) {
e.printStackTrace();
}
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
protected class DeleteThread implements Callable{
private String threadID;
public DeleteThread(String threadID){
this.threadID = threadID;
}
@Override
public Object call() throws Exception {
getNetworkAdapter().deleteThreadWithEntityID(threadID)
.done(new DoneCallback<Void>() {
@Override
public void onDone(Void aVoid) {
showToast( getString(R.string.delete_thread_success_toast) );
refreshOnBackground();
}
})
.fail(new FailCallback<BError>() {
@Override
public void onFail(BError error) {
showAlertToast( getString(R.string.delete_thread_fail_toast) );
}
});
return null;
}
}
@Override
public AbstractNetworkAdapter getNetworkAdapter() {
return BNetworkManager.sharedManager().getNetworkAdapter();
}
/** Authenticates the current user.*/
public Promise<BUser, BError, Void> authenticate(){
return getNetworkAdapter().checkUserAuthenticated();
}
public void setChatSDKUiHelper(ChatSDKUiHelper chatSDKUiHelper) {
this.chatSDKUiHelper = chatSDKUiHelper;
}
public void setToast(SuperToast toast) {
chatSDKUiHelper.setToast(toast);
}
public SuperToast getToast() {
return chatSDKUiHelper.getToast();
}
public SuperToast getAlertToast() {
return chatSDKUiHelper.getAlertToast();
}
}
interface ChatSDKBaseFragmentInterface extends ChatSDKUiHelper.ChatSDKUiHelperInterface{ public void refresh();
public void refreshOnBackground();
public void loadData();
public void loadDataOnBackground();
public void initViews();
public void clearData();
public void refreshForEntity(Entity entity);
public AbstractNetworkAdapter getNetworkAdapter();
}
Hello, so this is what i have in the Contacts fragment:
`final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
String[] items = {"Delete Contact"};
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
BUser currentUser = BNetworkManager.sharedManager().getNetworkAdapter().currentUserModel();
final BUser clickedUser = DaoCore.fetchEntityWithEntityID(BUser.class, adapter.getItem(position).getEntityID());
List<BThread> threadsToCheck = currentUser.getThreads(BThread.Type.Private);
if (threadsToCheck.isEmpty()) {
currentUser.deleteContact(clickedUser);
loadDataOnBackground();
showToast(getString(R.string.delete_thread_success_toast));
} else {
currentUser.deleteContact(clickedUser);
loadDataOnBackground();
showToast(getString(R.string.delete_thread_success_toast));
}
}
builder.chow();
});`
And here's the deleteContact, which i think is the same the first one i posted!
`@Override
public void deleteContact(BUser user) {
// Retrieve contacts
List contacts = getContacts();
// refresh contact list before updating
resetContactLinks();
List contactLinkList = getContactLinks();
ContactLink contactLink = new ContactLink();
// Set link owner
contactLink.setLinkOwnerBUser(this);
contactLink.setLinkOwnerBUserDaoId(this.getId());
daoSession.delete(user);
myDao.delete(user);
// make the connection to the user
contactLinkList.remove(user);
resetContactLinks();
this.update();
}`
It's just confusing because i know that it deletes the contact, 100% but not all the time, which i think is down to me not quite knowing fully how to search any open threads! I did try using the DeleteThread class but it wouldn't delete any threads, even ones i knew were currently open!
I also tried searching threads by doing:
if (threadsToCheck.get(position).getUsers().contains(clickedUser))
Then
threadsToCheck.remove(adapter.getItem(position).getEntityID());
To remove the thread...
But again, didn't work properly
So yeah if you can get the code to work then that would be amazing!
Thanks
@kykrueger