Do not handle the event in the new Activity

Post here your questions about the Java client / Android API for SFS2X

Moderators: Bax, Lapo

Do not handle the event in the new Activity

Postby kapacb » 26 Mar 2012, 16:40

Hello everyone, sorry for that question, but I spent two days and found nothing.

    Ok, I have 2 Activity.
    At first, I connect to the server, and create a connection, login, join into the room.
    In the second, I use the old connection (from the first class), and create calculations, including ExtensionRequest.
    The problem is that the listeners created by me in the second class do not work, and use of the first class.
    How to make listeners out of the second class have worked?

See code:
First (Main) Activity:
Code: Select all
package com.data.hardwork;

import sfs2x.client.SmartFox;
import sfs2x.client.core.BaseEvent;
import sfs2x.client.core.IEventListener;
import sfs2x.client.core.SFSEvent;
import sfs2x.client.entities.User;
import sfs2x.client.requests.CreateRoomRequest;
import sfs2x.client.requests.JoinRoomRequest;
import sfs2x.client.requests.LoginRequest;
import sfs2x.client.requests.PublicMessageRequest;
import sfs2x.client.requests.RoomExtension;
import sfs2x.client.requests.RoomSettings;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.smartfoxserver.v2.exceptions.SFSException;

public class HardWorkActivity extends Activity implements IEventListener {
    /** Called when the activity is first created. */
   public static SmartFox sfs;
   public static IEventListener evtListener;
   
   private EditText debugtxt;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.setProperty("java.net.preferIPv6Addresses", "false");
        setContentView(R.layout.main);
       
        sfs = new SmartFox(true);
        evtListener = this;
        sfs.addEventListener(SFSEvent.CONNECTION, evtListener);
        sfs.addEventListener(SFSEvent.CONNECTION_LOST, evtListener);
        sfs.addEventListener(SFSEvent.LOGIN, evtListener);
        sfs.addEventListener(SFSEvent.LOGIN_ERROR, evtListener);
        sfs.addEventListener(SFSEvent.ROOM_JOIN, evtListener);
        sfs.addEventListener(SFSEvent.ROOM_JOIN_ERROR, evtListener);
        sfs.addEventListener(SFSEvent.PUBLIC_MESSAGE, evtListener);
       
