• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps How to show toast/dialogue in Emitter.Listener

ware4u

Lurker
I can't show toast in Emitter.Listener, below is my code, with value login is true it's ok, but login value is false the app is stop.

I use socket io for server. Thk for reading my topic

Code:
 private Emitter.Listener onLogin = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            String data =  args[0].toString();

            if(data == "true"){

                Intent intent = new Intent(LoginActivity.this,RoomListChat.class);
                startActivity(intent);
                finish();

            }else{
               Toast.makeText(LoginActivity.this, "Username/passwod error", Toast.LENGTH_SHORT).show();
               

            }

        }
    };

-- onCreate event

Code:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_chat);

    mSocket.connect();
    mSocket.on("login",onLogin);

    username = (EditText)findViewById(R.id.txtUsername);
    password = (EditText)findViewById(R.id.txtPassword);
    btnLogin = (Button) findViewById(R.id.btnLogin);
    strPassword = md5(password.getText().toString().trim());

    saveLoginCheckBox=(CheckBox) findViewById(R.id.chkRemember);

    loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
    loginPrefsEditor = loginPreferences.edit();
    saveLogin = loginPreferences.getBoolean("saveLogin", false);

    if (saveLogin)
    {
        username.setText(loginPreferences.getString("username", ""));
        password.setText(loginPreferences.getString("password", ""));
        saveLoginCheckBox.setChecked(true);
    }
    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String strPassword = md5(password.getText().toString().trim());
            try {

                strPassword =strPassword.substring(0,39);
            }
            catch (Exception e){e.printStackTrace();}
            loginUser(username.getText().toString().toLowerCase().trim(),strPassword);
        }
    });
}
 
You can't execute UI operations from a non-UI thread. In an Android app, only the main thread handles UI events, including displaying of Toast dialogs.
In your app, the 'onLogin' listener is executing in a separate thread. If you wish you can add a message in the Log, or if you must display a Toast dialog, then use the following technique to run it on the main thread

http://stackoverflow.com/questions/13267239/toast-from-a-non-ui-thread

Some other options here:

https://www.intertech.com/Blog/android-non-ui-to-ui-thread-communications-part-1-of-5/
 
Back
Top Bottom