how to get instance chat message without press back button in quickblox - android

I want to get message in my chat activity without press back button in Quickblox instance chat
userData = new QBUser();
userData.setEmail(uNameStr);
userData.setPassword(uPwdStr);
userData.setId(user.getId());

You have to set listeners after the privateChat.sendMessage(chatMessage); so when you get success in listeners call notifydatasetchange method of the adapter.
private void sendMessage() {
// privateChatManager = chatService.getPrivateChatManager();
Log.d("PRIVATE", ">>>>> " + privateChatManager);
Log.d("INST", ">>>>> " + QBChatService.getInstance());
Log.d("CHAT ", "" + chatService);
Log.d("PRI", ">>>>> " + QBChatService.getInstance().getPrivateChatManager());
//login to chat firstly
if (messageEdt.length() > 0) {
privateChatMessageListener = new QBMessageListener<QBPrivateChat>() {
#Override
public void processMessage(QBPrivateChat privateChat, final QBChatMessage chatMessage) {
Log.e("privateChat ", " " + privateChat);
Log.e("chatMessage", "" + chatMessage);
chatListAdapter.notifyDataSetChanged();
}
#Override
public void processError(QBPrivateChat privateChat, QBChatException error, QBChatMessage originMessage) {
Log.e("privateChat ", " " + privateChat);
Log.e("QBChatMessage", "" + originMessage);
Log.e("error", "" + error);
}
};
privateChatManagerListener = new QBPrivateChatManagerListener() {
#Override
public void chatCreated(final QBPrivateChat privateChat, final boolean createdLocally) {
if (!createdLocally) {
privateChat.addMessageListener(privateChatMessageListener);
}
}
};
ChattingFragment.chatService.getPrivateChatManager().addPrivateChatManagerListener(privateChatManagerListener);
try {
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setBody(messageEdt.getText().toString());
chatMessage.setProperty("save_to_history", "1"); // Save a message to history
chatMessage.setProperty("notification_type", "1");
chatMessage.setSenderId(Integer.parseInt(Util.ReadSharePrefrence(getApplicationContext(), Constant.SHRED_PR.KEY_QB_USERID)));
chatMessage.setRecipientId(opponentId);
chatMessage.setMarkable(true);
privateChatManager = QBChatService.getInstance().getPrivateChatManager();
QBPrivateChat privateChat = privateChatManager.getChat(opponentId);
if (privateChat == null) {
privateChat = privateChatManager.createChat(opponentId, privateChatMessageListener);
}
// send message
privateChat.sendMessage(chatMessage);
privateChat.addMessageSentListener(privateChatMessageSentListener);
privateChat.addMessageListener(privateChatMessageListener);
} catch (SmackException.NotConnectedException e) {
Toast.makeText(PrivateChat.this, "Exception " + e, Toast.LENGTH_SHORT).show();
}
}
}
private QBMessageSentListener<QBPrivateChat> privateChatMessageSentListener = new QBMessageSentListener<QBPrivateChat>() {
#Override
public void processMessageSent(QBPrivateChat qbChat, QBChatMessage qbChatMessage) {
Log.d("MEHUL", "M " + qbChat);
Log.d("MSG", "MSG " + qbChatMessage);
hashmap = new HashMap<String, String>();
hashmap.put("id", "" + qbChatMessage.getId());
if (qbChatMessage.getBody() != null) {
hashmap.put("msg", "" + qbChatMessage.getBody());
} else {
hashmap.put("msg", "");
}
hashmap.put("recipient_id", "" + opponentId);
hashmap.put("sender_id", "" + user_id);
Collection<QBAttachment> collection = qbChatMessage.getAttachments();
if (collection != null && collection.size() > 0) {
for (QBAttachment attachment : collection) {
String imageid = attachment.getId();
String RecivedUrl = attachment.getUrl();
hashmap.put("url", "" + RecivedUrl);
}
//Here is the AsyncTask where I am trying to download image
//
}
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
// textView is the TextView view that should display it
hashmap.put("updated_at", "" + currentDateTimeString);
chatArraylist.add(hashmap);
Toast.makeText(getApplicationContext(), "Message Sent Successfully", Toast.LENGTH_SHORT).show();
messageEdt.setText("");
chatListAdapter = new PrivateChatMsgListAdapter(getApplicationContext(), chatArraylist);
lvChatDetails.setAdapter(chatListAdapter);
lvChatDetails.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
lvChatDetails.setStackFromBottom(true);
chatListAdapter.notifyDataSetChanged();
scrollMyListViewToBottom();
}
#Override
public void processMessageFailed(QBPrivateChat qbChat, QBChatMessage qbChatMessage) {
Log.d("MEHUL", "M " + qbChat);
Log.d("MSG", "ERR " + qbChatMessage);
}
};

Related

Multiple retrofit freeze ui

