Can't remove bitmaps from memory using Picasso and scrollGalleryView - android

I have an Activity in which I load bitmaps in a ScrollGalleryView using Picasso.
When I exit from that activity and enter again the memory is not emptied and an OutOfMemory error is thrown.
I tried using .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE) in Picasso but the images are still loaded and kept in memory.
I also tried to recycle the bitmaps when the back button is pressed but I still had no luck.
This is the code i'm using:
//Method called in the onCreate that loads the photo in the scrollGalleryView:
private void loadPhotos() {
savedImages = new ArrayList<Uri>();
File file = new File(getPhotoDirectory());
File[] files = file.listFiles();
if (files != null) {
for (File f : files) { // loop and print all file
savedImages.add(Uri.fromFile(f));
}
}
if (!savedImages.isEmpty()) {
for (final Uri savedImage : savedImages) {
if (savedImage.getLastPathSegment().contains(radiatorId)) {
scrollGalleryView.setVisibility(View.VISIBLE);
RadiatorSettingsMediaLoader mMediaLoader = new RadiatorSettingsMediaLoader(savedImage);
scrollGalleryView.addMedia(MediaInfo.mediaLoader(mMediaLoader));
}
}
}
}
class RadiatorSettingsMediaLoader implements MediaLoader {
Uri savedImage;
public RadiatorSettingsMediaLoader(Uri savedImage) {
this.savedImage = savedImage;
}
#Override
public boolean isImage() {
return true;
}
#Override
public void loadMedia(final Context context, final ImageView imageView,
final MediaLoader.SuccessCallback callback) {
imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public ViewTreeObserver.OnGlobalLayoutListener getLayoutListener() {
return this;
}
#Override
public void onGlobalLayout() {
Picasso.with(getApplicationContext()).load(savedImage)
.resize(imageView.getWidth(), (imageView.getHeight()) - 175)
.centerInside()
.placeholder(imageView.getDrawable())
.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
callback.onSuccess();
imageView.setPadding(0, 0, 0, 175);
imageView.getViewTreeObserver().removeOnGlobalLayoutListener(getLayoutListener());
Picasso.with(getApplicationContext()).invalidate(new File(savedImage.getPath()));
}
#Override
public void onError() {
Toast.makeText(context, "non sono riuscito a caricare l'immagine", Toast.LENGTH_SHORT).show();
imageView.getViewTreeObserver().removeOnGlobalLayoutListener(getLayoutListener());
loadMedia(context, imageView, callback);
}
});
imageViewsToClear.add(imageView);
}
});
}
#Override
public void loadThumbnail(final Context context, final ImageView thumbnailView,
final MediaLoader.SuccessCallback callback) {
thumbnailView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public ViewTreeObserver.OnGlobalLayoutListener getLayoutListener() {
return this;
}
#Override
public void onGlobalLayout() {
Picasso.with(context)
.load(savedImage)
.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.into(thumbnailView, new Callback() {
#Override
public void onSuccess() {
callback.onSuccess();
thumbnailView.setLongClickable(true);
thumbnailView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(RadiatorSettingsActivity.this);
builder.setTitle(R.string.safe_delete_photo_title).setMessage(R.string.safe_delete_photo_text);
builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
File fdelete = new File(savedImage.getPath());
if (fdelete.exists()) {
if (fdelete.delete()) {
deleteFileFromMediaStore(getContentResolver(), fdelete);
System.out.println("file Deleted ");
finish();
startActivity(getIntent().putExtra("PhotoRemoved", true));
} else {
System.out.println("file not Deleted :");
}
}
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
return true;
}
});
thumbnailView.getViewTreeObserver()
.removeOnGlobalLayoutListener(getLayoutListener());
}
#Override
public void onError() {
Toast.makeText(context, "errore a caricare thumbnail", Toast.LENGTH_SHORT).show();
loadThumbnail(context, thumbnailView, callback);
thumbnailView.getViewTreeObserver()
.removeOnGlobalLayoutListener(getLayoutListener());
}
});
imageViewsToClear.add(thumbnailView);
}
});
}
}

