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);
}
});
Related
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);
}
};
I'm using the socialAuth plugin to connect a user to linkdin within my app. I have the connection set up correctly and retrieves data. However, I'm unsure how I can get my main activity to wait until the socialAuthListeners have fired and finished. I know a little about threading but I haven't used it with listeners before. Here's my code:
public class LinkdinAuth {
private static final String TAG = "TEST";
// SocialAuth Components
SocialAuthAdapter adapter;
ProgressDialog mDialog;
private Context context;
private boolean loggedIn = false;
private Bundle LinkdinData;
public LinkdinAuth(Context C){
this.context = C;
LinkdinData = new Bundle();
adapter = new SocialAuthAdapter(new ResponseListener());
}
public void adapterAuthorize(View v){
adapter.authorize(v.getContext(), Provider.LINKEDIN);
}
private final class ResponseListener implements DialogListener
{
public void onComplete(Bundle values) {
String providerName = values.getString(SocialAuthAdapter.PROVIDER);
Log.d("Main", "providername = " + providerName);
mDialog = new ProgressDialog(context);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setMessage("Loading...");
//Get profile information
adapter.getUserProfileAsync(new ProfileDataListener());
// get Job and Education information
mDialog.show();
adapter.getCareerAsync(new CareerListener());
loggedIn = true;
Log.d("Main", "LOGGED IN = " + loggedIn );
Toast.makeText(context, providerName + " connected", Toast.LENGTH_SHORT).show();
}
#Override
public void onBack() {
Log.d("Main", "Dialog Closed by pressing Back Key");
}
#Override
public void onCancel() {
Log.d("Main", "Cancelled");
}
#Override
public void onError(SocialAuthError e) {
Log.d("Main", "Error");
e.printStackTrace();
}
}
// To receive the profile response after authentication
private final class ProfileDataListener implements SocialAuthListener<Profile> {
#Override
public void onExecute(String provider, Profile t) {
Log.d("Sign Up", "Receiving Data");
mDialog.dismiss();
Profile profileMap = t;
LinkdinData.putString("Validated ID", profileMap.getValidatedId() );
LinkdinData.putString("First Name", profileMap.getFirstName());
LinkdinData.putString("Last Name", profileMap.getLastName());
LinkdinData.putString("Email", profileMap.getEmail());
LinkdinData.putString("Country", profileMap.getCountry());
LinkdinData.putString("Language", profileMap.getLanguage());
LinkdinData.putString("Location", profileMap.getLocation());
LinkdinData.putString("Profile Image URL", profileMap.getProfileImageURL());
}
#Override
public void onError(SocialAuthError arg0) {
// TODO Auto-generated method stub
}
}
private final class CareerListener implements SocialAuthListener<Career> {
#Override
public void onExecute(String provider, Career t) {
Log.d("Custom-UI", "Receiving Data");
mDialog.dismiss();
Career careerMap = t;
//get education
Log.d("Main", "Education:");
if(careerMap.getEducations() != null){
for(Education E: careerMap.getEducations()){
Log.d("Main", "School = " +E.getSchoolName() );
Log.d("Main", "Major = " + E.getFieldOfStudy() );
Log.d("Main", "Degree = " + E.getDegree() );
Log.d("Main", "Start Date = " + E.getStartDate() );
Log.d("Main", "End Date = " + E.getEndDate() );
}
}
Log.d("SignUp", "Career");
if(careerMap.getPositions() != null){
for(Position P: careerMap.getPositions()){
LinkdinData.putString("Company Name", P.getCompanyName() );
LinkdinData.putString("Job Title", P.getTitle() );
Log.d("Main", "Industry = " + P.getIndustry() );
Log.d("Main", "Start Date = " + P.getStartDate() );
Log.d("Main", "End Date = " + P.getEndDate() );
}
}
}
#Override
public void onError(SocialAuthError e) {
}
}
public boolean isLoggedIn(){
return loggedIn;
}
public Bundle getLinkdinData(){
return LinkdinData;
}
So, as you can see. I have 2 listeners that get data after authorization goes through. And my main activity makes creates an instance, calls the adapterAuthroizeMethod and then if the user logs in a flag is set. Then getLinkedData is called. However I would like it to wait until I know the listeners have fired before calling getlinkdinData. Here's what my Main Activity does after a button press:
L.adapterAuthorize(v);
loggedInWithLinkdin = L.isLoggedIn();
Bundle B = L.getLinkdinData();
Intent i = new Intent(getBaseContext(), UserRegistration.class);
i.putExtra("linkdin bundle", B);
//startActivity(i);
Any ideas?
thanks
Well, not a recommend solution but more of a hack.
Here is what you can do.
Wrap the aync call around this construct :
AtomicBoolean done = new AtomicBoolean(false);
Global ans; // the return value holder
try{
result = someAsyncCall(query, new Thread()); // this new thread is for listener callback
result.setResultListener(result -> {
// do something with result.
ans = result.getAns() ; // set global ans
done.set(true);
synchronized (done) {
done.notifyAll(); // notify the main thread which is waiting
}
});
}
catch (Exception e ) {
Log(e);
}
synchronized (done) {
while (done.get() == false) {
done.wait(); // wait here until the listener fires
}
}
return ans; // return global ans
i am trying to parse the json data,in my application,i have 2 dropdown box from which user select the country name to which he wants to convert the data.and the amount he want to convert is passed into the url. and i am using AsyncHttpClient lib to read the data,before using it on different api it work perfectly fine ,but when i change my api it start run the failure method.first i thought i passed wrong url.,but on toast i get to knw i am passing correct url of the api.
what is the problem can anyone tell me..??
Thanking you in advance.
private String API_URL = "http://devel.farebookings.com/api/curconversor/";
public void onClick(View arg0) {
final String url1 = API_URL + t1.toString() + "/" + t2.toString() + "/"
+ usdValue.getText().toString() + "/" + "json";
Toast.makeText(getApplicationContext(), url1.toString(),
Toast.LENGTH_LONG).show();
if (!usdValue.getText().toString().equals("")) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(url1, new AsyncHttpResponseHandler() {
#Override
public void onFailure(Throwable arg0, String arg1) {
// TODO Auto-generated method stub
super.onFailure(arg0, arg1);
Toast.makeText(getApplicationContext(),
"unsuccess", Toast.LENGTH_LONG).show();
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
super.onFinish();
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(getApplicationContext(), "start",
Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(String response) {
Log.i("CHACHING", "HTTP Sucess");
Toast.makeText(getApplicationContext(), "success",
Toast.LENGTH_LONG).show();
try {
JSONObject jsonObj = new JSONObject(response);
Double usds = Double.valueOf(usdValue.getText()
.toString());
Double rate = jsonObj.getDouble("to_amount");
Toast.makeText(getApplicationContext(),
String.valueOf(rate), Toast.LENGTH_LONG)
.show();
double the_result = usds * rate;
ConvertedFrom.setText(usdValue.getText()
.toString()
+ " "
+ ConvertedFromCurr.getSelectedItem()
.toString() + " = ");
ConvertedTo.setText(String.valueOf(the_result)
+ " "
+ ConvertedToCurr.getSelectedItem()
.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} else {
Toast.makeText(getApplicationContext(),
"Please enter a Amount value!", Toast.LENGTH_LONG)
.show();
}
for cross domain api calls you must use jsonp.
This is an example in javascript
$.ajax({
url: "http://devel.farebookings.com/api/curconversor/EUR/GBP/1/",
dataType: 'jsonp',
success: function (data) {
alert(data.GBP);
}
});
I am working on Autobahn Web socket communication. There is a carousel view in my application, and there are four images. When users click on of the images, then connects to server with websocket and send message. But the problem is that when I select the images, it connects to server correctly, but client(android device) connects to the websocket every single time when the message is sent.
Here is my code..
if (pos == 0) {
product_photo.setImageResource(R.drawable.myoffers_0);
product_photo.setOnClickListener(new ImageButton.OnClickListener(){
public void onClick(View v){
String id = "Product0";
Log.d(TAG, "Current product is : " + id);
A.sendMessage(id);
}
});
}
Websocket.class
public class WebSocket_Connector extends Activity{
private static final String TAG = "ECHOCLIENT";
private static final String TAG1 = "My app";
public final WebSocketConnection mConnection = new WebSocketConnection();
private String tmpString = "";
public void connect(final String wsuri) {
Log.d(TAG, "Connecting to: " + wsuri);
try {
mConnection.connect(wsuri, new WebSocketHandler() {
#Override
public void onOpen() {
Log.d(TAG, "Status: Connected to " + wsuri );
Log.d(TAG, "Connection successful!\n");
mConnection.sendTextMessage(tmpString);
tmpString = "";
}
#Override
public void onTextMessage(String payload) {
Log.d(TAG, "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.d(TAG, "Connection closed.");
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
}
public void sendMessage(String message) {
if (mConnection.isConnected()) {
Log.d(TAG1, "Messeage is sent : " + message);
mConnection.sendTextMessage(message);
}
else {
tmpString = message;
connect("ws://xxx.xxx.x.xxx:xxxx");
}
}
}
It doens't go to 'if (mConnection.isConnected())' here..always goes to else.
I have written two pieces of code one for send email and other for collecting stacktrace if FORCE ERROR occurs , and both of these code work individually .
Now my problem is when i club both of these code it doesnt work (log are also working normal)
public class BaseActivity extends Activity{
public Context context;
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
Writer result = new StringWriter();
PrintWriter printWriter = new PrintWriter(result);
paramThrowable.printStackTrace(printWriter);
System.out.println("BaseActivity.onCreate(...).new UncaughtExceptionHandler() {...}.uncaughtException()" +result.toString());
sendMail(result.toString());
Toast.makeText(getContext(),"cs", 1).show();
}
});
}
public void sendMail(String body){
try {
GMailSender sender = new GMailSender("email#gmail.com",
"password");
sender.sendMail("This is Subject",
"java.lang.RuntimeException: Unable to start activity ComponentInfo{com.silverSkills.com/com.silverSkills.com.ChildActivity}: java.lang.NullPointerException" +
"at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)" +
" at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)" +
" at android.app.ActivityThread.access$1500(ActivityThread.java:117)" +
" at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)" +
" at android.os.Handler.dispatchMessage(Handler.java:99)" +
" at android.os.Looper.loop(Looper.java:123)" +
" at android.app.ActivityThread.main(ActivityThread.java:3683)" +
" at java.lang.reflect.Method.invokeNative(Native Method)" +
" at java.lang.reflect.Method.invoke(Method.java:507)" +
" at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)" +
" at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)" +
" at dalvik.system.NativeStart.main(Native Method)" +
" Caused by: java.lang.NullPointerException" +
" at com.silverSkills.com.ChildActivity.onCreate(ChildActivity.java:9)" +
" at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)" +
" at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)" +
" ... 11 more",
"email#gmail.com", "email#gmail.com");
Log.i("Confirm","mail send");
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
}
And this is how call make call this code .
public class ChildActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContext(this);
String a=null;
a.toString();
}
It would be great if u can suggest me anything :D