I use multiple retrofit in a service and my ui freeze,
So I try with asyncTask executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
I try also with a Thread but I have the same problem.
I put only one retrofit function for example, the other function is similar.
I read this in other post : Retrofit already run in the background so it cannot block your UI. I assume it must be something else
I use the same function with socket and asyncTask and screen doesn't freeze.
So I don't find the problem
public class RestApiService extends Service {
private Retrofit retrofit;
private RetrofitInterface retrofitInterface;
private String BASE_URL = "http://******.com:8080";
****
#Override
public void onCreate() {
if (BuildConfig.DEBUG)
Log.v(Constants.TAG6,"onCreate");
retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
retrofitInterface = retrofit.create(RetrofitInterface.class);
session = new SessionManager(getApplicationContext());
postemanager = new PosteManager(getApplicationContext());
contactmanager = new ContactManager(getApplicationContext());
commentmanager = new CommentManager(getApplicationContext());
groupeManager = new GroupeManager(getApplicationContext());
notifHelp = new NotificationHelper(getApplicationContext());
tinydb = new TinyDB(YuYuApplication.getAppContext());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
/*GetLists getLists = new GetLists();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
getLists.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
getLists.execute(); */
getListPosts();
getListCallbackReceivedPoste();
getListCallbackReceivedComment();
getListPostVu();
getListPostVuFromWeb();
getListCommentVu();
getListCommentVuFromWeb();
/* new Thread(new Runnable() {
#Override
public void run() {
getListPosts();
getListCallbackReceivedPoste();
getListCallbackReceivedComment();
getListPostVu();
getListPostVuFromWeb();
getListCommentVu();
getListCommentVuFromWeb();
}
}).start(); */
return Service.START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
class GetLists extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
getListPosts();
getListCallbackReceivedPoste();
getListCallbackReceivedComment();
getListPostVu();
getListPostVuFromWeb();
getListCommentVu();
getListCommentVuFromWeb();
return null;
}
}
public void getListPosts(){
Call<ArrayList<PosteFromServer>> call = retrofitInterface.getListPosts(session.getPhoneSession());
call.enqueue(new Callback<ArrayList<PosteFromServer>>() {
#Override
public void onResponse(Call<ArrayList<PosteFromServer>> call, Response<ArrayList<PosteFromServer>> response) {
ArrayList<PosteFromServer> myDataList = response.body();
Poste poste = new Poste();
final JSONArray callbackList = new JSONArray();
for (int i = 0; i < myDataList.size(); i++) {
if (postemanager.CheckIsIdPostEmetAlreadyInDBorNot(myDataList.get(i).getIdPostEmet()) == false) {
int nbPostNotRead = session.getNumbrePostNotRead();
nbPostNotRead++;
int nbCmtNotRead = session.getNumbreCommentNotRead();
session.createNumbrePostNotRead(nbPostNotRead);
//Notification counter
try {
// Badges.removeBadge(getApplicationContext());
// Alternative way
Badges.setBadge(getApplicationContext(), nbPostNotRead + nbCmtNotRead);
if (BuildConfig.DEBUG) {
int Nb = nbPostNotRead + nbCmtNotRead;
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, "Badges Poste ; CMT " + nbPostNotRead + " " + nbCmtNotRead);
Log.v(Constants.TAG6, "Badges Poste + CMT " + Nb);
}
}
} catch (BadgesNotSupportedException badgesNotSupportedException) {
if (BuildConfig.DEBUG) {
Log.d(Constants.TAG6, "getListPost BADGES MSG:" + badgesNotSupportedException.getMessage());
}
}
final JSONObject callback = new JSONObject();
try {
callback.put("app_id", myDataList.get(i).getApp_id());
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, "getListPost app_id " + myDataList.get(i).getApp_id());
}
/* Contact cdest = new Contact();
ArrayList<Contact> cdestList = new ArrayList<>();
cdest.setPhone(session.getPhoneSession());
cdestList.add(cdest);
sendCallback.put("destPhone",cdestList); */
callback.put("destPhone", session.getPhoneSession());
callback.put("idPostEmet", myDataList.get(i).getIdPostEmet());
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, "emmetteur" + myDataList.get(i).getEmetr_phone());
}
callback.put("emetr_phone", myDataList.get(i).getEmetr_phone());
callback.put("typeOfCallback", "callBackDevice");
} catch (JSONException e) {
e.printStackTrace();
}
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, "called emit message");
}
if (BuildConfig.DEBUG) {
Log.d(Constants.TAG6, "Handling friendcall");
}
//Catching IdMessages
boolean checkGroupNotification = false;
try {
if (BuildConfig.DEBUG)
Log.d(Constants.TAG6, " GROUPES " + myDataList.get(i).getGroups());
groups = Utils.convertStringToDummyObject(myDataList.get(i).getGroups().toString());
//TODO idGroup exit in TinyDB for notification purpose
TinyDB tinydb = new TinyDB(YuYuApplication.getAppContext());
ArrayList<String> mIdArray = tinydb.getListString("ids");
for (int j = 0; j < mIdArray.size(); j++)
for (int k = 0; k < groups.size(); k++)
if (mIdArray.get(k).equals(groups.get(k).getId())) {
checkGroupNotification = true;
break;
}
} catch (Exception ex) {
groups = null;
}
//Catching IdMessages
boolean checkGroupSon = false;
try {
groups = Utils.convertStringToDummyObject(myDataList.get(i).getGroups().toString());
//TODO idGroup exit in TinyDB for notification purpose
TinyDB tinydb = new TinyDB(YuYuApplication.getAppContext());
ArrayList<String> mIdArraySon = tinydb.getListString("idGroupsSon");
for (int j = 0; j < mIdArraySon.size(); j++)
for (int k = 0; k < groups.size(); k++)
if (mIdArraySon.get(j).equals(groups.get(k).getId())) {
checkGroupSon = true;
break;
}
} catch (Exception ex) {
groups = null;
}
try {
if (myDataList.get(i).getSansPhoto() != null) {
final String emeteur_phone = myDataList.get(i).getEmetr_phone();
String emeteur_name = null;
if (myDataList.get(i).getEmetr_name() != null) {
emeteur_name = myDataList.get(i).getEmetr_name();
}
message = myDataList.get(i).getText();
destFromServer = myDataList.get(i).getDestinataires();
idPostEmet = myDataList.get(i).getIdPostEmet();
counterDest = Integer.toString(myDataList.get(i).getCounterDest());
typePoste = myDataList.get(i).getTypePoste();
//TODO idGroup exit in TinyDB
TinyDB tinydb = new TinyDB(YuYuApplication.getAppContext());
ArrayList<String> mIdArray = tinydb.getListString("ids");
if (groups != null) {
for (int j = 0; j < mIdArray.size(); j++)
for (int k = 0; k < groups.size(); k++)
if (mIdArray.get(j).equals(groups.get(k).getId())) {
checkGroupNotification = true;
break;
}
}
//Debut Test
// Session class instance
// session = new SessionManager(getApplicato());
try {
EmeteurPoste = contactmanager.getContactsByNbrPhone(Utils.AddCaractDest(emeteur_phone));
if (EmeteurPoste.getName().equals(EmeteurPoste.getPhone()) || EmeteurPoste.getName().equals("null") && emeteur_name != null) { // || !c.getName().equals(name) a utiliser pour changer le nom a mettre en place qd l emmet sera un contact et pas un string
EmeteurPoste.setName(emeteur_name);
contactmanager.updateContactName(EmeteurPoste);
}
} catch (Exception ex) {
Log.v(Constants.TAG6, ex.getMessage());
}
if (EmeteurPoste == null) {
EmeteurPoste = new Contact();
if (emeteur_name == null)
EmeteurPoste.setName(Utils.AddCaractDest(emeteur_phone));
else
EmeteurPoste.setName(emeteur_name);
EmeteurPoste.setPhone(Utils.AddCaractDest(emeteur_phone));
EmeteurPoste.setStatus(Constants.STATUS_INSCRIS_NON_ENRG_REPERTOIRE);
contactmanager.openForWrite();
EmeteurPoste.setId((int) contactmanager.createContact(EmeteurPoste));
contactmanager.close();
}
if (EmeteurPoste != null) {
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost 3 Contact EmetPost Name" + EmeteurPoste.getName() + "EmetPost Phone" + EmeteurPoste.getPhone());
}
emeteur = EmeteurPoste.getName();
} else {
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost EmetPost null");
}
emeteur = emeteur_phone;
}
// destinataires = Utils.convertStringToArray();
destinataires = contactmanager.updateAllNameAndIdDestinataireForPost(destFromServer);
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost destinataires " + destinataires);
}
//TEST L'icône sera une petite loupe
//TEST int icon = R.drawable.ic_launcher;
// Le premier titre affiché
//TEST CharSequence tickerText = "Titre de la notification";
// Daté de maintenant
long when = System.currentTimeMillis();
if (BuildConfig.DEBUG) {
Log.d(Constants.TAG6, " getListPost notification manager");
}
//Loading webView
/*if(Utils.linkScannerWebView(msg)!=null)
typePoste = String.valueOf(PosteAdapter.TYPE_WEB_VIEW);*/
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost 4 Before getLinkPreview idPostEmet " + idPostEmet + " myDataList.get(i).getIdPostEmet() " + myDataList.get(i).getIdPostEmet() + " message " + message + " data.getString(text).toString() " + myDataList.get(i).getText());
}
if (typePoste.equals(String.valueOf(Constants.TYPE_WEB_VIEW)) || typePoste.equals(String.valueOf(Constants.TYPE_WEB_VIEW_Retry))) {
final boolean checkGrNotif = checkGroupNotification;
final boolean checkGrSon = checkGroupSon;
LinkUtil.getInstance().getLinkPreview(getBaseContext(), Utils.linkScannerWebView(message), message, EmeteurPoste, emeteur_phone, idPostEmet, destinataires, counterDest, groups, new GetLinkPreviewListener() {
#Override
public void onSuccess(final LinkPreview linkPreview) {
String img = null;
Gson gson = new Gson();
File imgFile = linkPreview.getImageFile();
try {
if (imgFile != null && imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
if (myBitmap != null) {
img = Utils.SaveImage(getBaseContext(), myBitmap, true);
}
}
} catch (Exception ex) {
}
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost 5 after save image and description and BEFORE addLink idPostEmet " + idPostEmet + " Message " + gson.toJson(linkPreview));
}
// postemessage = addMessage(EmeteurPoste, emeteur_phone, linkPreview.getTextPoste(), destinataires, linkPreview.getIdPostEmet(), counterDest, String.valueOf(Constants.TYPE_WEB_VIEW), img, groups, checkGrNotif, checkGrSon); //gson.toJson(linkPreview)
postemessage = addLinkWebView(linkPreview, String.valueOf(Constants.TYPE_WEB_VIEW), img, checkGrNotif, checkGrSon); //gson.toJson(linkPreview)
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " 10 after save image and description and AFTER addMessage idPostEmet " + idPostEmet);
}
try {
if ((postemessage != null) && callback.getString("idPostEmet") == postemessage.getIdpostemet()) {
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost 11 called emit POST WEB VIEW link: " + gson.toJson(linkPreview));
}
// socket.emit("callBackDevice", sendCallback);
callbackList.put(callback);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailed(Exception var1) {
if (BuildConfig.DEBUG) {
Log.d(Constants.TAG6, " getListPost 5 after save image and description and BEFORE addMessage idPostEmet " + idPostEmet + " Message " + message);
}
postemessage = addMessage(EmeteurPoste, emeteur_phone, message, destinataires, idPostEmet, counterDest, "0", null, groups, checkGrNotif, checkGrSon);
if (BuildConfig.DEBUG) {
Log.d(Constants.TAG6, " getListPost 10 after save image and description and BEFORE addMessage idPostEmet " + idPostEmet + " Message " + message);
}
try {
if ((postemessage != null) && callback.getString("idPostEmet") == postemessage.getIdpostemet()) {
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost 11 called emit POST WEB VIEW FAILED message: " + message);
}
// socket.emit("callBackDevice", sendCallback);
callbackList.put(callback);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} else {
postemessage = addMessage(EmeteurPoste, emeteur_phone, message, destinataires, idPostEmet, counterDest, "0", null, groups, checkGroupNotification, checkGroupSon);
try {
if ((postemessage != null) && callback.getString("idPostEmet") == postemessage.getIdpostemet()) {
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, "getListPost called emit POST MESSAGE message: " + message);
}
// socket.emit("callBackDevice", sendCallback);
callbackList.put(callback);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// Fin Test
}
} catch (Exception e) {
Log.d(Constants.TAG6, "getListPost friend call object cannot be parsed");
e.printStackTrace();
}
} else {
if (BuildConfig.DEBUG) {
Log.d(Constants.TAG6, " getListPostidPostEmet ALREADY EXIST");
}
//Sending callback if poste is already exist
JSONObject callback = new JSONObject();
try {
callback.put("app_id", myDataList.get(i).getApp_id());
/* Contact cdest = new Contact();
ArrayList<Contact> cdestList = new ArrayList<>();
cdest.setPhone(session.getPhoneSession());
cdestList.add(cdest);
callback.put("destPhone",cdestList); */
callback.put("destPhone", session.getPhoneSession());
callback.put("idPostEmet", myDataList.get(i).getIdPostEmet());
callback.put("emetr_phone", myDataList.get(i).getEmetr_phone());
callback.put("typeOfCallback", "callBackDevice");
} catch (JSONException e) {
e.printStackTrace();
}
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost post message called emit");
}
if (BuildConfig.DEBUG) {
Log.d(Constants.TAG6, "getListPost send callBackDevice callback " + callback.toString());
}
// socket.emit("callBackDevice",callback);
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost RECEIVE LISTPOSTS i " + i + " callback " + callback);
}
callbackList.put(callback);
}
/* } catch (JSONException e) {
e.printStackTrace();
if (BuildConfig.DEBUG) {
Log.d(Constants.TAG6,"3 try catch exception "+e.toString()+" myDataList.get(i).toString() "+myDataList.get(i).toString());
}
} */
}
if (BuildConfig.DEBUG) {
Log.v(Constants.TAG6, " getListPost END RECEIVE LISTPOSTS callbackList " + callbackList);
}
if(callbackList.length() > 0){
sendCallbackList(callbackList);
}else{
getListPostISentFromWeb();
}
}
#Override
public void onFailure(Call<ArrayList<PosteFromServer>> call, Throwable t) {
if (BuildConfig.DEBUG)
Log.v(Constants.TAG6, " getListPost onFailure " + t.getMessage());
}
});
}

