I'm trying to run a UDP connection with external equipment. I want it to send a message to the equipment every 3 second and read the response.
I created 3 classes: main, sender and receive.
I open a Runnable for both sender and receive and let them sleep for 3 seconds before continue.
My problem is, when i push the button on the screen, the messages are send and received, however they are not updated on my screen because the update line is not in a loop. How do i tell it to update the screen every 3 second? the code for reading the message and show it, is this:
textViewState.setText(udpReceive.receivedMessage);
Code
public class MainActivity extends AppCompatActivity {
public static TextView textViewState;
public static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewState = (TextView) findViewById(R.id.textView);
context = getApplicationContext();
}
public void buttonConnect(View v) {
(new Thread(new udpSender())).start();
(new Thread(new udpReceive())).start();
textViewState.setText(udpReceive.receivedMessage);
}
}
Class to send a message:
public class udpSender implements Runnable {
public void run() {
while (true) {
String messageStr = "Hello Android!";
int server_port = 8888;
DatagramSocket s = null;
try {
s = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
}
InetAddress local = null;
try {
local = InetAddress.getByName("192.168.43.159");
} catch (UnknownHostException e) {
e.printStackTrace();
}
int msg_length = messageStr.length();
byte[] message = messageStr.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length, local, server_port);
try {
s.send(p);
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Class to receive message from udp
public class udpReceive implements Runnable {
private static final int MAX_UDP_DATAGRAM_LEN = 100;
private static final int UDP_SERVER_PORT = 8888;
public static String receivedMessage;
public void run() {
while (true) {
String message;
byte[] lmessage = null;
lmessage = new byte[MAX_UDP_DATAGRAM_LEN];
DatagramPacket packet = null;
DatagramSocket socket = null;
try {
packet = new DatagramPacket(lmessage, lmessage.length);
socket = new DatagramSocket(UDP_SERVER_PORT);
socket.receive(packet);
message = new String(lmessage, 0, packet.getLength());
receivedMessage = message;
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
socket.close();
}
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
In any class that is in another thread, try doing this
Handler handler = new Handler(getActivity().getMainLooper());
handler.post(new Runnable(){
// your TextView goes here
})
Only the UI thread (main thread) can access UI elements
// Your message receiving class
...
message = new String(lmessage, 0, packet.getLength());
final String message_received = new String(lmessage, 0, packet.getLength());
...
MainActivity.context.runOnUiThread(new Runnable() {
#Override
public void run() {
MainActivity.textViewState.setText(message_received);
}
});
...
I found a solution based on both of your answers :) Thank you
MainActivity class:
public static Handler UIHandler;
static {
UIHandler = new Handler(Looper.getMainLooper());
}
public static void runOnUI(Runnable runnable) {
UIHandler.post(runnable);
}
receive class
MainActivity.runOnUI(new Runnable() {
public void run() {
MainActivity.textViewState.setText(message_received);
}
});
Related
I'm tracking the UDP messages I'm sending from my android phone on Wireshark, but the source port number changes every time I send a message.
So I have two questions:
Is this bad if I want to receive messages back? Or would it be find, just each received message comes through a different port?
If the answer to 1) is yes it is bad, then what should I do to change that?
Here's my code:
edit: Full code
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final int SERVERPORT = 1111;
public static final String SERVER_IP = "255.255.255.255";
private LinearLayout msgList;
private EditText edMessage;
private int clientTextColor;
private ClientThread clientThread;
private Thread thread;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msgList = findViewById(R.id.msgList);
edMessage = findViewById(R.id.edMessage);
clientTextColor = ContextCompat.getColor(this, R.color.colorAccent);
handler = new Handler();
}
// Just for displaying messages on device
public TextView textView(String message, int color) {...}
public void showMessage(final String message, final int color) {
handler.post(new Runnable() {
#Override
public void run() {
msgList.addView(textView(message, color));
}
});
}
// Implementation
#Override
public void onClick(View view) {
if(view.getId() == R.id.clear) {
msgList.removeAllViews();
}
if (view.getId() == R.id.send_data) {
// Starting thread
clientThread = new ClientThread();
thread = new Thread(clientThread);
thread.start();
String clientMessage = edMessage.getText().toString().trim(); // Client's Message
showMessage(clientMessage, Color.BLUE); // Just display
if (null != clientThread) {
clientThread.sendMessage(clientMessage + "\r\n");
}
}
}
class ClientThread implements Runnable {
byte[] buffer = new byte[1024];
#Override
public void run() {
try {
while (true) {
DatagramSocket ds = new DatagramSocket(SERVERPORT);
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
ds.receive(dp);
String serverMsg = new String(dp.getData(), 0, dp.getLength());
showMessage("Server: " + serverMsg, clientTextColor);
ds.close();
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
}
void sendMessage(final String message) { // Called by "Send Data" button
new Thread(new Runnable() {
#Override
public void run() {
try {
byte[] msg = message.getBytes();
InetAddress ip = InetAddress.getByName(SERVER_IP);
DatagramSocket socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(msg, msg.length, ip, SERVERPORT);
socket.setBroadcast(true);
socket.send(packet);
} catch(Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
String getTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(new Date());
}
#Override
protected void onDestroy() {
super.onDestroy();
if (null != clientThread) {
clientThread.sendMessage("Disconnect");
clientThread = null;
}
}
}
I need to create an application using android socket level programming, I created a connection between server and client but I need to show waiting server IP list at client side and select one IP from the list and establish a connection between them.
Here is my code for server side
public class Server extends AppCompatActivity {
private static final String TAG = "ServerActivity";
private TextView tvServerStatus;
private TextView recievemsg;
InetAddress receiverAddress;
public static String SERVERIP = "";
DatagramSocket datagramSocket;
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
Handler updateConversationHandler;
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
updateConversationHandler = new Handler();
tvServerStatus = (TextView) findViewById(R.id.tvServerStatus);
recievemsg=(TextView)findViewById(R.id.send_msg);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
try {
datagramSocket = new DatagramSocket(8080);
byte[] buffer = "0123456789".getBytes();
byte[] address=SERVERIP.getBytes();
receiverAddress = InetAddress.getByAddress(address);
DatagramPacket packet = new DatagramPacket(
buffer, buffer.length, receiverAddress, 8080);
datagramSocket.send(packet);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getLocalIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
public class ServerThread implements Runnable {
#Override
public void run() {
try {
Log.e(TAG, "Server IP: " + SERVERIP);
if (SERVERIP != null) {
handler.post(new Runnable() {
#Override
public void run() {
tvServerStatus.setText("Listening On Ip: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (!Thread.currentThread().isInterrupted()) {
{
try {
// LISTEN FOR INCOMING CLIENTS
Socket client = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(client);
new Thread(commThread).start();
// Log.e(TAG, "Client Socket: " + client);
// new Clients_Handle(client, ROOT_DIRECTORY).start();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
handler.post(new Runnable() {
#Override
public void run() {
tvServerStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (IOException e) {
handler.post(new Runnable() {
#Override
public void run() {
tvServerStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
recievemsg.setText(recievemsg.getText().toString() + "Client Says: " + msg + "\n");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
serverSocket.close();
Log.e(TAG,"Socket Closed");
} catch (IOException e) {
e.printStackTrace();
}
}
}
And here is my client side code
public class Clientss extends AppCompatActivity {
private static final String TAG = "Client_Activity";
private EditText etServerIp;
private EditText etMsg;
private Button btnConnectClients;
private Button btnSendMsg;
private TextView textIn;
private String serverIpAddress = "";
private String t;
private boolean connected = false;
DatagramSocket datagramSocket;
DatagramPacket packet;
private Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clientss);
Log.e(TAG, "ONCREATE METHOD");
textIn = (TextView)findViewById(R.id.txt_msg);
initializations();
eventClickListener();
try {
datagramSocket = new DatagramSocket(8080);
byte[] buffer = new byte[10];
packet = new DatagramPacket(buffer, buffer.length);
datagramSocket.receive(packet);
byte[] buff = packet.getData();
textIn.setText(buff.toString());
System.out.println("this is incoming ip"+buff.toString());
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// textIn.setText(t);
}
private void eventClickListener() {
btnConnectClients.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = etServerIp.getText().toString().trim();
connectsClient();
}
}
});
btnSendMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = etMsg.getText().toString().trim();
ClientResponseTask clientResponseTask=new ClientResponseTask(msg);
clientResponseTask.execute();
}
});
}
private void connectsClient() {
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
private void initializations() {
etServerIp = (EditText) findViewById(R.id.etServerIp);
etMsg = (EditText) findViewById(R.id.etMsg);
btnSendMsg = (Button) findViewById(R.id.btnMsgSend);
btnConnectClients = (Button) findViewById(R.id.btnConnect);
}
private class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.e(TAG, "C: Connecting...");
socket = new Socket(serverAddr, Server.SERVERPORT);
System.out.println("this is socket"+socket);
connected = true;
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
//showToast("");
Log.e(TAG, "C: Connected..." + socket);
} catch (Exception e) {
Log.e(TAG, "C: Error", e);
connected = false;
}
}
}
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
if(msg.arg1 == 1)
Toast.makeText(getApplicationContext(),"Connected...", Toast.LENGTH_LONG).show();
}
};
#Override
protected void onDestroy() {
if (socket != null) try {
socket.close();
Log.e(TAG, "C: Socket Closed.");
} catch (IOException e) {
e.printStackTrace();
} finally
{
try
{
socket.close();
}
catch(Exception e){}
}
super.onDestroy();
}
protected class ClientResponseTask extends AsyncTask<Void,Void,Void> {
String msg;
ClientResponseTask(String msg){
this.msg=msg;
}
#Override
protected Void doInBackground(Void... params) {
if (connected) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(msg);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
Log.e(TAG, "Error", e);
}
}
else {
connectsClient();
}
return null;
}
}
}
Please help me to find a solution.
I'm trying for sometime now and I cant figure it out why this is not working.
CLIENT:
public class MainActivity extends AppCompatActivity {
private Socket socket;
public static final int PORT = 6000;
public static final String server_IP = "192.168.2.30";
public String mensagem = null;
public String mensagem_final = null;
Button btn_conetar;
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_conetar = (Button) findViewById(R.id.btn_conetar);
txt = (TextView) findViewById(R.id.txt);
Thread t = new Thread() {
public void run() {
try {
while(!isInterrupted())
{
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
txt.setText(mensagem_final);
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
}
public void onClick(View view)
{
new Thread((new ClientThread())).start();
//Intent i = new Intent(MainActivity.this,Main2Activity.class);
// startActivity(i);
}
//Thread que inicia o socket
class ClientThread implements Runnable
{
#Override
public void run() {
try
{
InetAddress serveradress = InetAddress.getByName(server_IP);
Log.e("TCP","A conetar...");
socket = new Socket(serveradress,PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while((mensagem = in.readLine()) != null)
{
mensagem_final += mensagem;
}
if(in.readLine() == null)
{
Log.e("TCP","Nao tem mensagens");
}
Log.e("MSG",mensagem);
socket.close();
}
catch (UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Server:
Servidor servidor = new Servidor();
servidor.serverthread();
class Servidor
{
public void serverthread()
{
Thread serverthread = new Thread(server);
serverthread.Start();
}
public void server()
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
TcpListener tcplistener = new TcpListener(IPAddress.Any, 6000);
tcplistener.Start();
TcpClient tcpclient = tcplistener.AcceptTcpClient();
byte[] data = new byte[1024];
NetworkStream ns = tcpclient.GetStream();
string welcome = "Ola";
data = Encoding.ASCII.GetBytes(welcome);
ns.Write(data, 0, data.Length);
}
}
Any idea why I cant receive the string "Ola" in my android application? It doesnt give me any error, it just doesnt do anything.
My internet's default adress is 192.168.2.1.
Good links are also welcome.
I'm working on an android Quiz app with connection to a server over a socket. On the client side (Android device) I check in a while loop the answers which are given by a server (Java server). The connection and the receiving of the answer all goes good. The problem is that in my class to check for answers there's a bug. To give more information I will include a part of the code here:
public void startClient(){
checkValue = new Thread(new Runnable(){
#Override
public void run() {
try
{
final int PORT = 4444;
final String HOST = "192.168.1.118";
Socket SOCK = new Socket(HOST, PORT);
Log.e("success", "You connected to: " + HOST);
quizClient = new QuizClient(SOCK);
//Send the groupname to the list
PrintWriter OUT = new PrintWriter(SOCK.getOutputStream());
OUT.println(groupName);
OUT.flush();
Thread X = new Thread(quizClient);
X.start();
connected = true;
}
catch(Exception X)
{
Log.e("connection error", "Error: ", X);
}
}
});
checkValue.start();
}
public void testvalue(){
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
while(true){
if(message != null && !message.matches("")){
Thread.sleep(1000);
Log.e("receive", message);
buffer = message;
message = "";
Message msg = new Message();
String textTochange = buffer;
msg.obj = textTochange;
mHandler.sendMessage(msg);
Thread.sleep(3000);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String text = (String)msg.obj;
//call setText here
//String[] myStringArray = new String[];
value.clear();
String[] items = text.split(";");
for (String item : items)
{
value.add(item);
Log.e("message", item);
//System.out.println("item = " + item);
}
if(value.get(0).equals("1")){
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
question.setText("");
question.setText(value.get(2));
rad1.setText(value.get(3));
rad2.setText(value.get(4));
rad3.setText(value.get(5));
rad4.setText(value.get(6));
questionGroup.setVisibility(View.VISIBLE);
sendAnswer.setVisibility(View.VISIBLE);
} else if (value.get(0).equals("2")){
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
question.setText("");
question.setText(value.get(2));
answer.setVisibility(View.VISIBLE);
sendAnswer.setVisibility(View.VISIBLE);
} else
{
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
question.setText(text);
}
}
};
#Override
protected void onStop()
{
if (connected == true){
try {
quizClient.DISCONNECT();
} catch (IOException e) {
e.printStackTrace();
}
}
if(checkValue != null)
{
checkValue.interrupt();
}
super.onStop();
closeApplication();
}
So I make a new instance of this class (where I actually check the incoming stream of data)
public class QuizClient implements Runnable {
//Globals
Socket SOCK;
Scanner INPUT;
Scanner SEND = new Scanner(System.in);
PrintWriter OUT;
public QuizClient(Socket X)
{
this.SOCK = X;
}
public void run()
{
try
{
try
{
INPUT = new Scanner(SOCK.getInputStream());
OUT = new PrintWriter(SOCK.getOutputStream());
OUT.flush();
CheckStream();
}
finally
{
SOCK.close();
}
}
catch(Exception X)
{
Log.e("error", "error: ", X);
}
}
public void DISCONNECT() throws IOException
{
OUT.println("DISCONNECT");
OUT.flush();
SOCK.close();
}
public void CheckStream()
{
while(true)
{
RECEIVE();
}
}
public void RECEIVE()
{
if(INPUT.hasNext())
{
String MESSAGE = INPUT.nextLine();
if(MESSAGE.contains("#?!"))
{
}
else
{
QuizActivity.message = MESSAGE;
Log.e("test", MESSAGE);
}
}
}
public void SEND(String X)
{
OUT.println(X);
OUT.flush();
}
}
So the bug persist I think in the following class:
public void testvalue(){
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
while(true){
if(message != null && !message.matches("")){
Thread.sleep(1000);
Log.e("receive", message);
buffer = message;
message = "";
What I do here is make a thread and check if the "message" is not equals at null. The message come from the other class:
public void RECEIVE()
{
if(INPUT.hasNext())
{
String MESSAGE = INPUT.nextLine();
if(MESSAGE.contains("#?!"))
{
}
else
{
QuizActivity.message = MESSAGE;
Now most of the time this works good but there are 2 problems. When I go out of the page it disconnect from the server (works) I go back on the page and connect again to the server but this time I don't get any values on the screen (receiving is okj but for one of the other reason it does not go good in my handler). Also get an indexoutofboundexception after a time:
question.setText(value.get(2));
A second problem occurs some time while the program runs. There are moments that I also don't get a value on my interface while it correctly receive the input.
So my guess is that my solution of the thread to read in the values is not the best way to handle it. So now I ask to people with more experience what I can do to make this work without major problems? You need to know the connection works and I get the value in my QuizClient class. So the problem need to be in my main class.
My oncreate class:
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
selectgroep = (Spinner) findViewById(R.id.groepen);
questionGroup = (RadioGroup) findViewById(R.id.QuestionGroup);
sendAnswer = (Button) findViewById(R.id.sendAnswer);
rad1 = (RadioButton) findViewById(R.id.radio0);
rad2 = (RadioButton) findViewById(R.id.radio1);
rad3 = (RadioButton) findViewById(R.id.radio2);
rad4 = (RadioButton) findViewById(R.id.radio3);
answer = (EditText) findViewById(R.id.textanswer);
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
try {
connect();
} catch (InterruptedException e) {
e.printStackTrace();
}
//Code na het drukken op de knop
startserver = (Button) findViewById(R.id.startserver);
startserver.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startClient();
getID();
testvalue();
}
});
sendAnswer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Stuur antwoord door en sluit alles af
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
answer.setText("");
rad1.setChecked(true);
rad1.setText("");
rad2.setText("");
rad3.setText("");
rad4.setText("");
question.setText("Wachten op server ... ");
}
});
}
Thank you in advance,
Thomas Thooft
I am trying to receive images over a network, I set up a server as follows
public class IServerActivity extends Activity {
ServerSocket ss = null;
Bitmap bp ;
Thread myCommsThread = null;
protected static final int MSG_ID = 0x1337;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//TextView tv = (TextView) findViewById(R.id.TextView01);
this.myCommsThread = new Thread(new CommsThread());
this.myCommsThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Handler myUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ID:
ImageView iv = (ImageView) findViewById(R.id.imageView01);
iv.setImageBitmap(bp);;
break;
default:
break;
}
super.handleMessage(msg);
}
};
class CommsThread implements Runnable {
public void run() {
Socket s = null;
try {
ss = new ServerSocket(SERVERPORT );
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
Message m = new Message();
m.what = MSG_ID;
try {
if (s == null)
s = ss.accept();
bp= BitmapFactory.decodeStream(s.getInputStream());
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
But it shows an error at runtime
java.lang.NullPointerException
E/AndroidRuntime(3047):atExample.IServer.IServerActivity$CommsThread.run(IServerActivity.java:68)
It shows null pointer exception at s=ss.accept(); line.
please help I don't know what is going wrong.
If you are getting a null pointer exception at that line, it can only mean that the earlier:
ss = new ServerSocket(SERVERPORT );
statement did not return normally. That is the only plausible way that ss could be null.
(Actually, there is one other possible explanation. Since the ss variable is package private and not final, some other class in the same package could reach in and assign null to it. But I wouldn't think that was plausible. Why would anyone write code to do that?)