I am alerting the user after some action and showing alert dialog but when accessibility is on it is not reading full alert dailog header and body. It is reading only header. I found this issue in samsung galaxy s5.
Please help me solving this issue.
public class TransactionDialog extends DialogFragment {
private int _state = -1;
private final String TITLE = "TITLE";
private final String MESSAGE = "MESSAGE";
private final String POS_TEXT = "POS_TEXT";
private final String STATE = "STATE";
private int _title = 0;
private int _message = 0;
private int _positiveText = 0;
private NoticeDialogListener mListener;
Logger logger = Logger.getNewLogger("com.ui.TransactionDialog");
boolean actionPerformed = false;
AlertDialog dialog = null;
public TransactionDialog() {
}
public void setListener(NoticeDialogListener listener) {
this.mListener = listener;
}
public TransactionDialog(int title, int message, int positiveText, int state) {
this._title = title;
this._message = message;
this._positiveText = positiveText;
this._state = state;
}
public int getState() {
return _state;
}
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putInt(TITLE, this._title);
outState.putInt(MESSAGE, this._message);
outState.putInt(POS_TEXT, this._positiveText);
outState.putInt(STATE, this._state);
}
#Override
public void onResume() {
super.onResume();
logger.debug("TITLE:" + this._title);
logger.debug("_message:" + this._message);
logger.debug("_positiveText:" + this._positiveText);
logger.debug("_state:" + this._state);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
logger.debug("Created");
}
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
super.onDismiss(dialog);
mListener.onDialogDismissed();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
logger.debug("ON CREATE");
if (savedInstanceState != null) {
this._title = savedInstanceState.getInt(TITLE);
this._message = savedInstanceState.getInt(MESSAGE);
this._positiveText = savedInstanceState.getInt(POS_TEXT);
this._state = savedInstanceState.getInt(STATE);
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getResources().getString(this._title))
.setMessage(getResources().getString(_message))
.setPositiveButton(getResources().getString(_positiveText), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(actionPerformed)
return;
actionPerformed = true;
mListener.onDialogPositiveClick(TransactionDialog.this);
}
});
dialog = builder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
dialog.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
mListener.onDialogPositiveClick(TransactionDialog.this);
}
return false;
}
});
return dialog;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the
// host
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogDismissed();
}}
Here i am using the txndialog class for creating the alert dialog.
private TransactionDialog transactionDialog;
transactionDialog = (TransactionDialog) newTransactionFrgment;
transactionDialog.setListener(this);
transactionDialog = new TransactionDialog(R.string.transaction_complete_header, R.string.transaction_complete_message,
R.string.transaction_complete_positive_button, STATE_SET_TRANSACION);
transactionDialog.show(getFragmentManager(), TRANSACTION_DIALOG_TAG);
Related
I am using quickblox for my android application. I am able to register, login user, even add custom objects and retrieve them from the quick-blox server, but in chatting listing screen my count is coming wrong.
I am getting issue with unread count
Here is my code flow:-
public class ConversationFragment extends Fragment implements Observer, DialogsManager.ManagingDialogsCallbacks {
ConversationViewModel conversationViewModel;
FragmentConversationBinding binding;
QBChatDialogMessageListener allDialogsMessagesListener;
SystemMessagesListener systemMessagesListener;
QBSystemMessagesManager systemMessagesManager;
QBIncomingMessagesManager incomingMessagesManager;
private DialogsManager dialogsManager;
public ConversationFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false);
getActivity().getWindow().setBackgroundDrawableResource(R.drawable.bg_img);
View view = binding.getRoot();
systemMessagesListener = new SystemMessagesListener();
dialogsManager = new DialogsManager();
return view;
}
private void setUpModel() {
Bundle mBundle = getArguments();
if (mBundle != null) {
conversationViewModel = new ConversationViewModel(getActivity(), binding, getArguments().getString("DialogIdData"));
} else {
conversationViewModel = new ConversationViewModel(getActivity(), binding, "");
}
binding.setConversationViewModel(conversationViewModel);
setUpObserver(conversationViewModel);
}
private void setUpObserver(ConversationViewModel observer) {
observer.addObserver(this);
}
#Override
public void update(Observable o, Object arg) {
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onResume() {
super.onResume();
setUpModel();
}
#Override
public void onPause() {
super.onPause();
unregisterQbChatListeners();
}
public void unregisterQbChatListeners() {
if (incomingMessagesManager != null) {
incomingMessagesManager.removeDialogMessageListrener(allDialogsMessagesListener);
}
if (systemMessagesManager != null) {
systemMessagesManager.removeSystemMessageListener(systemMessagesListener);
}
dialogsManager.removeManagingDialogsCallbackListener(this);
}
#Override
public void onDialogCreated(QBChatDialog chatDialog) {
}
#Override
public void onDialogUpdated(String chatDialog) {
}
#Override
public void onNewDialogLoaded(QBChatDialog chatDialog) {
}
private class SystemMessagesListener implements QBSystemMessageListener {
#Override
public void processMessage(final QBChatMessage qbChatMessage) {
dialogsManager.onSystemMessageReceived(qbChatMessage);
}
#Override
public void processError(QBChatException e, QBChatMessage qbChatMessage) {
}
}
private BroadcastReceiver mNotificationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
}
Here is my Fragment viewModel code :-
public class ConversationViewModel extends Observable implements DialogsManager.ManagingDialogsCallbacks {
private static final int REQUEST_DIALOG_ID_FOR_UPDATE = 165;
public Context mContext;
FragmentConversationBinding binding;
private ActionMode currentActionMode;
public QBRequestGetBuilder requestBuilder;
private int skipRecords = 0;
private DialogsAdapter dialogsAdapter;
private QBChatDialogMessageListener allDialogsMessagesListener;
private SystemMessagesListener systemMessagesListener;
private QBSystemMessagesManager systemMessagesManager;
private QBIncomingMessagesManager incomingMessagesManager;
private DialogsManager dialogsManager;
private QBUser currentUser;
private String id;
public ConversationViewModel(Context mContext, FragmentConversationBinding binding, String Dialogid) {
this.mContext = mContext;
this.binding = binding;
this.id = Dialogid;
initUI();
}
public void initUI() {
allDialogsMessagesListener = new AllDialogsMessageListener();
systemMessagesListener = new SystemMessagesListener();
dialogsManager = new DialogsManager();
currentUser = ChatHelper.getCurrentUser();
initList();
registerQbChatListeners();
if (QbDialogHolder.getInstance().getDialogs().size() > 0) {
loadDialogsFromQb(true, true);
} else {
loadDialogsFromQb(false, true);
}
if (!id.isEmpty()) {
loadUpdatedDialog(id);
id = "";
} else {
updateDialogsList();
}
}
public void initList() {
dialogsAdapter = new DialogsAdapter(mContext, new ArrayList<>(QbDialogHolder.getInstance().getDialogs().values()));
binding.listDialogsChats.setAdapter(dialogsAdapter);
binding.listDialogsChats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
QBChatDialog selectedDialog = (QBChatDialog) parent.getItemAtPosition(position);
if (currentActionMode == null) {
ChatActivity.startForResult(((Activity) mContext), REQUEST_DIALOG_ID_FOR_UPDATE, selectedDialog);
} else {
dialogsAdapter.toggleSelection(selectedDialog);
}
}
});
binding.listDialogsChats.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
QBChatDialog selectedDialog = (QBChatDialog) parent.getItemAtPosition(position);
dialogsAdapter.selectItem(selectedDialog);
return true;
}
});
requestBuilder = new QBRequestGetBuilder();
binding.swipyRefreshLayout.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh(SwipyRefreshLayoutDirection direction) {
requestBuilder.setSkip(skipRecords += ChatHelper.DIALOG_ITEMS_PER_PAGE);
loadDialogsFromQb(true, false);
}
});
}
private void loadUpdatedDialog(String dialogId) {
ChatHelper.getInstance().getDialogById(dialogId, new QbEntityCallbackImpl<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog result, Bundle bundle) {
QbDialogHolder.getInstance().addDialog(result);
updateDialogsAdapter();
}
#Override
public void onError(QBResponseException e) {
}
});
}
public void updateDialogsList() {
requestBuilder.setSkip(skipRecords = 0);
loadDialogsFromQb(true, true);
}
#Override
public void onDialogCreated(QBChatDialog chatDialog) {
updateDialogsAdapter();
}
#Override
public void onDialogUpdated(String chatDialog) {
updateDialogsAdapter();
}
#Override
public void onNewDialogLoaded(QBChatDialog chatDialog) {
updateDialogsAdapter();
}
private void registerQbChatListeners() {
incomingMessagesManager = QBChatService.getInstance().getIncomingMessagesManager();
systemMessagesManager = QBChatService.getInstance().getSystemMessagesManager();
if (incomingMessagesManager != null) {
incomingMessagesManager.addDialogMessageListener(allDialogsMessagesListener != null
? allDialogsMessagesListener : new AllDialogsMessageListener());
}
if (systemMessagesManager != null) {
systemMessagesManager.addSystemMessageListener(systemMessagesListener != null
? systemMessagesListener : new SystemMessagesListener());
}
dialogsManager.addManagingDialogsCallbackListener(this);
}
private class SystemMessagesListener implements QBSystemMessageListener {
#Override
public void processMessage(final QBChatMessage qbChatMessage) {
dialogsManager.onSystemMessageReceived(qbChatMessage);
}
#Override
public void processError(QBChatException e, QBChatMessage qbChatMessage) {
}
}
private class AllDialogsMessageListener extends QbChatDialogMessageListenerImp {
#Override
public void processMessage(final String dialogId, final QBChatMessage qbChatMessage, Integer senderId) {
if (!senderId.equals(ChatHelper.getCurrentUser().getId())) {
dialogsManager.onGlobalMessageReceived(dialogId, qbChatMessage);
}
}
}
public void updateDialogsAdapter() {
dialogsAdapter.updateList(new ArrayList<>(QbDialogHolder.getInstance().getDialogs().values()));
}
public void loadDialogsFromQb(final boolean silentUpdate, final boolean clearDialogHolder) {
if (!silentUpdate) {
binding.progressDialogs.setVisibility(View.VISIBLE);
}
ChatHelper.getInstance().getDialogs(requestBuilder, new QBEntityCallback<ArrayList<QBChatDialog>>() {
#Override
public void onSuccess(ArrayList<QBChatDialog> dialogs, Bundle bundle) {
binding.progressDialogs.setVisibility(View.GONE);
binding.swipyRefreshLayout.setRefreshing(false);
if (clearDialogHolder) {
QbDialogHolder.getInstance().clear();
}
QbDialogHolder.getInstance().addDialogs(dialogs);
updateDialogsAdapter();
}
#Override
public void onError(QBResponseException e) {
binding.progressDialogs.setVisibility(View.GONE);
binding.swipyRefreshLayout.setRefreshing(false);
Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
Here is my Chat Activity:-
public class ChatActivity extends BindingActivity<ActivityChatBinding> implements OnImagePickedListener {
ChatViewModel chatViewModel;
public static final int REQUEST_CODE_ATTACHMENT = 721;
public static final String EXTRA_DIALOG_ID = "dialogId";
#Override
protected int getLayoutId() {
return R.layout.activity_chat;
}
public static void startForResult(Activity activity, int code, QBChatDialog dialogId) {
Intent intent = new Intent(activity, ChatActivity.class);
intent.putExtra(ChatActivity.EXTRA_DIALOG_ID, dialogId);
activity.startActivityForResult(intent, code);
}
#Override
public void setInitBinding() {
getWindow().setBackgroundDrawableResource(R.drawable.bg_img);
chatViewModel = new ChatViewModel(this, binding);
binding.setChatViewModel(chatViewModel);
}
#Override
protected void setUpObserver() {
chatViewModel.addObserver(this);
}
#Override
public void update(Observable o, Object arg) {
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
#Override
public void onBackPressed() {
binding.getChatViewModel().releaseChat();
binding.getChatViewModel().sendDialogId();
super.onBackPressed();
}
#Override
public void onImagePicked(int requestCode, File file) {
switch (requestCode) {
case REQUEST_CODE_ATTACHMENT:
binding.getChatViewModel().attachmentPreviewAdapter.add(file);
break;
}
}
#Override
public void onImagePickError(int requestCode, Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onImagePickClosed(int requestCode) {
}
}
Chat Activity View Model :-
public class ChatViewModel extends Observable {
public Context mContext;
ActivityChatBinding binding;
public static final String TAG = ChatActivity.class.getSimpleName();
public static final int REQUEST_CODE_ATTACHMENT = 721;
public static final String PROPERTY_SAVE_TO_HISTORY = "save_to_history";
public static final String EXTRA_DIALOG_ID = "dialogId";
public ChatAdapter chatAdapter;
public AttachmentPreviewAdapter attachmentPreviewAdapter;
public QBChatDialog qbChatDialog;
public ArrayList<QBChatMessage> unShownMessages;
public int skipPagination = 0;
public ChatMessageListener chatMessageListener;
QBPrivacyList qbPrivacyList;
public static boolean mBlock;
public static int userId, recipientId;
public QBPrivacyListsManager privacyListsManager;
public ObservableField<String> chatMessage = new ObservableField<>("");
public ChatViewModel(Context mContext, ActivityChatBinding binding) {
this.mContext = mContext;
this.binding = binding;
Log.v(TAG, "onCreate ChaActivity on Thread ID = " + Thread.currentThread().getId());
qbChatDialog = (QBChatDialog) ((Activity) mContext).getIntent().getSerializableExtra(EXTRA_DIALOG_ID);
Log.v(TAG, "deserialized dialog = " + qbChatDialog);
qbChatDialog.initForChat(QBChatService.getInstance());
chatMessageListener = new ChatMessageListener();
qbPrivacyList = new QBPrivacyList();
privacyListsManager = QBChatService.getInstance().getPrivacyListsManager();
qbChatDialog.addMessageListener(chatMessageListener);
initViews();
initChat();
}
public void initViews() {
try {
recipientId = qbChatDialog.getRecipientId();
userId = qbChatDialog.getUserId();
getPrivacyList();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
}
attachmentPreviewAdapter = new AttachmentPreviewAdapter(mContext,
new AttachmentPreviewAdapter.OnAttachmentCountChangedListener() {
#Override
public void onAttachmentCountChanged(int count) {
binding.attachmentContainer.setVisibility(count == 0 ? View.GONE : View.VISIBLE);
}
},
new AttachmentPreviewAdapter.OnAttachmentUploadErrorListener() {
#Override
public void onAttachmentUploadError(QBResponseException e) {
Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
}
});
binding.attachmentAdapter.setAdapter(attachmentPreviewAdapter);
}
public void onAttachmentsClick(View view) {
new ImagePickHelper().pickAnImage(((FragmentActivity) mContext), REQUEST_CODE_ATTACHMENT);
}
private void initChat() {
switch (qbChatDialog.getType()) {
case PRIVATE:
loadDialogUsers();
break;
default:
Toaster.shortToast(String.format("%s %s", getString(R.string.chat_unsupported_type), qbChatDialog.getType().name()));
((Activity) mContext).finish();
break;
}
}
public void loadDialogUsers() {
ChatHelper.getInstance().getUsersFromDialog(qbChatDialog, new QBEntityCallback<ArrayList<QBUser>>() {
#Override
public void onSuccess(ArrayList<QBUser> users, Bundle bundle) {
String chatName = QbDialogUtils.getDialogName(qbChatDialog);
binding.dialogName.setText(chatName);
loadChatHistory();
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
}
});
}
public void loadChatHistory() {
ChatHelper.getInstance().loadChatHistory(qbChatDialog, skipPagination, new QBEntityCallback<ArrayList<QBChatMessage>>() {
#Override
public void onSuccess(ArrayList<QBChatMessage> messages, Bundle args) {
Collections.reverse(messages);
if (chatAdapter == null) {
chatAdapter = new ChatAdapter(mContext, qbChatDialog, messages);
chatAdapter.setPaginationHistoryListener(new PaginationHistoryListener() {
#Override
public void downloadMore() {
loadChatHistory();
}
});
chatAdapter.setOnItemInfoExpandedListener(new ChatAdapter.OnItemInfoExpandedListener() {
#Override
public void onItemInfoExpanded(final int position) {
if (isLastItem(position)) {
((Activity) mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
binding.listChat.setSelection(position);
}
});
} else {
binding.listChat.smoothScrollToPosition(position);
}
}
private boolean isLastItem(int position) {
return position == chatAdapter.getCount() - 1;
}
});
if (unShownMessages != null && !unShownMessages.isEmpty()) {
List<QBChatMessage> chatList = chatAdapter.getList();
for (QBChatMessage message : unShownMessages) {
if (!chatList.contains(message)) {
chatAdapter.add(message);
}
}
}
binding.listChat.setAdapter(chatAdapter);
binding.listChat.setAreHeadersSticky(false);
binding.listChat.setDivider(null);
} else {
chatAdapter.addList(messages);
binding.listChat.setSelection(messages.size());
}
binding.progressBar.setVisibility(View.GONE);
}
#Override
public void onError(QBResponseException e) {
binding.progressBar.setVisibility(View.GONE);
skipPagination -= ChatHelper.CHAT_HISTORY_ITEMS_PER_PAGE;
Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
}
});
skipPagination += ChatHelper.CHAT_HISTORY_ITEMS_PER_PAGE;
QBRestChatService.markMessagesAsRead(qbChatDialog.getDialogId(), null);
}
public class ChatMessageListener extends QbChatDialogMessageListenerImp {
#Override
public void processMessage(String s, QBChatMessage qbChatMessage, Integer integer) {
showMessage(qbChatMessage);
}
}
public void showMessage(QBChatMessage message) {
if (chatAdapter != null) {
chatAdapter.add(message);
scrollMessageListDown();
} else {
if (unShownMessages == null) {
unShownMessages = new ArrayList<>();
}
unShownMessages.add(message);
}
}
public void scrollMessageListDown() {
binding.listChat.setSelection(binding.listChat.getCount() - 1);
}
public void onSendChatClick(View view) {
int totalAttachmentsCount = attachmentPreviewAdapter.getCount();
Collection<QBAttachment> uploadedAttachments = attachmentPreviewAdapter.getUploadedAttachments();
if (!uploadedAttachments.isEmpty()) {
if (uploadedAttachments.size() == totalAttachmentsCount) {
for (QBAttachment attachment : uploadedAttachments) {
sendChatMessage(null, attachment);
}
} else {
Toaster.shortToast(R.string.chat_wait_for_attachments_to_upload);
}
}
String text = binding.getChatViewModel().chatMessage.get().trim();
if (!TextUtils.isEmpty(text)) {
sendChatMessage(text, null);
}
}
public void sendChatMessage(String text, QBAttachment attachment) {
QBChatMessage chatMessage = new QBChatMessage();
if (attachment != null) {
chatMessage.addAttachment(attachment);
} else {
chatMessage.setBody(text);
}
chatMessage.setProperty(PROPERTY_SAVE_TO_HISTORY, "1");
chatMessage.setDateSent(System.currentTimeMillis() / 1000);
chatMessage.setMarkable(true);
if (!QBDialogType.PRIVATE.equals(qbChatDialog.getType()) && !qbChatDialog.isJoined()) {
Toaster.shortToast("You're still joining a group chat, please wait a bit");
return;
}
try {
qbChatDialog.sendMessage(chatMessage);
if (QBDialogType.PRIVATE.equals(qbChatDialog.getType())) {
showMessage(chatMessage);
}
if (attachment != null) {
attachmentPreviewAdapter.remove(attachment);
} else {
binding.getChatViewModel().chatMessage.set("");
}
} catch (SmackException.NotConnectedException e) {
Log.w(TAG, e);
Toaster.shortToast("Can't send a message, You are not connected to chat");
}
}
public void leaveGroupDialog() {
try {
ChatHelper.getInstance().leaveChatDialog(qbChatDialog);
} catch (XMPPException | SmackException.NotConnectedException e) {
Log.w(TAG, e);
}
}
public void releaseChat() {
qbChatDialog.removeMessageListrener(chatMessageListener);
if (!QBDialogType.PRIVATE.equals(qbChatDialog.getType())) {
leaveGroupDialog();
}
}
public void sendDialogId() {
Intent result = new Intent();
result.putExtra(EXTRA_DIALOG_ID, qbChatDialog.getDialogId());
((Activity) mContext).setResult(RESULT_OK, result);
}
public void finishActivity(View view) {
((Activity) mContext).finish();
}
public void clickButtonBlock(View view) {
AppUtils.dialog(mContext);
if (mBlock) {
onClickUnblock();
} else {
onClickBlock();
}
}
public void getPrivacyList() throws SmackException.NotConnectedException, XMPPException.XMPPErrorException, SmackException.NoResponseException {
QBPrivacyListsManager privacyListsManager = QBChatService.getInstance().getPrivacyListsManager();
QBPrivacyList privacyList = privacyListsManager.getPrivacyList("public");
List<QBPrivacyListItem> items = privacyList.getItems();
int i;
for (i = 0; i < privacyList.getItems().size(); i++) {
QBPrivacyListItem item = items.get(i);
String valueForType = item.getValueForType();
String[] splitvalueType = valueForType.split("-");
String blockId = splitvalueType[0];
if (blockId.equalsIgnoreCase(String.valueOf(recipientId))) {
mBlock = true;
binding.tvBlock.setText("Unblock");
break;
} else {
binding.tvBlock.setText("Block");
}
}
}
}
The problem is chatDialog.getUnreadMessageCount() giving me count 2 when I once enter in chat room and come back to my chat listing page.
Description on issue:-
Example:-
I have installed my application in two devices. when i send message from one (Device A) to other (Device B).The device B will display correct Unread count i.e 1 . Now when i click on chat dialog and get entered inside the chat room (of Device B). and come back to it's listing page and then again try to send message from Device A to device B . This time the unread count comes as 2 but it should be one as i already viewed my previous message. This get more worse if i try to open my chat room again to read the message(Device B) and get back to my listing page(Device B) after reading the message . This time if I send the message from Device A to Device B, Then the count came out as "5" just for my one message this thing is making me sick, I debugged the whole code, it's chatDialog .getUnreadMessageCount() who is returning me count "5", I don't know why my previous messages are not counted as being read messages and why everytime I open chat room one additional number gets added up inside the unread count.Please help me out , i am scratching my head from past two days.
Your help will be greatly Appreciated.
Thanks
Problem is that your AllDialogsMessageListener is not getting unregistered so unregister it by calling unregisterQbChatListeners(); when you will be opening your chat room screen . Every thing will work fine once you do that.
This what i mean :-
binding.listDialogsChats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
QBChatDialog selectedDialog = (QBChatDialog) parent.getItemAtPosition(position);
if (currentActionMode == null) {
unregisterQbChatListeners();
ChatActivity.startForResult(((Activity) mContext), REQUEST_DIALOG_ID_FOR_UPDATE, selectedDialog);
} else {
dialogsAdapter.toggleSelection(selectedDialog);
}
}
});
private void unregisterQbChatListeners() {
if (incomingMessagesManager != null) {
incomingMessagesManager.removeDialogMessageListrener(allDialogsMessagesListener);
}
if (systemMessagesManager != null) {
systemMessagesManager.removeSystemMessageListener(systemMessagesListener);
}
dialogsManager.removeManagingDialogsCallbackListener(this);
}
cheers!!!
Please use this code below :
QBChatService.markMessagesAsRead("YOUR_DIALOG_ID", null, new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void aVoid, Bundle bundle) {
QBRequestGetBuilder requestBuilder = new QBRequestGetBuilder();
requestBuilder.eq("_id", Team.getCurrent().getChatId());
QBChatService.getChatDialogs(null, requestBuilder, new QBEntityCallback<ArrayList<QBDialog>>() {
#Override
public void onSuccess(ArrayList<QBDialog> qbDialogs, Bundle bundle) {
if (qbDialogs != null && qbDialogs.size() > 0) {
QBDialog dialog = qbDialogs.get(0);//here you get your dialog with unreadMessageCount = 0
}
}
#Override
public void onError(QBResponseException e) {
}
});
}
#Override
public void onError(QBResponseException e) {
}
});
In my form fragment Hardware "back" button work not correctly. For example when I opened fragment and when I didn't start typing, and I pressed Hardware "back" button it's work excellent. But when I started typing and after typing press to Hardware "back" button app crashed without any error logs.
my form fragment
public class D_Category_Login extends Fragment implements View.OnClickListener{
public static FragmentListItemClick fragmentListItemClick;
EditText edt_name,edt_lastname,edt_phone,edt_pass1,edt_pass2;
String name="";
DBHelper dbHelper;
public static final String REGISTER_URL = "http://admin.unimax.kz/api/Klientapi/AddClient?";
public static final String KEY_USERNAME = "first_name";
public static final String KEY_LASTNAME = "last_name";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.form_login, null);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Регистрация");
edt_name = (EditText) view.findViewById(R.id.edt_firstname);
edt_lastname = (EditText) view.findViewById(R.id.lastname);
edt_phone = (EditText) view.findViewById(R.id.login);
edt_pass1 = (EditText) view.findViewById(R.id.pass);
edt_pass2 = (EditText) view.findViewById(R.id.pass_repeet);
Button btn_submit = (Button) view.findViewById(R.id.btn_submit);
TextView tv_number = (TextView) view.findViewById(R.id.tv_number);
btn_submit.setOnClickListener(this);
tv_number.setOnClickListener(this);
edt_phone.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if(!s.toString().contains("+7 ")){
edt_phone.setText("+7 ");
Selection.setSelection(edt_phone.getText(), edt_phone.getText().length());
}
}
});
return view;
}
void setfragmentclick(FragmentListItemClick fr){
fragmentListItemClick = fr;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_submit:{
if (edt_name.getText().toString().trim().isEmpty() || edt_lastname.getText().toString().trim().isEmpty()){
if (edt_name.getText().toString().trim().isEmpty()) {
edt_name.setError("Заполните это поле");
requestFocus(edt_name);
}
if (edt_lastname.getText().toString().trim().isEmpty()) {
edt_lastname.setError("Заполните это поле");
requestFocus(edt_lastname);
}
}
else {
CheckInternet();
}
}
break;
case R.id.tv_number:{
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "+77079300066"));
startActivity(intent);
}
break;
}
}
void CheckInternet(){
if (isOnline()){
registerUser();
}
else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
alertDialogBuilder.setMessage("Проверьте подключение к Интернету");
alertDialogBuilder.setPositiveButton("Закрыть", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
void registerUser(){
final String first_name = edt_name.getText().toString().trim();
final String last_name = edt_lastname.getText().toString().trim();
String fill_url = REGISTER_URL+"familia="+Uri.encode(last_name)+"&name="+Uri.encode(first_name);
StringRequest stringRequest = new StringRequest(Request.Method.POST, fill_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dbHelper = new DBHelper(getContext());
final ContentValues cv = new ContentValues();
final SQLiteDatabase db = dbHelper.getWritableDatabase();
name+= String.valueOf(edt_name.getText()+" "+String.valueOf(edt_lastname.getText()));
cv.put("id_user", Integer.valueOf(response));
cv.put("name", name);
db.execSQL("delete from form_login");
db.insert("form_login",null, cv);
db.close();
dbHelper.close();
getFragmentManager().popBackStack();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Ошибка сервера"+error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
}
My form fragment is child fragment. And this parent fragment where I implement backaction.
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
backAction();
return true;
}
return false;
}
});
}
public void backAction() {
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
getChildFragmentManager().popBackStack();
}
else {
((MainActivity) getActivity()).setCurrentItem(0, true);
}
}
Create TextWatcher like
TextWatcher textWatcher=new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if(!s.toString().contains("+7 ")){
edt_phone.setText("+7 ");
Selection.setSelection(edt_phone.getText(), edt_phone.getText().length());
}
};
Add it to edt_phone like
edt_phone.addTextChangedListener(textWatcher);
Then in the back press event remove the listener,
getView().setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
edt_phone.removeTextChangedListener(textWatcher);
return true;
}
}
return false;
}
});
In your foam fragment(child fragment)
Communicator communicator;
#Override
public void onBackPressed() {
super.onBackPressed();
communicator.exitFragment();
}
public void setCommunicator(Communicator communicator)
{
this.communicator = communicator;
}
public interface Communicator
{
void exitFragment();
}
in your parent fragment do this
public parentFragment extends Fragment implements childFragment.Communicator
{
#override
public void onCreatView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
childFragment.setCommunicator(this);
}
public void exitFragment()
{
getActivity().finish();
}
}
Fragments are managed by the Fragment Managers which are called by the Activity; so, to control what you want to do when the back button is clicked, you must do that in the activity;
Now, if you have more than one fragment set, you should use tags to find them, check to see if they are visible and if so, do what you mentioned above.
When setting your fragments, you should give them a tag and then use this tag later to findFragmentByTagName() and do an if check to see which fragment is set at the moment;
Let me know if you need any clarification on the same.
I'm trying to get working a native android project that uses Worklight form based authentication. I'm already able to authenticate the user through the native APIs. The problem appears when I change between activities (intents). Once the user enters his information and submits the form, it is authenticated but the worklight server connection is lost.
This is the code:
MainActivity.java
public class MainActivity extends Activity {
private Button buttonConnect = null;
private Button buttonInvoke = null;
private static TextView textView = null;
private static MainActivity _this;
private MyChallengeHadler challengeHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_this = this;
buttonConnect = (Button)findViewById(R.id.buttonConnect);
buttonInvoke = (Button)findViewById(R.id.buttonInvoke);
textView = (TextView)findViewById(R.id.textView);
final WLClient client = WLClient.createInstance(this);
buttonConnect.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateTextView("Connecting...");
client.connect(new MyConnectListener());
challengeHandler = new MyChallengeHadler(MainActivity.this, "BasicAuth");
client.registerChallengeHandler(challengeHandler);
}
});
buttonInvoke.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateTextView("Invoking procedure...");
String adapterName = "RSSReader";
String procedureName = "getStoriesFiltered";
WLProcedureInvocationData invocationData =
new WLProcedureInvocationData(adapterName, procedureName);
Object[] parameters = new Object[] {"world"};
invocationData.setParameters(parameters);
WLRequestOptions options = new WLRequestOptions();
options.setTimeout(30000);
WLClient client = WLClient.getInstance();
client.invokeProcedure(invocationData, new MyInvokeListener(), options);
}
});
}
public static void updateTextView(final String str){
Runnable run = new Runnable() {
public void run() {
textView.setText(str);
}
};
_this.runOnUiThread(run);
}
}
LoginActivity.java
public class LoginActivity extends Activity {
private Button Submit = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Submit = (Button)findViewById(R.id.button1);
Submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
MyChallengeHadler challengeHandler = new MyChallengeHadler(LoginActivity.this, "BasicAuth");
challengeHandler.submitLogin(0, "maria", "maria", false);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MyChallengeHadler.java
public class MyChallengeHadler extends ChallengeHandler {
private WLResponse cachedResponse;
private final Activity parentActivity;
public MyChallengeHadler(final Activity a, String realm) {
super(realm);
this.parentActivity =a;
// TODO Auto-generated constructor stub
}
#Override
public void onFailure(WLFailResponse arg0) {
// TODO Auto-generated method stub
}
#Override
public void onSuccess(WLResponse arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean isCustomResponse(WLResponse response) {
if (response == null || response.getResponseText() == null
|| response.getResponseText().indexOf("j_security_check") == -1) {
return false;
}
return true;
}
#Override
public void handleChallenge(WLResponse response){
if (!isCustomResponse(response)) {
submitSuccess(response);
} else {
cachedResponse = response;
Intent login = new Intent(parentActivity, LoginActivity.class);
parentActivity.startActivityForResult(login, 1);
}
}
public void submitLogin(int resultCode, String userName, String password, boolean back){
HashMap<String, String> params = new HashMap<String, String>();
params.put("j_username", userName);
params.put("j_password", password);
submitLoginForm("/j_security_check", params, null, 0, "post");
Intent login = new Intent(parentActivity, MainActivity.class);
parentActivity.startActivityForResult(login, 1);
}
}
I have already solved my code's problem. I was using wrongly android's intents. This is the new version of the code:
LoginActivity.java
public class LoginActivity extends Activity {
private Button Submit;
private Intent result;
public static final String Back = "back";
public static final String UserNameExtra = "username";
public static final String PasswordExtra = "password";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Submit = (Button)findViewById(R.id.button1);
result = new Intent();
Submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
result.putExtra(UserNameExtra, "maria");
result.putExtra(PasswordExtra, "maria");
result.putExtra(Back, false);
setResult(RESULT_OK, result);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MainActivity.java
public class MainActivity extends Activity {
private Button buttonConnect = null;
private Button buttonInvoke = null;
private static TextView textView = null;
private static MainActivity _this;
private MyChallengeHadler challengeHandler;
private String realm = "BasicAuth";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_this = this;
buttonConnect = (Button)findViewById(R.id.buttonConnect);
buttonInvoke = (Button)findViewById(R.id.buttonInvoke);
textView = (TextView)findViewById(R.id.textView);
final WLClient client = WLClient.createInstance(this);
buttonConnect.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateTextView("Connecting...");
client.connect(new MyConnectListener());
challengeHandler = new MyChallengeHadler(MainActivity.this, realm);
client.registerChallengeHandler(challengeHandler);
}
});
buttonInvoke.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateTextView("Invoking procedure...");
String adapterName = "SOAPAdapter";
String procedureName = "getStories";
WLProcedureInvocationData invocationData =
new WLProcedureInvocationData(adapterName, procedureName);
//Object[] parameters = new Object[] {"world"};
//invocationData.setParameters(parameters);
WLRequestOptions options = new WLRequestOptions();
options.setTimeout(30000);
WLClient client = WLClient.getInstance();
client.invokeProcedure(invocationData, new MyResponseListener(), options);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
boolean back = data.getBooleanExtra(LoginActivity.Back, true);
String username = data.getStringExtra(LoginActivity.UserNameExtra);
String password = data.getStringExtra(LoginActivity.PasswordExtra);
challengeHandler.submitLogin(resultCode, username, password, back);
}
public static void updateTextView(final String str){
Runnable run = new Runnable() {
public void run() {
textView.setText(str);
}
};
_this.runOnUiThread(run);
}
}
MyChallengeHadler.java
public class MyChallengeHadler extends ChallengeHandler {
private WLResponse cachedResponse;
private final Activity parentActivity;
public MyChallengeHadler(final Activity a, String realm) {
super(realm);
parentActivity =a;
// TODO Auto-generated constructor stub
}
#Override
public void onFailure(WLFailResponse arg0) {
// TODO Auto-generated method stub
}
#Override
public void onSuccess(WLResponse arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean isCustomResponse(WLResponse response) {
if (response == null || response.getResponseText() == null
|| response.getResponseText().indexOf("j_security_check") == -1) {
return false;
}
return true;
}
#Override
public void handleChallenge(WLResponse response){
if (!isCustomResponse(response)) {
submitSuccess(response);
} else {
cachedResponse = response;
Intent login = new Intent(parentActivity, LoginActivity.class);
parentActivity.startActivityForResult(login, 1);
}
}
public void submitLogin(int resultCode, String userName, String password, boolean back){
if (resultCode != Activity.RESULT_OK || back) {
submitFailure(cachedResponse);
} else {
HashMap<String, String> params = new HashMap<String, String>();
params.put("j_username", userName);
params.put("j_password", password);
submitLoginForm("/j_security_check", params, null, 0, "post");
}
}
}
Please help me. I don't know why, but after screen rotation EditText is empty. I use setRetainInstance(true), but it doesn't help for me. Please tell me what is the right way to save dialog's state and EditText's state with selection and text
My code:
public class InputTextDialog extends DialogFragment implements OnClickListener {
static final String DIALOG_TAG = "InputTextDialog";
static EditText input;
String initialText;
InputTextDialogListener inputTextDialogListener = null;
public interface InputTextDialogListener {
void onChangeText(String text);
}
public void setInputTextDialogListener(InputTextDialogListener listener) {
inputTextDialogListener = listener;
}
public void setInitialText(String text) {
initialText = text;
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onDestroyView() {
if (getDialog() != null && getRetainInstance())
getDialog().setDismissMessage(null);
super.onDestroyView();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
input = new EditText(getActivity());
input.setHint("Enter your text");
if (initialText != null) {
input.setText(initialText);
} else {
input.setText("");
}
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity())
.setTitle("Enter your text").setPositiveButton("Apply", this)
.setNegativeButton("Cancel", this).setView(input);
return adb.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == Dialog.BUTTON_POSITIVE && inputTextDialogListener != null) {
inputTextDialogListener.onChangeText(input.getText().toString());
}
}
}
Show dialog in activity:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
InputTextDialog inputDialog = new InputTextDialog();
inputDialog.setInitialText(initialText);
inputDialog.setInputTextDialogListener(new InputTextDialogListener() {
#Override
public void onChangeText(String text) {
resultText = text;
}
});
inputDialog.show(getSupportFragmentManager(), InputTextDialog.DIALOG_TAG);
}
});
Thanks I solved this by:
package com.xfakehopex.lovelywidget.Dialogs;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.EditText;
public class InputTextDialog extends DialogFragment implements OnClickListener {
public static final String DIALOG_TAG = "InputTextDialog";
private static final String DIALOG_TITLE_BUNDLE= "dialogTitle";
private static final String DIALOG_TEXT_BUNDLE= "dialogText";
private static final String DIALOG_TEXT_SELECTION_START_BUNDLE = "dialogTextSelectionStart";
private static final String DIALOG_TEXT_SELECTION_END_BUNDLE = "dialogTextSelectionEnd";
private EditText input;
private String initialText;
private String title;
InputTextDialogListener inputTextDialogListener = null;
public interface InputTextDialogListener {
void onChangeText(String text);
}
public void setInputTextDialogListener(InputTextDialogListener listener) {
inputTextDialogListener = listener;
}
public void setInitialText(String text) {
initialText = text;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
input = new EditText(getActivity());
input.setHint("Введите текст");
if (savedInstanceState != null) {
String text = savedInstanceState.getString(DIALOG_TEXT_BUNDLE);
title = savedInstanceState.getString(DIALOG_TITLE_BUNDLE);
int selectionStart = savedInstanceState.getInt(DIALOG_TEXT_SELECTION_START_BUNDLE);
int selectionEnd = savedInstanceState.getInt(DIALOG_TEXT_SELECTION_END_BUNDLE);
input.setText(text);
input.setSelection(selectionStart, selectionEnd);
}
else
{
if (initialText != null) {
input.setText(initialText);
} else {
input.setText("");
}
}
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity())
.setTitle(title).setPositiveButton("Apply", this)
.setNegativeButton("Cancel", this).setView(input);
return adb.create();
}
#Override
public void onSaveInstanceState(Bundle saved) {
super.onSaveInstanceState(saved);
saved.putString(DIALOG_TEXT_BUNDLE, input.getText().toString());
saved.putString(DIALOG_TITLE_BUNDLE, title);
saved.putInt(DIALOG_TEXT_SELECTION_START_BUNDLE, input.getSelectionStart());
saved.putInt(DIALOG_TEXT_SELECTION_END_BUNDLE, input.getSelectionEnd());
}
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == Dialog.BUTTON_POSITIVE && inputTextDialogListener != null) {
inputTextDialogListener.onChangeText(input.getText().toString());
}
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
i want to integrate flurry in my app. in the following code i am integrate flurry but that was not working properly in android. flurry listener call its method two times. how it working please help me.
LoginActivity.java
public class LoginActivity extends Activity implements OnClickListener,
AsyncTaskCompleteListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
setContentView(R.layout.login_activity);
Map<String, String> map = new HashMap<String, String>();
map.put("url", NFLConstanants.LOGIN_URL);
map.put("username", strUser);
map.put("passwd", strPassword);
new ParseController(LoginActivity.this, map,
NFLConstanants.SERVICE_CODE0, 1);
}
#Override
protected void onStart() {
super.onStart();
System.out.println("call on start method");
FlurryAgent.onStartSession(this, MACUtils.APIKEY_FLURRY);
FlurryAgent.enableTestAds(true);
FlurryAgent.initializeAds(this);
FlurryAgent.setLogEnabled(true);
}
#Override
protected void onStop() {
super.onStop();
System.out.println("call on stop method");
FlurryAgent.onEndSession(this);
}
#Override
public void onTaskCompleted(String responce, int sc) {
if (FlurryAgent.isAdAvailable(LoginActivity.this,
MACUtils.myAdSpaceName,
FlurryAdSize.FULLSCREEN, MACUtils.timeout)) {
final String msgv = "To help keep this app free please watch this short video. Thanks";
AlertDialog.Builder dlg = new AlertDialog.Builder(
LoginActivity.this);
dlg.setCancelable(false);
dlg.setTitle("Message");
dlg.setMessage(msgv);
dlg.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
try {
MyAdListener myAdListener = new MyAdListener(
LoginActivity.this,
LoginActivity.this, "3");
FlurryAgent
.setAdListener(myAdListener);
FrameLayout container = new FrameLayout(
LoginActivity.this);
FlurryAgent
.getAd(LoginActivity.this,
MACUtils.myAdSpaceName,
container,
FlurryAdSize.FULLSCREEN,
MACUtils.timeout);
} catch (Exception e) {
e.printStackTrace();
}
}
});
AlertDialog alert = dlg.create();
alert.show();
}
}
}
MyAdListener.java
public class MyAdListener implements FlurryAdListener {
public Activity activity;
public Context ctx;
String pagePosition;
boolean isDialogLaunch = false;
public MyAdListener(Activity act, Context ctx, String page) {
this.activity = act;
this.pagePosition = page;
this.ctx = ctx;
this.isDialogLaunch = false;
}
#Override
public boolean shouldDisplayAd(String myAdSpaceName, FlurryAdType type) {
System.out.println("shouldDisplayAd:: " + type);
return true;
}
#Override
public void onAdClosed(String myAdSpaceName) {
System.out.println("onAdClosed::: " + myAdSpaceName);
if (pagePosition.equals("1") || pagePosition.equals("2")) {
actionOnFlurryVideo();
} else {
if (!FlurryAgent.isAdAvailable(activity, MACUtils.myAdSpaceName,
FlurryAdSize.FULLSCREEN, MACUtils.timeout)) {
Intent macIntent = new Intent(activity, MACCustomTab.class);
macIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(macIntent);
activity.finish();
}
}
}
#Override
public void onApplicationExit(String myAdSpaceName) {
System.out.println("onApplicationExit:: " + myAdSpaceName);
actionOnFlurryVideo();
}
#Override
public void onRenderFailed(String adSpace) {
System.out.println("onRenderFailed:: " + adSpace);
actionOnFlurryVideo();
}
#Override
public void spaceDidReceiveAd(String adSpace) {
System.out.println("spaceDidReceiveAd:: " + adSpace);
}
#Override
public void spaceDidFailToReceiveAd(String adSpace) {
System.out.println("spaceDidFailToReceiveAd:: " + adSpace);
}
#Override
public void onAdClicked(String id) {
System.out.println("onAdClicked:: " + id);
}
#Override
public void onAdOpened(String id) {
System.out.println("onAdOpened::: " + id);
}
public void actionOnFlurryVideo() {
System.out.println("call actionOnflurryvideo");
if (pagePosition.equals("1") || pagePosition.equals("2")) {
if (!isDialogLaunch) {
isDialogLaunch = true;
final String msg = "Thanks for supporting our free website. Your bet has now been confirmed.";
AlertDialog.Builder dlg = new AlertDialog.Builder(ctx);
dlg.setCancelable(false);
dlg.setTitle("Message");
dlg.setMessage(msg);
dlg.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
NavigationGroupActivity parent = ((NavigationGroupActivity) activity
.getParent());
parent.backToFirst();
}
});
AlertDialog alert = dlg.create();
alert.show();
}
} else {
Intent macIntent = new Intent(activity, MACCustomTab.class);
macIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(macIntent);
activity.finish();
}
}
}
This issue will be fixed in our next release which is expected to come out very soon.
(Full disclosure: I work in the Support team at Flurry)