        Button connect_btn = (Button) findViewById(R.id.button1);
        connect_btn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            final SmartFox finalsfs = sfs;
            new Thread() {
               @Override
               public void run() {
                  finalsfs.connect("192.168.0.6",9933);
               }
            }.start();
         }
      });
       
        Button login_btn = (Button) findViewById(R.id.button2);
        login_btn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {            
            sfs.send(new LoginRequest("user_"+String.valueOf(Math.random()), "", "BasicExamples"));
         }
      });
       
        Button join_btn = (Button) findViewById(R.id.button3);
        join_btn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            sfs.send(new JoinRoomRequest("The Lobby"));
         }
      });
       
        Button publicmsg_btn = (Button) findViewById(R.id.button4);
        publicmsg_btn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            sfs.send(new PublicMessageRequest("тестовое сообщение"));
         }
      });
       
        Button roomjoin_btn = (Button) findViewById(R.id.button5);
        roomjoin_btn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            RoomSettings sets = new RoomSettings("OtherRoom");
            RoomExtension exten = new RoomExtension("Hardwork", "net.server.Hardwork");
            sets.setExtension(exten);
            sets.setMaxUsers(40);
            sfs.send(new CreateRoomRequest(sets, true));
            Intent it = new Intent(HardWorkActivity.this,Otherroom.class);
            startActivity(it);
         }
      });
       
        debugtxt = (EditText) findViewById(R.id.editText1);
    }
   
   @Override
   public void dispatch(final BaseEvent event) throws SFSException {
      runOnUiThread(new Runnable() {
         @Override
         public void run() {
            //выводим на экран диалог типа toast как дебаг
            Toast tt = Toast.makeText(getApplicationContext(), event.getType(), Toast.LENGTH_SHORT);
            tt.show();
            
            if(event.getType().equalsIgnoreCase(SFSEvent.CONNECTION)) {
               debug("Соединение с сервером установлено");
            }
            
            if(event.getType().equalsIgnoreCase(SFSEvent.CONNECTION_LOST)) {
               debug("Потеряно соединение с сервером");
            }
            
            if(event.getType().equalsIgnoreCase(SFSEvent.LOGIN)) {
               debug("Залогинились с ником "+sfs.getMySelf().getName()+" в зону по умолчанию");
            }
            
            if(event.getType().equalsIgnoreCase(SFSEvent.LOGIN_ERROR)) {
               debug("Ошибка логина, попробую текст показать: "+event.getArguments().get("errorMessage"));
            }
            
            if(event.getType().equalsIgnoreCase(SFSEvent.ROOM_JOIN)) {
               debug("Вошли в комнату по умолчанию");
            }
            
            if(event.getType().equalsIgnoreCase(SFSEvent.ROOM_JOIN_ERROR)) {
               debug("Ошибка входа в комнату, пропую текст:"+event.getArguments().get("errorMessage"));
            }
            
            if(event.getType().equalsIgnoreCase(SFSEvent.PUBLIC_MESSAGE)) {
               User sender = (User)event.getArguments().get("sender");
                  String msg = event.getArguments().get("message").toString();
               debug("Публичное сообщение от "+sender.getName()+" пишет "+msg);
            }
         }
      });
   }
   
   @Override
   protected void onDestroy()
   {
      super.onDestroy();
      
      if(sfs != null)
      {
         sfs.removeEventListener(SFSEvent.CONNECTION, evtListener);       
      }
   }
   
   @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
           
            AlertDialog.Builder build = new AlertDialog.Builder(this);
           build.setMessage("Вы уверены, что хотите выйте?").setTitle("Выход")
              .setPositiveButton("Да", new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which) {
                  sfs.disconnect();
                  finish();
               }
            })
            .setNegativeButton("Нет", new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which) {
                  
               }
            });
           
           build.show();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
   
   public void debug(String text) {
      debugtxt.setText(text+"\n"+debugtxt.getText());
   }
}


And second Activity (Otherroom):
Code: Select all
package com.data.hardwork;

import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.exceptions.SFSException;

import sfs2x.client.SmartFox;
import sfs2x.client.core.BaseEvent;
import sfs2x.client.core.IEventListener;
import sfs2x.client.core.SFSEvent;
import sfs2x.client.entities.User;
import sfs2x.client.requests.ExtensionRequest;
import sfs2x.client.requests.PublicMessageRequest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Otherroom extends Activity implements IEventListener {
   private static SmartFox sfs;
   private TextView debugtxt;
   private IEventListener evrList;
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.otherroom);
       sfs = HardWorkActivity.sfs;
       sfs.addEventListener(SFSEvent.PUBLIC_MESSAGE, evrList);
       sfs.addEventListener(SFSEvent.EXTENSION_RESPONSE, evrList);
      
       Button publicmsg_btn = (Button) findViewById(R.id.button1);
        publicmsg_btn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            sfs.send(new PublicMessageRequest("тестовое сообщение"));
            sfs.send(new ExtensionRequest("e_hand", new SFSObject(),sfs.getLastJoinedRoom()));
         }
      });
      
       debugtxt = (TextView) findViewById(R.id.textView1);
       debugtxt.setText("Пользователей в комнате "+String.valueOf(sfs.getRoomByName("OtherRoom").getUserCount()));
   }
   @Override
   public void dispatch(final BaseEvent event) throws SFSException {
      //выводим на экран диалог типа toast как дебаг
      Toast tt = Toast.makeText(getApplicationContext(), event.getType(), Toast.LENGTH_SHORT);
      tt.show();
      
      if(event.getType().equalsIgnoreCase(SFSEvent.PUBLIC_MESSAGE)) {
         User sender = (User)event.getArguments().get("sender");
            String msg = event.getArguments().get("message").toString();
            debug("Юзер "+sender.getName()+" пишет "+msg);
      }
   }
   
   public void debug(String text) {
      debugtxt.setText(text+"\n"+debugtxt.getText());
   }

}