Upload a video to FTP android

I have created an application that requires uploading video to the server using FTP. I have searched many options but once the file is uploaded it is not playing back. Can someone help me ?
Here is the data sender parts of my BackgroundSenderService
I used AndroidNetworking library.
My service triggers on some periods to check db that has unsent media file.
For the success and error results I updated db, but you can send Localbroadcasts to trigger some interface elements on UI.
private void checkDbForUpload() {
((MainApp) getApplicationContext()).setMediaSenderIsIdle(false);
MediaModel media = ((MainApp) getApplicationContext()).getFirstUnsendMedia(mContext);
if (media != null) {
if (((MainApp) getApplicationContext()).getHasMission() && ((MainApp) getApplicationContext()).getLastResponse().getCaseId().equals(media.getCaseId())) {
stopThisService();
return;
}
boolean canBeginUpload = ((MainApp) getApplicationContext()).canBeginMediaUpload(mContext);
if (canBeginUpload) {
Log.d(TAG, "checkDbForUpload: we have connected and we have file to upload");
startUploadingProcess(media);
} else {
((MainApp) getApplicationContext()).setMediaSenderIsIdle(true);
stopThisService();
}
} else {
((MainApp) getApplicationContext()).setMediaSenderIsIdle(true);
stopThisService();
}
}
private void startUploadingProcess(MediaModel media) {
int mediaStatus = media.getUploadStatus();
Log.d(TAG, "beginMediaUploadProcess: #" + media.getId() + " Status: " + mediaStatus);
if (media.getRetryCount() > Constants.UPLOAD_ERROR_RETRY_COUNT) {
media.setSessionId("");
saveMediaToDb(media);
}
switch (mediaStatus) {
case Constants.MEDIA_STATUS_UPLOADED:
deleteMediaFromDbAndDisk(media);
checkDbForUpload();
break;
case Constants.MEDIA_STATUS_UPLOADING:
case Constants.MEDIA_STATUS_WAITING:
case Constants.MEDIA_STATUS_ERROR:
if (media.getSessionId() != null && !media.getSessionId().equals("")) {
Log.d(TAG, "startUploadingProcess: has session");
startPutWithoutBody(media);
} else {
Log.d(TAG, "startUploadingProcess: no session");
getMediaEndpoint(media);
}
break;
}
}
private void startPostTask(MediaModel media) {
media.setSessionId("");
setMediaAsWaiting(media);
File file = new File(media.getFile());
String contentType = getMimeType(file.getPath());
setMediaAsUploading(media);
String postUrl = ENDPOINT + "?uploadType=resumable&name=" + createSendingFileName(media);
AndroidNetworking.post(postUrl)
.setTag("uploadRequest")
.setPriority(Priority.HIGH)
.addHeaders("X-Api-Key", Constants.API_KEY_UPLOAD)
.addHeaders("Content-Type", "application/json")
.addHeaders("X-Upload-Content-Type", contentType)
.addHeaders("X-Upload-Content-Length", String.valueOf(file.length()))
.addJSONObjectBody(prepareMetaData(media).toJSON())
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse: " + response.toString());
UploadPostResponseModel responseModel = new UploadPostResponseModel(response);
if (responseModel.getStatusCode() == Constants.HTTP_STATUS_OK) {
media.setSessionId(responseModel.getId());
try {
startPutTask(media);
} catch (Exception e) {
e.printStackTrace();
}
} else {
setMediaUploadError(media);
}
}
#Override
public void onError(ANError anError) {
Log.d(TAG, "onError: " + anError.getErrorDetail());
setMediaUploadError(media);
}
});
}
private void startPutWithoutBody(MediaModel media) {
String putUrl = ENDPOINT + (ENDPOINT.contains("?") ? "&" : "?") + "upload_id=" + media.getSessionId();
AndroidNetworking.put(putUrl)
.setTag("putRequest")
.setPriority(Priority.HIGH)
.addHeaders("X-Api-Key", Constants.API_KEY_UPLOAD)
.addHeaders("Content-Range", getContentRangeString(media))
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse: " + response.toString());
//UploadPostResponseModel responseModel = new UploadPostResponseModel(response);
}
#Override
public void onError(ANError anError) {
setMediaUploadError(media);
}
});
}
private void startPutTask(MediaModel media) {
if (!((MainApp) getApplicationContext()).canBeginMediaUpload(mContext)) {
setMediaAsWaiting(media);
stopThisService();
}
//if fails -> consider using this https://stackoverflow.com/a/54961878/1492681
try {
File tmpDir = mContext.getCacheDir();
File tmpFile = File.createTempFile("TMPFILE", media.getSessionId(), tmpDir);
File orgFile = new File(media.getFile());
int startIndex = (int) media.getUploadedBytes();
Log.d(TAG, "startIndex: " + startIndex);
int bytesLeft = (int) (orgFile.length() - startIndex);
Log.d(TAG, "bytesLeft: " + bytesLeft);
RandomAccessFile f = new RandomAccessFile(media.getFile(), "r");
int len = Constants.CHUNKSIZE;
if (Constants.CHUNKSIZE >= bytesLeft) {
len = bytesLeft;
}
Log.d(TAG, "len: " + len);
byte[] buffer = new byte[len];
f.seek(startIndex);
f.read(buffer, 0, len);
Log.d(TAG, "buffer: " + buffer.length);
int endIndex = startIndex + len;
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile));
bos.write(buffer);
bos.flush();
bos.close();
//send chunk here
String putUrl = ENDPOINT + "?uploadType=resumable&upload_id=" + media.getSessionId();
AndroidNetworking.put(putUrl)
.setTag("putRequest")
.setPriority(Priority.HIGH)
.addHeaders("X-Api-Key", Constants.API_KEY_UPLOAD)
.addHeaders("Content-Range", getContentRangeString(media))
.addFileBody(tmpFile)
.build()
.getAsOkHttpResponse(new OkHttpResponseListener() {
#Override
public void onResponse(Response response) {
switch (response.code()) {
case Constants.HTTP_STATUS_CREATED:
case Constants.HTTP_STATUS_OK:
setMediaAsUploaded(media);
break;
case Constants.HTTP_STATUS_PERMANENT_REDIRECT:
case Constants.HTTP_STATUS_RANGENOTSATISFIABLE:
Log.d(TAG, "onResponse: " + response.toString());
long receivedBytes = parseRange(response);
Log.d(TAG, "uploaded: " + receivedBytes + " of " + orgFile.length());
media.setUploadedBytes(receivedBytes);
setMediaAsUploading(media);
Log.d(TAG, "onResponse: receivedBytesFromServer: " + receivedBytes);
try {
startPutTask(media);
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
setMediaUploadError(media);
break;
}
}
#Override
public void onError(ANError anError) {
setMediaUploadError(media);
}
});
} catch (IOException | ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
setMediaUploadError(media);
}
}
private String getContentRangeString(MediaModel media) {
File file = new File(media.getFile());
long fileLength = file.length();
String contentRange = "bytes */" + fileLength;
Log.d(TAG, "getContentRangeString: " + contentRange);
return contentRange;
}

