I am working on a GroupChat process. I have successfully sent the invitation and using PSI i have received this invitation. But M unable to invoke my own "MultiUserChat.addInvitationListener". I have done this many ways but in-vain. Here is one of my attempt.
ProviderManager pm = ProviderManager.getInstance();
pm.addExtensionProvider("x", "http://jabber.org/protocol/muc#user", new MUCUserProvider());
MultiUserChat.addInvitationListener(mXmppConnection, MyClass.this);
And doing "MyClass extends Activity implements InvitationListener"
#Override
public void invitationReceived(final Connection conn,final String room, final String inviter, String reason, String password, Message message) {
AlertDialog.Builder builder = new AlertDialog.Builder(MyClass.this);
builder.setTitle("Room Invitation");
builder.setMessage(inviter + " sent you an invitation to join GroupChat saying \""+reason+" \". \n Do you want to join "+inviter+"?");
builder.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
// Joining Room
#Override
public void onClick(DialogInterface dialog, int which) {
try {
MultiUserChat multiUserChat = new MultiUserChat(conn, room);
multiUserChat.join(myNickName);
if(multiUserChat.isJoined()){
dialog.cancel();
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
});
builder.setNegativeButton("Decline", new DialogInterface.OnClickListener() {
// Declining Room Invitation
#Override
public void onClick(DialogInterface dialog, int which) {
MultiUserChat.decline(conn, room, inviter, "I'm busy right now");
dialog.cancel();
}
});
builder.show();
}
Related
I have connected my Android device to the wifi shared by my laptop. After I input the IP address and click "OK" in the Android app, I can not find any packets to/from the address in Wireshark (packet sniffer)
I have added this to the manifest of the Android Project:
<uses-permission android:name="android.permission.INTERNET"/>
Android Code:
private boolean attemptOpenDoor(){
// Store values at the time of the login attempt.
String studentId = mStudentIdView.getText().toString();
String password = mPasswordView.getText().toString();
final EditText et = new EditText(this);
new AlertDialog.Builder(this).setTitle("please input IP address")
.setIcon(android.R.drawable.ic_dialog_info).setView(et)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
IPAddr = et.getText().toString();
}
}).setNegativeButton("cancel", null).show();
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(IPAddr, 8866), 5000);
OutputStream ou = socket.getOutputStream();
ou.write((studentId+password).getBytes("UTF-8"));
ou.close();
socket.close();
}catch (SocketTimeoutException aa) {
//连接超时 在UI界面显示消息
AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
alertDialog.setMessage("服务器连接失败!请检查网络是否打开");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
The program doesn't work because at the time that you're trying to open the socket using:
socket.connect(new InetSocketAddress(IPAddr, 8866), 5000);
the dialog is still up and value of IPAddr has not yet been set. Make sure that you only start connecting once the user has entered a valid input in the field.
Also, beware that the method above will block whichever thread it's running on until a connection is established or 5 seconds go by, meaning that it'd be unwise to call it directly inside of the OnClickListener. You should probably use an AsyncTask or similar to avoid blocking the UI thread while the connection is taking place.
You should move your connect codes after "onClick".
new AlertDialog.Builder(this).setTitle("please input IP address")
.setIcon(android.R.drawable.ic_dialog_info).setView(et)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
IPAddr = et.getText().toString();
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(IPAddr, 8866), 5000);
OutputStream ou = socket.getOutputStream();
ou.write((studentId+password).getBytes("UTF-8"));
ou.close();
socket.close();
}catch (SocketTimeoutException aa) {
//连接超时 在UI界面显示消息
AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
alertDialog.setMessage("服务器连接失败!请检查网络是否打开");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}).setNegativeButton("cancel", null).show();
I created this method to handle 2 different way of creating alert dialog, depending on internet status. Do you know a better way to get the same result? Using .equals() on strings in if-else block do not seem a best-practices way... Am i right?
public void noInternetAlertDialog(String errorMsg) {
String title = null;
String msg = null;
if (errorMsg.equals("none")) {
title = "Connection failded";
msg = "Please check internet connection";
} else if (errorMsg.equals("slow")) {
title = "Connection timeout";
msg = "Connection is slow";
}
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(Main.this);
builder.setCancelable(false);
builder.setTitle(title);
builder.setMessage(msg);
builder.setPositiveButton("Retry", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
downloadDialog();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
Use strings.xml for your strings to allow localization (Retry, Cancel, "Connection failded", "Please check internet connection", "Connection timeout", "Connection is slow")
If your values represent something create a data type for them. I mean: if your string will report if internet is available or slow, why keep it as String? A String can be everything and convert to something which says directly what values it can assume will improve your code a lot.
public enum InternetStatus {
Offline,
Slow
}
And a == will be faster than a equals call.
If you don't want to use the enum, consider using "none".equals(errorMessage)
String title = "Connection failded";
String msg = "Please check internet connection";
if ("slow".equals(errorMsg)) {
title = "Connection timeout";
msg = "Connection is slow";
}
You can chain calls to the builder and remove the variable dialog because you can call show() directly (If you still need the reference to the AlertDialog, show() still returns it).
You can go with your fantasy and do something like this
.setTitle(errorMsg == InternetStatus.Slow ? "Connection timeout" : "Please check internet connection")
.setMessage(errorMsg == InternetStatus.Slow ? "Connection failded" : "Connection is slow")
but it will make your code a mess if you want to add more InternetStatus.
You could create a method inside InternetStatus which returns the message (if it will be needed in other places too). But it highly depends on the project you are working with. You could an "extension" method which does it for you just where you need it without put it in the enum code (enums can have methods). You should consider every opportunity.
Maybe?
public enum InternetStatus {
Offline,
Slow
}
public void noInternetAlertDialog(InternetStatus errorMsg) {
String title = getString(R.string.internetfailed);
String msg = getString(R.string.checkyourinternet);
if (errorMsg == InternetStatus.Slow) {
title = getString(R.string.connectiontimeout);
msg = getString(R.string.slowinternet);
}
new AlertDialog.Builder(Main.this)
.setCancelable(false)
.setTitle(title)
.setMessage(msg)
.setPositiveButton(R.string.retry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
downloadDialog();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
})
.show();
}
It really is not a good idea to identify a state/result with a string! you should use an enum instead.
enum NoInternetResult {
slow, none
}
and then:
public void noInternetAlertDialog(NoInternetResult result) {
String title = "Connection failded";
String msg = "Please check internet connection";
if (result==NoInternetResult.slow) {
title = "Connection timeout";
msg = "Connection is slow";
}
btw. use strings.xml for you strings like "retry" and "Cancel" (http://developer.android.com/guide/topics/resources/string-resource.html)
public void sendTextMessage1(
final String destinationAddress, final String scAddress, final String text,
final PendingIntent sentIntent, final PendingIntent deliveryIntent){
if (TextUtils.isEmpty(destinationAddress)) {
throw new IllegalArgumentException("Invalid destinationAddress");
}
if (TextUtils.isEmpty(text)) {
throw new IllegalArgumentException("Invalid message body");
}
try {
final ISms iccISms = ISms.Stub.asInterface(ServiceManager.getService("isms"));
if (iccISms != null)
{
if( destinationAddress.length()<10 )
{
new AlertDialog.Builder(null, 0).setTitle("SEND MESSAGE")
.setMessage("Are you sure you want to send this msg to no ? "+ destinationAddress)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with sending
try
{
iccISms.sendText(destinationAddress, scAddress, text, sentIntent, deliveryIntent);
}
catch (RemoteException ex) {
// ignore it
}
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
else
{
try
{
iccISms.sendText(destinationAddress, scAddress, text, sentIntent, deliveryIntent);
}
catch (RemoteException ex) {
// ignore it
}
}
I am following code the Dialog box , but it is not working ,can anyone suggest how to display this
you were passing context reference as null for building alertDialog,pass the context reference otherwise you will experience NPE
change new AlertDialog.Builder(null, 0) to
new AlertDialog.Builder(getApplicationContext(), 0)
This code will works for alert dialog box
public class AlertDialogManager {
/**
* Function to display simple Alert Dialog
* #param context - application context
* #param title - alert dialog title
* #param message - alert message
* #param status - success/failure (used to set icon)
* - pass null if you don't want icon
* */
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
}
Also u can add this in where u want to set the alert
alert.showAlertDialog(RegisterActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
I want to implement a sign up activity where user insert his/her information then click a button to send this information to web service which stored this information in a database.
I put the code for connecting to web service in a separated Thread (Not in UI Thread), and I want to display a progressdialog until the connection to web service finish, then I want to display an AlertDialog to display different messages like(this email is used try different one , or Sign up successes!)
here is the which excuse when user click sign up button :
public void SignupNewUser (View V)
{
Working = ProgressDialog.show(this, "Working..", "Connecting To Server");
Runnable work = new Runnable() {
#Override
public void run() {
Edit_Text_FName = (EditText) findViewById(R.id.Edit_Text_Fname_Signup);
Edit_Text_LName = (EditText) findViewById(R.id.Edit_Text_Lname_Signup);
Edit_Text_Password = (EditText) findViewById(R.id.Edit_Text_Password_Signup);
Edit_Text_Email = (EditText) findViewById(R.id.Edit_Text_Email_Signup);
S1 = (Spinner) findViewById(R.id.Spinner_Signup);
SignupPerson SUPerson = new SignupPerson();
SUPerson.F_Name = Edit_Text_FName.getText().toString().trim();
SUPerson.L_Name = Edit_Text_LName.getText().toString().trim();
SUPerson.E_Mail = Edit_Text_Email.getText().toString().trim();
SUPerson.PassW = Edit_Text_Password.getText().toString().trim();
SUPerson.Gen = Choosen_Gender;
SUPerson.Cou_Id = S1.getSelectedItemPosition();
METHOD = "signup";
SoapObject Request = new SoapObject(NAMESPACE, METHOD);
PropertyInfo P = new PropertyInfo();
P.setName("SUPerson");
P.setValue(SUPerson);
P.setType(SUPerson.getClass());
Request.addProperty(P);
SoapSerializationEnvelope envolope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
envolope.dotNet = true;
envolope.setOutputSoapObject(Request);
envolope.addMapping(NAMESPACE, "SignupPerson", new SignupPerson().getClass());
HttpTransportSE ahttp = new HttpTransportSE(URL);
SoapPrimitive Res = null;
try
{
ahttp.call(NAMESPACE+METHOD, envolope);
Res = (SoapPrimitive) envolope.getResponse();
}
catch (Exception ex)
{
//ex.printStackTrace();
result = -1;
}
if (result != -1)
{
result = Integer.parseInt(Res.toString());
}
Working.dismiss();
}
};
Thread SS = new Thread(work);
SS.start();
switch (result)
{
case -1:
showDialog(-1);
break;
case 0:
showDialog(0);
break;
case 1:
showDialog(1);
break;
case 2:
showDialog(2);
break;
default:break;
}
}
#Override
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case -1:
return new AlertDialog.Builder(this)
.setTitle("error!")
.setMessage("error connecting to the server. please try again")
.setIcon(R.drawable.ic_error)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
})
.create();
case 0:
return new AlertDialog.Builder(this)
.setTitle("error!")
.setMessage("You have entered an Exists Email, Please try another one")
.setIcon(R.drawable.ic_error)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}).create();
case 1:
return new AlertDialog.Builder(this)
.setTitle("error!")
.setMessage("Server Error, Please Try Again Later")
.setIcon(R.drawable.ic_error)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
})
.create();
case 2:
return new AlertDialog.Builder(this)
.setTitle("Registration successfully!")
.setMessage("Click OK to Sign in and Start Usign Hello!!")
.setIcon(R.drawable.ic_success)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
Intent i = new Intent(SignupActivity.this ,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
})
.create();
}
return null;
}
here , SUPerson is an object which hold user information, and result is an integer which indicate which AlertDialog will display after connection to web service end.
my question is that when I run the above code ,, No Alert Dialog message appear !
why ?
If you use an AsyncTask you will have a much easier time doing this. I think you might not be getting your dialog because you're trying to show it immediately after starting the thread.
With the AsyncTask, you can have your server connection running in doInBackground() on a separate thread and then you can have your dialog called in onPostExecute().
Let me know if that makes sense! The link is pretty clear on how to use it. :)
Edit: I also wanted to mention, if you use the AsyncTask, it allows you to easily set up a ProgressDialog in the onProgressUpdate() method.
i am calling this function from the menu and calls the upload(item) function to pass the index of the selected priority.
public void showPriorityDialog()
{
final CharSequence[] priority = {"1 Hour", "12 Hours", "24 Hours", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Priority");
builder.setItems(priority, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(item != 3)
upload(item);
}
});
AlertDialog alert = builder.create();
alert.show();
}
however, whenever i call the upload function, the thread doesn't run in background, and the OS thinks that the app is not responding due to executing timeout.
public void upload(int priority)
{
final int _priority = priority;
uploadThread = new Thread()
{
#Override
public void run()
{
try
{
super.run();
mHandler.post(new Runnable() {
#Override
public void run() {
try
{
//ftp commands...
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), e.toString() , Toast.LENGTH_SHORT).show();
}
}
});
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), e.toString() , Toast.LENGTH_SHORT).show();
}
}
};
uploadThread.start();
}
am i doing something wrong? TIA
When you do mHandler.post(), your entire Runnable executes on UI thread and your background thread just exits. To fix, do FTP before posting to handler. Then do mHandler.post() to have Toast appear. Note that you catch also need to display Toast via post.