我試圖將套接字連接從一個活動傳遞給另一個活動。這是我的代碼片段。無法將套接字從一個活動傳遞到另一個活動
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;
}
}
}
}
而在其他活動中,我調用它像這樣
@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
但我不知道爲什麼,它返回一個NullPointerException異常。 有人可以幫助我應該如何處理這個?
你不能用'new'實例化一個'Activity'並讓它正常工作。即使可以,新實例也不會有與前一個實例相同的「Socket」。 –
你解決了這個問題嗎? – Pooya
我已經upvoted你的答案,我還沒有嘗試過呢!所以一旦我回來,就要把它標記正確。 –