I have two classes: Server class (plain java class) and MainActivity class (android activity class). I am trying to access a static variable from the Server class with my MainActivity but every time I tried to use the static variable, it always returns null.
Here is my code for the Server class:
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 */
}
}
}
Here is my code for the MainActivity class:
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*/
}
}
No matter how I access the static variable clientMsg from the Server class, it always returns null.
Did I do something wrong in the code? How should I access the static variable? Or it doesn't even have to be static, how do I simply access the variable clientMsg without it returning a null value?
/EDIT/
Sorry for not being clear with my question. I am actually running the 2 classes separately, one as a plain Java that displays in console and the other displays in the Android emulator and lastly, I have a client app running in my android phone.
So basically, I use the client app to send a message to the server which stores the value of the message in the clientMsg variable. Then I tried displaying the value of clientMsg using System.out.println() and it works! But when I access the variable in the MainActivity, its value becomes null. Any reason as to why that is?
Servercode actually running in the same process? Are you sure it's received a message?Server's main()?clientMsgis being set? I see it getting set only from main method