And This part in second activity not working:
Code: Select all
@Override
   public void dispatch(final BaseEvent event) throws SFSException {
      //выводим на экран диалог типа toast как дебаг
      Toast tt = Toast.makeText(getApplicationContext(), event.getType(), Toast.LENGTH_SHORT);
      tt.show();
     
      if(event.getType().equalsIgnoreCase(SFSEvent.PUBLIC_MESSAGE)) {
         User sender = (User)event.getArguments().get("sender");
            String msg = event.getArguments().get("message").toString();
            debug("Юзер "+sender.getName()+" пишет "+msg);
      }
   }


Please help me, I am very tired of searching for :(
p.s. This special code for publish in the forum
kapacb
 
Posts: 11
Joined: 23 Feb 2011, 04:05

Re: Do not handle the event in the new Activity

Postby A51Integrated » 27 Mar 2012, 17:35

Listen for all your SFS events in your main class and communicate using intents to your other classes. Here's a good tutorial on how to do it:
http://www.vogella.de/articles/AndroidI ... ticle.html

So basically, all your SFS listeners are contained in a single location and broadcast their results to specific other classes.
A51 Integrated
http://a51integrated.com / +1 416-703-2300
User avatar
A51Integrated
 
Posts: 240
Joined: 03 Jan 2012, 19:55
Location: Toronto, Canada

Re: Do not handle the event in the new Activity

Postby kapacb » 27 Mar 2012, 17:46

I know how to work with Activity and transfer data between them. I can not understand why my method of dispatch is not overwritten in the new Activity, and uses the old.

Just, look at the code and show the error, not a lot of code because :)

In the example of Tris, it works, but in my case did not want to work
kapacb
 
Posts: 11
Joined: 23 Feb 2011, 04:05

Re: Do not handle the event in the new Activity

Postby A51Integrated » 27 Mar 2012, 18:05

It's because you're not overriding the first class and the first class is listening for that same event (PUBLIC_MESSAGE) and is handling it. Either remove the event handler from the first class or expand it to communicate the message to the second class.
A51 Integrated
http://a51integrated.com / +1 416-703-2300
User avatar
A51Integrated
 
Posts: 240
Joined: 03 Jan 2012, 19:55
Location: Toronto, Canada

Re: Do not handle the event in the new Activity

Postby kapacb » 27 Mar 2012, 18:16

That is, if I write removeEventListener (SFSEvent.PUBLIC_MESSAGE, this) in the first Activity, before the call intent, in the second Activity the event handler and method dispath will it work?
kapacb
 
Posts: 11
Joined: 23 Feb 2011, 04:05

Re: Do not handle the event in the new Activity

Postby A51Integrated » 27 Mar 2012, 18:26

You'll have to try it. It should. But as long as you have a reference to the SFS client in your second activity, you should be able to create a new listener and handle the event.

However, I prefer for architecture reasons, to organize the code the way I mentioned in my first post - that is, listen for all SFS events in a single location and fork the results to the right activity. That way, you don't have to keep track of where you have attached a listener and where you have removed one - it all exists in a central location.
A51 Integrated
http://a51integrated.com / +1 416-703-2300
User avatar
A51Integrated
 
Posts: 240
Joined: 03 Jan 2012, 19:55
Location: Toronto, Canada

Re: Do not handle the event in the new Activity

Postby kapacb » 27 Mar 2012, 18:36

I agree with you, it's much easy. Thanks for the advice.
kapacb
 
Posts: 11
Joined: 23 Feb 2011, 04:05


Return to SFS2X Java / Android API

Who is online

Users browsing this forum: No registered users and 2 guests