Method is not called from onCreate

I am making classified marketplace android app. So, I have to show ads or post done by people on my home page, all is working and I am getting all my post on postman but not on my recycleview.
public class SearchFragment extends Fragment {
private static final String TAG = "SearchFragment";
private static final String BASE_URL = "http://35.188.133.114//elasticsearch/posts/post/";
private static final int NUM_GRID_COLUMNS = 2;
private static final int GRID_ITEM_MARGIN = 5;
//widgets
private ImageView mFilters;
private EditText mSearchText;
private FrameLayout mFrameLayout;
//vars
private String mElasticSearchPassword;
private String mPrefCity;
private String mPrefStateProv;
//private String mPrefCountry;
private String mPrefCollege;
private ArrayList<Post> mPosts;
private RecyclerView mRecyclerView;
private PostListAdapter mAdapter;
private ListView listView;
private String currentuser;
private String user;
private ImageView filter;
ArrayList<Card> list = new ArrayList<>();
FloatingActionButton fab;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search, container, false);
mFilters = (ImageView) view.findViewById(R.id.ic_search);
mSearchText = (EditText) view.findViewById(R.id.input_search);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mFrameLayout = (FrameLayout) view.findViewById(R.id.container);
filter = (ImageView) view.findViewById(R.id.filter);
currentuser = FirebaseAuth.getInstance().getUid();
filter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(),FiltersActivity.class);
startActivity(intent);
}
});
getElasticSearchPassword();
welcome();
init();
return view;
}
private void setupPostsList(){
RecyclerViewMargin itemDecorator = new RecyclerViewMargin(GRID_ITEM_MARGIN, NUM_GRID_COLUMNS);
mRecyclerView.addItemDecoration(itemDecorator);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), NUM_GRID_COLUMNS);
mRecyclerView.setLayoutManager(gridLayoutManager);
mAdapter = new PostListAdapter(getActivity(), mPosts);
mRecyclerView.setAdapter(mAdapter);
// CustomListAdapter adapter = new CustomListAdapter(getActivity(), R.layout.card_layout_main, list);
}
private void welcome() {
if (!currentuser.equals("")) {
mPosts = new ArrayList<Post>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ElasticSearchAPI searchAPI = retrofit.create(ElasticSearchAPI.class);
HashMap<String, String> headerMap = new HashMap<String, String>();
headerMap.put("Authorization", Credentials.basic("user", mElasticSearchPassword));
// String searchString = "*";
/* if(!mSearchText.equals("")){
searchString = searchString + mSearchText.getText().toString() + "*";
}*/
/* if(!mPrefCity.equals("")){
searchString = searchString + " city:" + mPrefCity;
}
if(!mPrefStateProv.equals("")){
searchString = searchString + " state_province:" + mPrefStateProv;
}*/
/* if(!mPrefCollege.equals("")){
searchString = searchString + " college:" + mPrefCollege;
}*/
/*if(!currentuser.equals("")){
searchString = searchString + " user_id:" + currentuser;
}*/
Call<HitsObject> call = searchAPI.search(headerMap, "AND", "*");
call.enqueue(new Callback<HitsObject>() {
#Override
public void onResponse(Call<HitsObject> call, Response<HitsObject> response) {
HitsList hitsList = new HitsList();
String jsonResponse = "";
try {
Log.d(TAG, "onResponse: server response: " + response.toString());
if (response.isSuccessful()) {
hitsList = response.body().getHits();
} else {
jsonResponse = response.errorBody().string();
}
Log.d(TAG, "onResponse: hits: " + hitsList);
for (int i = 0; i < hitsList.getPostIndex().size(); i++) {
Log.d(TAG, "onResponse: data: " + hitsList.getPostIndex().get(i).getPost().toString());
mPosts.add(hitsList.getPostIndex().get(i).getPost());
}
Log.d(TAG, "onResponse: size: " + mPosts.size());
//setup the list of posts
setupPostsList();
} catch (NullPointerException e) {
Log.e(TAG, "onResponse: NullPointerException: " + e.getMessage());
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "onResponse: IndexOutOfBoundsException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "onResponse: IOException: " + e.getMessage());
}
}
#Override
public void onFailure(Call<HitsObject> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
Toast.makeText(getActivity(), "search failed", Toast.LENGTH_SHORT).show();
}
});
}
// return false;
}
private void init(){
mFilters.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPosts = new ArrayList<Post>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ElasticSearchAPI searchAPI = retrofit.create(ElasticSearchAPI.class);
HashMap<String, String> headerMap = new HashMap<String, String>();
headerMap.put("Authorization", Credentials.basic("user", mElasticSearchPassword));
String searchString = "";
if(!mSearchText.equals("")){
searchString = searchString + mSearchText.getText().toString() + "*";
}
/* if(!mPrefCity.equals("")){
searchString = searchString + " city:" + mPrefCity;
}
if(!mPrefStateProv.equals("")){
searchString = searchString + " state_province:" + mPrefStateProv;
}*/
if(!mPrefCollege.equals("")){
searchString = searchString + " college:" + mPrefCollege;
}
/*if(!currentuser.equals("")){
searchString = searchString + " user_id:" + currentuser;
}*/
Call<HitsObject> call = searchAPI.search(headerMap, "AND", searchString);
call.enqueue(new Callback<HitsObject>() {
#Override
public void onResponse(Call<HitsObject> call, Response<HitsObject> response) {
HitsList hitsList = new HitsList();
String jsonResponse = "";
try{
Log.d(TAG, "onResponse: server response: " + response.toString());
if(response.isSuccessful()){
hitsList = response.body().getHits();
}else{
jsonResponse = response.errorBody().string();
}
Log.d(TAG, "onResponse: hits: " + hitsList);
for(int i = 0; i < hitsList.getPostIndex().size(); i++){
Log.d(TAG, "onResponse: data: " + hitsList.getPostIndex().get(i).getPost().toString());
mPosts.add(hitsList.getPostIndex().get(i).getPost());
}
Log.d(TAG, "onResponse: size: " + mPosts.size());
//setup the list of posts
setupPostsList();
}catch (NullPointerException e){
Log.e(TAG, "onResponse: NullPointerException: " + e.getMessage() );
}
catch (IndexOutOfBoundsException e){
Log.e(TAG, "onResponse: IndexOutOfBoundsException: " + e.getMessage() );
}
catch (IOException e){
Log.e(TAG, "onResponse: IOException: " + e.getMessage() );
}
}
#Override
public void onFailure(Call<HitsObject> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage() );
Toast.makeText(getActivity(), "search failed", Toast.LENGTH_SHORT).show();
}
});
}
// return false;
});
}
welcome() method is not called as i am not able to see any post but init() method is working and showing all the post when clicking on search button. And both methods are using same code, the only difference of the query that I am making, do not know why welcome() method is not showing any post.
Actually, Your method is called from onCreate() but your condition (!currentuser.equals("") is return false.
See the value of currentuser = FirebaseAuth.getInstance().getUid();
Only if you authenticate the user,then you will have this as not null else it will be empty or null.
This is issue with Firbase issue, Please check the firebase instance is configured and initialized properly in your application class. Then you should not able to get currentUser == "".
Firebase will return 401/410 error code incase of invalid user token / authentication with invalid user information.

Restoring inapp purchased items in android

I'm trying to give the user the ability to restore his inapp purchased items from my application.
I'm using the following code:
ServiceConnection mServiceConn = new ServiceConnection()
{
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
mService = IInAppBillingService.Stub.asInterface(service);
Log.d("TEST", "mService ready to go!");
checkownedItems();
}
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
mService = null;
}
};
public void checkownedItems()
{
try
{
String base64EncodedPublicKey = "MY_KEY";
// Log.d("getPackageName ", "Items Owned: " + getPackageName());
Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
if(ownedItems.getInt("RESPONSE_CODE") == 0)
{
ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
//ownedSkus.toArray();
ownedSkus.add("test");
for (int n=0;n<ownedSkus.size();n++)
{
Log.d("Items: ", "Items: " + ownedSkus.get(n));
}
ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
ArrayList<String> signatureList = ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
String continuationToken = ownedItems.getString("INAPP_CONTINUATION_TOKEN");
//Log.d("Items Owned: ", "Items Owned: " + ownedSkus.size()); toast
Log.d("Data List: ", "Data List: " + purchaseDataList.size());
Log.d("signature List: ", "signature List: " + signatureList);
Log.d("continuation Token: ", "continuation Token: " + continuationToken);
if(purchaseDataList.size() > 0)
{
//Item(s) owned
Log.d("purchaseDataList: ", "purchaseDataList: " + purchaseDataList.size());
for(int i=0; i<purchaseDataList.size(); ++i)
{
String sku = ownedSkus.get(i);
/* String xx = ownedItems.getString("INAPP_CONTINUATION_TOKEN");
Log.d(TAG, "INAPP_CONTINUATION_TOKEN: " + xx);
*/
Log.d(TAG, "Item_SKU: " + "consume");
String bookpdf = "http://www.mybook.com/"+sku+ ".pdf";
String Bookvalue= sku.substring(sku.lastIndexOf(".")+1);
downloadAndEncrypt(bookpdf,Bookvalue + ".pdf");
Log.d(TAG, "Item_SKU-Download: "
+ "Download Complete");
Log.d("OWNED_ITEMS_FINAL_SIZE","OWNED_ITEMS_FINAL_SIZE: " + ownedItems.size() );
Log.d("OWNED_ITEMS_FINAL_LIST","OWNED_ITEMS_FINAL_LIST: " + ownedItems.keySet());
Log.d("ownedSkus1","ownedSkus1: " + ownedSkus.size() );
Log.d("ownedSkus2","ownedSkus2: " + ownedSkus.toString());
Log.d("ownedSkus3","ownedSkus3: " + ownedSkus);
//Log.d("testtt","testtt " + "INAPP_PURCHASE_ITEM_LIST".length());
/* String value = ownedItems.getString("INAPP_PURCHASE_ITEM_LIST");
Log.d("my_test","my_test: " + value); */
}
}
else
{
//Item(s) not owned
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener()
{
#Override
public void onIabSetupFinished(IabResult result) {
// TODO Auto-generated method stub
if(!result.isSuccess())
{
Log.d("TEST", "In-app Billing setup failed: " + result);
}
else
{
Log.d("TEST", "In-app Billing is set up OK");
}
}
});
}
}
else
{
//Error checking owned items
}
}
catch(RemoteException e)
{
e.printStackTrace();
}
}
#Override
public void onDestroy()
{
super.onDestroy();
if(mServiceConn != null)
{
//unbindService(mServiceConn);
}
}
Note that I'm using the correct base64EncodedPublicKey key of my application.
The problem now is the above code only returns the first inapp item purchased from my application. I tried much everything possible with that piece of code, and it always returns only the first item when trying to log the output results.
Please advise.
Thank you.
Here is the code you are looking for:
private void queryUserPurcahses()
{
mHelper.queryInventoryAsync(mGotInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mGotInventoryListener
= new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
// handle error here
}
else {
boolean is_purchased_1 = inventory.hasPurchase(product_1_ID);
boolean is_purchased_2 = inventory.hasPurchase(product_2_ID);
}
}
};
I figured it out. I was consuming the purchased items in my code. What I did I just commented the consumeitem() function, and when I published my apk (it has to be published to return all the purchased items don't know why!) it worked like a charm and restored all my item that I purchased after commenting the consumeitem().
Thank you all.

My TextView not update

Here is my code
this is my InstantMessage application
the method processMessage will automatically do when the applicaiton have new message
My problem is the textview not work when method processMessage do but when i send message when textview update by both use the same updateChat method
#Override
public void onClick(View v) {
String message = text.getText().toString();
try {
Log.e("On Click", message + " : " + contact);
chat.sendMessage(message);
message = username + " : " + message;
updateChat(message);
} catch (XMPPException e) {
e.printStackTrace();
}
}
public void updateChat(String message){
chatLog += message + "\n";
chatBox.setText(chatLog);
}
#Override
public void processMessage(org.jivesoftware.smack.Chat arg0, Message arg1) {
String temp = InstantMessage.usernameCutter(arg0.getParticipant()) + " : "+ arg1.getBody();
Log.e("ChatPage ", "ProcessMessage");
updateChat(temp);
}
Are processMessage method running on UI thread?
if not, use this construction
final String temp = InstantMessage.usernameCutter(arg0.getParticipant()) + " : "+ arg1.getBody();
runOnUiThread(new Runnable() {
public void run() {
updateChat(temp);
}
});

Categories

Resources