简体   繁体   English

无法将套接字从一个活动传递到另一个活动

[英]Unable to pass socket from one Activity to another

I was trying to pass my socket connection from one activity to another. 我试图将套接字连接从一种活动传递到另一种活动。 Here is my code snippet. 这是我的代码段。

public class MainActivity extends AppCompatActivity {

            //private EditText serverIp;

            private Button connectPhones;

            protected String SERVER_IP_ADDR = "172.16.1.103";

            protected String SERVER_PORT = "8889";

            private boolean connected = false;

            private Handler handler = new Handler();

            Socket socket;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                //serverIp = (EditText) findViewById(R.id.server_ip);
                connectPhones = (Button) findViewById(R.id.connect);
                connectPhones.setOnClickListener(connectListener);
            }


            public Socket getSocket(){
                Log.wtf("MainActivity : ",socket.toString());
                return socket;
            }

            private View.OnClickListener connectListener = new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (!connected) {
                        //SERVER_IP_ADDR = SERVER_IP_ADDR.getText().toString();
                        if (!SERVER_IP_ADDR.equals("")) {
                            Thread cThread = new Thread(new ClientThread());
                            cThread.start();
                        }
                    }
                }
            };

            public class ClientThread implements Runnable {

                public void run() {
                    try {
                        InetAddress serverAddr = InetAddress.getByName(SERVER_IP_ADDR);
                        Log.d("ClientActivity", "C: Connecting...");
                        socket = new Socket(serverAddr, Integer.parseInt(SERVER_PORT));
                        connected = true;

                            try {
                                Log.d("ClientActivity", "C: Sending command.");
                                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                                        .getOutputStream())), true);
                                out.println("Hey Server!");
                                Log.d("ClientActivity", "C: Sent.");
                                Intent intent = new Intent(getApplicationContext(), SocketInteraction.class);
                                startActivityForResult(intent,1);
                            } catch (Exception e) {
                                Log.e("ClientActivity", "S: Error", e);
                            }

                        //socket.close();
                        Log.d("ClientActivity", "C: Closed.");
                    } catch (Exception e) {
                        Log.e("ClientActivity", "C: Error", e);
                        connected = false;
                    }
                }

            }
        }

And in other activity, I am calling it like this 在其他活动中,我这样称呼它

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.socketinteraction);
    MainActivity mainActivity = new MainActivity();
    final Socket socket = mainActivity.getSocket();   //returns null pointer

But I don't know why, Its returning a Nullpointerexception. 但是我不知道为什么,它返回一个Nullpointerexception。 Can someone please assist me on how should I deal with this ? 有人可以帮我解决这个问题吗?

You need to use Singleton patterns class like the following: 您需要使用Singleton模式类,如下所示:

public class SocketSingleton {


private static Socket socket;

public static void setSocket(Socket _socket){
    SocketSingleton.socket=_socket;
}

public static Socket getSocket(){
    return SocketSingleton.socket;
}

and then in your MainActivity use the following: 然后在您的MainActivity使用以下命令:

SocketSingleton.setSocket(socket);
Intent i = new Intent(getActivity().getApplicationContext(), NewActivity.class);
startActivity(intent);

and finally in your NewActivity use the following: 最后在您的NewActivity使用以下命令:

Socket socket = SocketSingleton.getSocket();

I am sorry to say this, but your code is a total mess, 抱歉,您的代码很混乱,

Reasons 原因

  1. We should not create an instance of an activity, its the job of android framework to create, we can only start an activity. 我们不应该创建一个活动的实例,它是在android框架中创建的工作,我们只能启动一个活动。

  2. The second activity has a different layout 'socketinteraction', and the code to create socket is written in the button click listener, which is in your MainActivity layout. 第二个活动具有不同的布局“ socketinteraction”,并且用于创建套接字的代码是在MainActivity布局中的按钮单击侦听器中编写的。

You might want to do something like this, 您可能想做这样的事情,

From your other activity, 从您的其他活动中,

  1. Add a button in your layout 'socketinteraction' 在布局“ socketinteraction”中添加一个按钮
  2. On click of the button,start mainactivity like below, 点击按钮后,开始如下所示的维护活动,

    startActivityForResult(new Intent(this,MainActivity.class),0) startActivityForResult(new Intent(this,MainActivity.class),0)

and always use Intent to communicate between activities. 并始终使用Intent在活动之间进行交流。 Refer this link, http://developer.android.com/training/basics/intents/result.html 请参阅此链接, http://developer.android.com/training/basics/intents/result.html

  1. Do your task in MainActivity, and once your job is done, set the Result using setResult method, 在MainActivity中完成任务,完成工作后,请使用setResult方法设置Result,

Refer to this link, 参考此链接,

http://stackoverflow.com/questions/920306/sending-data-back-to-the-main-activity-in-android http://stackoverflow.com/questions/920306/sending-data-back-to-the-main-activity-in-android

You can do it quite easily, create and instance of your MainActivity like this. 您可以很容易地做到这一点,像这样创建和创建MainActivity实例。

    public class MainActivity extends Activity {
        public static MainActivity sInstance = null;

        protected void onCreate(Bundle bundle) {
             super.onCreate(...);
             setContentView(...);
             sInstance = this;
        }
    }

Now in your other activity you can call it simply like this. 现在,在您的其他活动中,您可以像这样简单地调用它。

    if (MainActivity.sInstance != null) {
         final Socket socket = MainActivity.sInstance.getSocket();
    }

this creates your MainActivity a Singleton while its running. 这会在您的MainActivity运行时为其创建一个Singleton。 Just don't finish it when you go to the next Activity and when you are done and when you are shutting your app down. 只是当您转到下一个活动,完成时以及关闭应用程序时,不要完成它。 Release the sInstance like this, Don't forget this part. 像这样释放sInstance,不要忘记这一部分。

    sInstance = null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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