Call this in your program
public void clearAllResources() {
// Set related variables null
System.gc();
Runtime.getRuntime().gc();
}
that is clearAllResources(); on start of activity

Related

How do I check if the download completed in onCreate android fetch library?

How do I check if the download completed in onCreate fetch library?
The following code work without problem, but maybe user cancel the download operation before completion and incomplete file exists in the path.
public class MainActivity extends AppCompatActivity implements FetchObserver<Download> {
private Button Edame, tavaghof, DownloadImage, online;
public static TextView etaTextView;
public static TextView downloadSpeedTextView;
public static Request request;
public static Fetch fetch;
public static ProgressBar progressBar;
public static TextView progressTextView;
private LinearLayout dllaye;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
File root = android.os.Environment.getExternalStorageDirectory();
File path = new File(root.getAbsolutePath() + "/telavat/" + "naba.mp3");
if (path.exists()) {
dllaye.setVisibility(View.GONE);
}
} catch (Exception e) {
}
FetchConfiguration fetchConfiguration = new FetchConfiguration.Builder(this)
.setDownloadConcurrentLimit(3)
.build();
fetch = Fetch.Impl.getInstance(fetchConfiguration);
DownloadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
enqueueDownload();
}
});
Edame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetch.resume(request.getId());
}
});
tavaghof.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetch.pause(request.getId());
}
});
//EndOnceate
}
private void enqueueDownload() {
File root = android.os.Environment.getExternalStorageDirectory();
final String url = "https://amoozesh3.ir/play/naba.mp3";
final String filePath = root.getAbsolutePath() + "/telavatquran/" + Uri.parse(url).getLastPathSegment();
request = new Request(url, filePath);
request.setExtras(getExtrasForRequest(request));
fetch.attachFetchObserversForDownload(request.getId(), this)
.enqueue(request, new Func<Request>() {
#Override
public void call(#NotNull Request result) {
request = result;
}
}, new Func<Error>() {
#Override
public void call(#NotNull Error result) {
}
});
}
#Override
protected void onResume() {
super.onResume();
if (request != null) {
fetch.attachFetchObserversForDownload(request.getId(), this);
}
}
#Override
protected void onPause() {
super.onPause();
if (request != null) {
fetch.removeFetchObserversForDownload(request.getId(), this);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
fetch.close();
}
#Override
public void onChanged(Download data, #NotNull Reason reason) {
updateViews(data, reason);
}
private Extras getExtrasForRequest(Request request) {
final MutableExtras extras = new MutableExtras();
extras.putBoolean("testBoolean", true);
extras.putString("testString", "test");
extras.putFloat("testFloat", Float.MIN_VALUE);
extras.putDouble("testDouble", Double.MIN_VALUE);
extras.putInt("testInt", Integer.MAX_VALUE);
extras.putLong("testLong", Long.MAX_VALUE);
return extras;
}
private void updateViews(#NotNull Download download, Reason reason) {
if (request.getId() == download.getId()) {
if (reason == Reason.DOWNLOAD_COMPLETED) {
dllaye.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "File download successful",
Toast.LENGTH_LONG).show();
}
setProgressView(download.getStatus(), download.getProgress());
etaTextView.setText(Utils.getETAString(this, download.getEtaInMilliSeconds()));
downloadSpeedTextView.setText(Utils.getDownloadSpeedString(this, download.getDownloadedBytesPerSecond()));
}
}
private void setProgressView(#NonNull final Status status, final int progress) {
switch (status) {
case QUEUED: {
progressTextView.setText(R.string.queued);
progressBar.setProgress(progress);
break;
}
case ADDED: {
progressTextView.setText(R.string.added);
progressBar.setProgress(progress);
break;
}
case DOWNLOADING: {
if (progress == -1) {
progressTextView.setText(R.string.downloading);
progressBar.setProgress(progress);
} else {
final String progressString = getResources().getString(R.string.percent_progress, progress);
progressTextView.setText(progressString);
progressBar.setProgress(progress);
}
break;
}
case COMPLETED: {
break;
}
default: {
progressTextView.setText(R.string.status_unknown);
progressBar.setProgress(progress);
break;
}
}
}
}
I want to free up more space on the screen after downloading
How can I understand the download is completed?
I’d appreciate your cooperation.

how to show prograss bar before loading the image in Picasso. and then if image is loaded then start stories progressview in android

I am working on the project to create the stories like whatsapp or instagram.
we are using the library from Github
Our image are loaded from firebase.
but the problem is that stories start with loading the image because image size is large.
#Override
public void onFirebaseLoadSuccess(final List<Movie> movieList) {
storiesProgressView.setStoriesCount(movieList.size());
storiesProgressView.setStoryDuration(1500L);
Picasso.get().load(movieList.get(counter).getImage()).into(imageView, new Callback() {
#Override
public void onSuccess() {
progressBar.setVisibility(View.GONE);
storiesProgressView.startStories();
}
#Override
public void onError(Exception e) {
}
});
storiesProgressView.setStoriesListener(new StoriesProgressView.StoriesListener() {
#Override
public void onNext() {
if(counter < movieList.size()){
counter++;
Picasso.get().load(movieList.get(counter).getImage()).into(imageView);
}
}
#Override
public void onPrev() {
if(counter > 0){
counter--;
Picasso.get().load(movieList.get(counter).getImage()).into(imageView);
}
}
#Override
public void onComplete() {
counter = 0;
Toast.makeText(MainActivity.this,"Completed!",Toast.LENGTH_LONG).show();
finish();
}
});
}
Picasso doesn't has a function to check when load started so i highly recommend you to use Glide instead of Picasso.
Here, you can show progress bar when image loading is started via onLoadStarted() function :
Glide.with(this).load(movieList.get(counter).getImage()).into(new Target<GlideDrawable>() {
#Override
public void onStart() {
}
#Override
public void onStop() {
}
#Override
public void onDestroy() {
}
#Override
public void onLoadStarted(Drawable placeholder) {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
}
#Override
public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
progressBar.setVisibility(View.GONE);
imageView.setImageDrawable(resource);
storiesProgressView.startStories();
}
#Override
public void onLoadCleared(Drawable placeholder) {
}
#Override
public void getSize(SizeReadyCallback cb) {
}
#Override
public void setRequest(Request request) {
}
#Override
public Request getRequest() {
return null;
}
});

Picasso context error

I'm using fragement actitivty ,but context error
Picasso.get(activity)
this line activity error
public void setdetails(FragmentActivity activity, String sitename, String sitelink, final String imageuri) {
TextView District = (TextView) mview.findViewById(R.id.txtsitename);
final ImageView imageView = (ImageView) mview.findViewById(R.id.imgsiteimage);
Picasso.get(activity).load(imageuri).networkPolicy(NetworkPolicy.OFFLINE).into(imageView, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
Picasso.get().load(imageuri).placeholder(R.drawable.loadbar).into(imageView);
}
});
Remove activity from get() like this.
Picasso.get().load(imageuri).networkPolicy(NetworkPolicy.OFFLINE).into(imageView, new Callback()
This will fix your problem.
Replace activity with context like this
File file = new File(filePath);
Picasso.with(context).load(file).placeholder(R.drawable.draw_detailed_view_display).error(R.drawable.draw_detailed_view_display)
.resize(400, 400).into(mImageView, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
mImageView.setVisibility(View.GONE);
}
});

count on chat does not working correctly QuickBlox

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) {
}
});

How to Flurry Intigration with FlurryAdListener in android

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)

Categories

Resources