サーバー クラス (プレーン Java クラス) と MainActivity クラス (Android アクティビティ クラス) の 2 つのクラスがあります。MainActivity を使用して Server クラスから静的変数にアクセスしようとしていますが、静的変数を使用しようとするたびに、常に null が返されます。
Server クラスのコードは次のとおりです。
public class Server {
private static String clientMsg;
public static String getClientMsg() {
return clientMsg;
}
public static void main(String[] args){
/*Some Server code here*/
while(true){
try {
clientSocket = serverSocket.accept();
//READ THE MESSAGE SENT BY CLIENT
dataInputStream = new DataInputStream(clientSocket.getInputStream());
//Here is where I assigned the static variable clientMsg
clientMsg = dataInputStream.readUTF();
dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
dataOutputStream.writeUTF("Message Received!");
} catch (IOException e) {
e.printStackTrace();
}
/* Rest of the code here */
}
}
}
MainActivity クラスのコードは次のとおりです。
public class MainActivity extends FragmentActivity implements LocationListener{
private Button connect;
/*Some variable declarations here*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connect = (Button) findViewById(R.id.connect);
/*Some code here*/
connect.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String msg = Server.getClientMsg();
if(msg != null)
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Client Message is null!", Toast.LENGTH_LONG).show();
}
});
/*Rest of the code here*/
}
}
Serverクラスから静的変数clientMsgにどのようにアクセスしても、常に null が返されます。
コードで何か間違ったことをしましたか? 静的変数にアクセスするにはどうすればよいですか? または、静的である必要さえありません.null値を返さずに変数clientMsgにアクセスするにはどうすればよいですか?
/編集/
私の質問が明確でなくて申し訳ありません。私は実際に 2 つのクラスを別々に実行しています。1 つはコンソールに表示されるプレーン Java として、もう 1 つは Android エミュレーターに表示されます。最後に、Android フォンでクライアント アプリを実行しています。
したがって、基本的には、クライアント アプリを使用してサーバーにメッセージを送信し、サーバーはメッセージの値をclientMsg変数に格納します。次に、System.out.println() を使用して clientMsg の値を表示しようとしましたが、うまくいきました。しかし、MainActivity の変数にアクセスすると、その値は null になります。それがなぜなのか、何か理由はありますか?