简体   繁体   中英

Have to call singleton socketIO class in different activities?

i am using gottox-socket.io library for my socket programming. I have created singleton class for socket. I am able to call it in main activity but i am not able to call it into another activities.... This is my singleton class..

public class MainActivity extends Activity {
    EditText uname, passwd;
    Button login;
    JSONObject json;
    SocketIOClient socket;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    socket = new SocketIOClient();
    try {
        SocketIOClient.initInstance();
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    json = new JSONObject();
    uname = (EditText) findViewById(R.id.unameED);
    passwd = (EditText) findViewById(R.id.passwdED);
    login = (Button) findViewById(R.id.loginButton);
    login.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            try {
                json.put("username", uname.getText().toString().trim());
                json.put("password", passwd.getText().toString().trim());
              //request send to server    
                SocketIOClient.emit("login_request", json);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });

}

} 

Also i have used abstract class to get the json reposnse from singleton classs to activity. here is my abstract class

    public abstract class ResponseHandler 
{
    private Context context;

    public abstract void execute (JSONObject jsonObject) throws JSONException;

    public ResponseHandler (Context ctx)
    {
        this.context = ctx;
    }

    public void handleObject(JSONObject jsonObject) throws Exception
    {
        execute(jsonObject);

    }
}

Have you thought about creating a GlobalClass in a helper package (eg. com.project.name.helpers) and call it from there. Like

public class GlobalClass extends Activity {
    public static SocketIOClient socket = new SocketIOClient();
}

Then you can call it from your activities after importing your GlobalClass since it is a static and already created class like:

import com.project.name.helpers;
public SomeActivity extends Activity 
{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try{
            GlobalClass.socket.initInstance();
        }
        catch{
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM