Application crashes while starting the new thread - java

I have a thread class when I start the thread and create the instance of thread class in the main class my app get crash. My main activity code for creating the thread is:
broadcast broadcastobject=new broadcast(messages);
broadcastobject.start();
My thread class is :
public class broadcast extends Thread {
private DatagramSocket socket;
String str;
private static final int TIMEOUT_MS = 10;
WifiManager mWifi;
EditText et;
DatagramPacket packet;
Button bt;
private static final int SERVERPORT = 11111;
private static final String SERVER_IP = "192.168.1.255";
public broadcast(String to) {
// TODO Auto-generated constructor stub
str = to;
}
/*
private InetAddress getBroadcastAddress() throws IOException {
DhcpInfo dhcp = mWifi.getDhcpInfo();
if (dhcp == null) {
//Log.d(TAG, "Could not get dhcp info");
return null;
}
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
*/
#Override
public void run() {
try {
socket = new DatagramSocket(SERVERPORT);
socket.setBroadcast(true);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// socket.setSoTimeout(TIMEOUT_MS);
InetAddress serverAddr = null;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
packet = new DatagramPacket(str.getBytes(), str.length(),serverAddr,SERVERPORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My log cat error is:
09-01 08:23:47.949: D/gralloc_goldfish(1720): Emulator without GPU emulation detected.
09-01 08:24:01.941: W/System.err(1720): java.net.SocketException: socket failed: EACCES (Permission denied)
09-01 08:24:01.941: W/System.err(1720): at libcore.io.IoBridge.socket(IoBridge.java:573)
09-01 08:24:01.979: W/System.err(1720): at java.net.PlainDatagramSocketImpl.create(PlainDatagramSocketImpl.java:91)
09-01 08:24:01.979: W/System.err(1720): at java.net.DatagramSocket.createSocket(DatagramSocket.java:131)
09-01 08:24:01.979: W/System.err(1720): at java.net.DatagramSocket.<init>(DatagramSocket.java:78)
09-01 08:24:01.989: W/System.err(1720): at soft.b.peopleassist.broadcast.run(broadcast.java:65)
09-01 08:24:01.989: W/System.err(1720): Caused by: libcore.io.ErrnoException: socket failed: EACCES (Permission denied)
09-01 08:24:01.999: W/System.err(1720): at libcore.io.Posix.socket(Native Method)
09-01 08:24:01.999: W/System.err(1720): at libcore.io.BlockGuardOs.socket(BlockGuardOs.java:169)
09-01 08:24:01.999: W/System.err(1720): at libcore.io.IoBridge.socket(IoBridge.java:558)
09-01 08:24:02.009: W/System.err(1720): ... 4 more
09-01 08:24:02.149: W/dalvikvm(1720): threadid=11: thread exiting with uncaught exception (group=0x409961f8)
09-01 08:24:02.149: E/AndroidRuntime(1720): FATAL EXCEPTION: Thread-114
09-01 08:24:02.149: E/AndroidRuntime(1720): java.lang.NullPointerException
09-01 08:24:02.149: E/AndroidRuntime(1720): at soft.b.peopleassist.broadcast.run(broadcast.java:92)
09-01 08:24:03.329: W/IInputConnectionWrapper(1720): showStatusIcon on inactive InputConnection

The thread is not the issue, the real issue is the EACCES (Permission denied), add this permission to your manifest file
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Related

KitKat Connection from URL get NullPointerException in AsyncTask

i'm new in java and android programming but i accepted a challenge launched by a friend and now i have to work hard.
I finally managed to have this type of activity working with AsyncTask but it seems to work well on all android but not on 4.4.2 KitKat.
The problem seems to be on url.openConnection and i tried many times to change the way in wich i do it but i haven't had positive results...
I have only to read file from an URL
This is my class code:
public class MenuActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
new HttpTask().execute();
}
public final class HttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
private HttpClient mHc = new DefaultHttpClient();
#Override
protected String doInBackground(String... params) {
publishProgress(true);
InputStream inputstream = null;
URL url = null;
try {
url = new URL("http://somesite/prova.txt");
} catch (MalformedURLException e) {
e.printStackTrace();
}
assert url != null;
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputstream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
ByteArrayOutputStream bytearryoutputstream = new ByteArrayOutputStream();
int i;
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytearryoutputstream.toString();
}
#Override
protected void onProgressUpdate(Boolean... progress) {
}
#Override
protected void onPostExecute(String result) {
StringBuilder nuovafrase=new StringBuilder("");
String[] frasone=result.split("\n");
ListView listView = (ListView)findViewById(R.id.listViewDemo);
ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.rowmenu, R.id.textViewList, frasone);
listView.setAdapter(arrayAdapter);
}
}
}
And this is the Logcat...
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.Posix.getaddrinfo(Native Method)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 18 more
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 21 more
03-11 17:49:37.963 1277-1294/com.example.appsb.app W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0xa4d69b20)
03-11 17:49:37.963 1277-1294/com.example.appsb.app E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.appsb.app, PID: 1277
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:74)
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:33)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
              at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
             at java.lang.Thread.run(Thread.java:841)
There is a Caused by: java.lang.NullPointerException but i cannot understand why...
Thanks
It could be caused by the inputstream being null. inputstream will only be initialized if the response code is OK. So you need to check what response code is being returned. If it is not causing the error, I'd still add some code for if the response code is not OK. You don't want your app to crash if it can't connect. You should at least display a helpful error message
Example:
else{
showErrorMsg();
return null;
}
Catch FileNotFoundException when trying inputstream.read();
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (FileNotFoundException e) {
Log.e("MyTag","Handling empty page...");
} catch (IOException e) {
Log.e("MyTag",e.toString());
}

Transfer file using Sockets Server/Client

Hi there I have 2 classes in order to push a file into an android device.
My Server CLass:
public class FileServer {
public static void main (String [] args ) throws IOException {
// create socket
ServerSocket servsock = new ServerSocket(13267);
while (true) {
System.out.println("Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// sendfile
File myFile = new File ("C:\\Users\\Petrica\\Desktop\\zzz.txt");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
}
And my Client Class:
public class TCPClient extends AsyncTask{
#Override
protected Object doInBackground(Object... params) {
int filesize=6022386; // filesize temporary hardcoded
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
Socket sock = null;
try {
sock = new Socket("127.0.0.1",13267);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Connecting...");
// receive file
try {
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("/mnt/sdcard/zzz.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
// thanks to A. Cádiz for the bug fix
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
sock.close();
// TODO Auto-generated method stub
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
I get an error
09-09 15:52:39.261: E/AndroidRuntime(802): FATAL EXCEPTION: AsyncTask #1
09-09 15:52:39.261: E/AndroidRuntime(802): java.lang.RuntimeException: An error occured while executing doInBackground()
09-09 15:52:39.261: E/AndroidRuntime(802): at android.os.AsyncTask$3.done(AsyncTask.java:299)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
09-09 15:52:39.261: E/AndroidRuntime(802): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.lang.Thread.run(Thread.java:841)
09-09 15:52:39.261: E/AndroidRuntime(802): Caused by: java.lang.NullPointerException
09-09 15:52:39.261: E/AndroidRuntime(802): at com.aaaaaa.TCPClient.doInBackground(TCPClient.java:33)
09-09 15:52:39.261: E/AndroidRuntime(802): at com.aaaaaa.TCPClient.doInBackground(TCPClient.java:1)
09-09 15:52:39.261: E/AndroidRuntime(802): at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-09 15:52:39.261: E/AndroidRuntime(802): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-09 15:52:39.261: E/AndroidRuntime(802): ... 4 more
MainActivity:
public class MainActivity extends Activity {
TCPClient tcpc;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.send_button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tcpc.execute();
}
});
}
}
Does anyone have an idea what should I do ??? In the future i would like to send 2 files :D .Thanks in advice .
You're really expected to be able to sort out your own NullPointerExceptions: at least I expect it, but when you get past that, your copy code is wrong. You are presently ignoring the count returned by read() and assuming it fills the buffer. It isn't guaranteed to do that. See the Javadoc.
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Use this at both ends, with any buffer size > 0, typically 8192.
I don't think your Socket is connecting, but its hard to tell. IN your log output, it says NullPointerException caused by doInBackground() line 33. You should check line 33 in your editor, and better yet, show us in your post which line is 33. I kind of have a feeling that you call Socket sock = null;, then you try and instantiate a new Socket in a try block, but that fails, so sock still == null, then you call a method on sock, and boom, NPE.
If you are running the Server on a computer, and the AsyncTask on an Android device, you won't be able to try and connect to localhost (127.0.0.1). You should instead try to connect to the internal network ip of your computer (something like 192.168.1.XXX), assuming both devices are on WiFi. If you are running an android emulator, then 127.0.0.1 refers back to the emulated device, and all emulator sessions run on an emulated router that you will have to configure for port forwarding before you can refer to the development machine, see here-->http://developer.android.com/tools/devices/emulator.html#emulatornetworking
As Andras Balazs Lajtha says, it looks like TCPClient isn't ever initialized/created during onCreate(), it is only declared. Since your logcat output shows errors from TCPClient though, I assume you have that code actually running.
In general, when you post a log output that refers to problems with a specific line of code, you should start there, and when you post, tell us or show us which line that is. And of course, if line 33 isn't related to a null Socket object, then I haven't been much help at all :)

my application crashes when i start new thread [duplicate]

This question already has an answer here:
Application crashes while starting the new thread
(1 answer)
Closed 9 years ago.
I have a class where I have implemented runnable and I start the thread in one of the function of this class, and I call this function from the main activity,I create the object of this class and call the method of thread class.My main activity code from where I call this class method is:
broadcast broadcastobject.threadfunc(messages);
My class where I create threads is:
public class broadcast {
private DatagramSocket socket;
String str;
private static final int TIMEOUT_MS = 10;
WifiManager mWifi;
EditText et;
DatagramPacket packet;
Button bt;
private static final int SERVERPORT = 11111;
private static final String SERVER_IP = "192.168.1.255";
public void threadfunc(String message){
str=message;
new Thread(new ClientThread()).start();
}
/*
private InetAddress getBroadcastAddress() throws IOException {
DhcpInfo dhcp = mWifi.getDhcpInfo();
if (dhcp == null) {
//Log.d(TAG, "Could not get dhcp info");
return null;
}
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
*/
class ClientThread implements Runnable {
#Override
public void run() {
try {
socket = new DatagramSocket(SERVERPORT);
socket.setBroadcast(true);
// socket.setSoTimeout(TIMEOUT_MS);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InetAddress serverAddr = null;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
packet = new DatagramPacket(str.getBytes(), str.length(),serverAddr,SERVERPORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My log cat is:
08-31 21:55:56.277: D/gralloc_goldfish(1669): Emulator without GPU emulation detected.
08-31 21:56:02.467: D/AndroidRuntime(1669): Shutting down VM
08-31 21:56:02.467: W/dalvikvm(1669): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
08-31 21:56:02.517: E/AndroidRuntime(1669): FATAL EXCEPTION: main
08-31 21:56:02.517: E/AndroidRuntime(1669): java.lang.NullPointerException
08-31 21:56:02.517: E/AndroidRuntime(1669): at soft.b.peopleassist.Send$1.onClick(Send.java:113)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.view.View.performClick(View.java:3480)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.view.View$PerformClick.run(View.java:13983)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Handler.handleCallback(Handler.java:605)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Handler.dispatchMessage(Handler.java:92)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Looper.loop(Looper.java:137)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.app.ActivityThread.main(ActivityThread.java:4340)
08-31 21:56:02.517: E/AndroidRuntime(1669): at java.lang.reflect.Method.invokeNative(Native Method)
08-31 21:56:02.517: E/AndroidRuntime(1669): at java.lang.reflect.Method.invoke(Method.java:511)
08-31 21:56:02.517: E/AndroidRuntime(1669): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-31 21:56:02.517: E/AndroidRuntime(1669): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-31 21:56:02.517: E/AndroidRuntime(1669): at dalvik.system.NativeStart.main(Native Method)
This simply means that the emulator you are using does not have GPU emulation enabled. In Android SDK Tools R15 you can enable GPU emulation.You need to create a new emulator virtual device and set GPU emulation to true in Hardware properties.

How to make a UDP connection in android

I'm trying to make a connection between my galaxy tab and my laptop. So I'm trying to run server activity on my laptop and client activity on my tab, but it doesn't work. Here is the server and client code. Where is the mistake?
SERVER:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txt = (TextView)findViewById(R.id.textView1);
int port = 12345;
byte [] message = new byte [1500];
DatagramPacket p = new DatagramPacket (message,message.length);
try {
InetAddress serveraddr = InetAddress.getByName("192.168.1.116");
DatagramSocket s = new DatagramSocket (port,serveraddr);
while (true){
s.receive(p);
String text = new String (message,0,p.getLength());
txt.setText(text);
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
CLIENT:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edt = (EditText)findViewById(R.id.editText1);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
String msg = edt.getText().toString();
int port = 12345;
try {
DatagramSocket s = new DatagramSocket();
InetAddress local = InetAddress.getByName("192.168.1.116");
int msg_lenght = msg.length();
byte []message = msg.getBytes();
DatagramPacket p = new DatagramPacket(message,msg_lenght,local,port);
s.send(p);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
Here is the log:
09-17 23:49:55.190: D/dalvikvm(5892): Late-enabling CheckJNI 09-17
23:49:55.690: D/CLIPBOARD(5892): Hide Clipboard dialog at Starting
input: finished by someone else... ! 09-17 23:49:59.590:
D/AndroidRuntime(5892): Shutting down VM 09-17 23:49:59.590:
W/dalvikvm(5892): threadid=1: thread exiting with uncaught exception
(group=0x40c4f1f8) 09-17 23:49:59.590: E/AndroidRuntime(5892): FATAL
EXCEPTION: main 09-17 23:49:59.590: E/AndroidRuntime(5892):
android.os.NetworkOnMainThreadException 09-17 23:49:59.590:
E/AndroidRuntime(5892): at
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
09-17 23:49:59.590: E/AndroidRuntime(5892): at
libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
libcore.io.IoBridge.sendto(IoBridge.java:463) 09-17 23:49:59.590:
E/AndroidRuntime(5892): at
java.net.PlainDatagramSocketImpl.send(PlainDatagramSocketImpl.java:182)
09-17 23:49:59.590: E/AndroidRuntime(5892): at
java.net.DatagramSocket.send(DatagramSocket.java:307) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
com.example.udpclient.MainActivity$1.onClick(MainActivity.java:36)
09-17 23:49:59.590: E/AndroidRuntime(5892): at
android.view.View.performClick(View.java:3620) 09-17 23:49:59.590:
E/AndroidRuntime(5892): at
android.view.View$PerformClick.run(View.java:14322) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
android.os.Handler.handleCallback(Handler.java:605) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
android.os.Handler.dispatchMessage(Handler.java:92) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
android.os.Looper.loop(Looper.java:137) 09-17 23:49:59.590:
E/AndroidRuntime(5892): at
android.app.ActivityThread.main(ActivityThread.java:4507) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
java.lang.reflect.Method.invokeNative(Native Method) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
java.lang.reflect.Method.invoke(Method.java:511) 09-17 23:49:59.590:
E/AndroidRuntime(5892): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:978)
09-17 23:49:59.590: E/AndroidRuntime(5892): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
dalvik.system.NativeStart.main(Native Method) 09-17 23:50:34.320:
I/Process(5892): Sending signal. PID: 5892 SIG: 9
09-17 23:49:59.590: E/AndroidRuntime(5892): android.os.NetworkOnMainThreadException
09-17 23:49:59.590: E/AndroidRuntime(5892): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
09-17 23:49:59.590: E/AndroidRuntime(5892): at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175)
You shouldn't do network or time intensiv operations in ui thread
See also:
Android: NoClassDefFoundError for some app users or
android developers information
Checkout:
activity.runOnUi
You have an infinite loop in onCreate of the Server. You shouldn't! Create a thread for polling the socket.
you cannot send udp packets on ui thread, so a new seperate thread must be created.
Just a quick solution...
create a udpOutputData string:
String udpOutputData;
create a new thread in your code:
//-----UDP send thread
Thread udpSendThread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
Thread.sleep(100);
}
catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (sendUdp == true) {
try {
// get server name
InetAddress serverAddr = InetAddress.getByName(outputIP);
Log.d("UDP", "C: Connecting...");
// create new UDP socket
DatagramSocket socket = new DatagramSocket();
// prepare data to be sent
byte[] buf = udpOutputData.getBytes();
// create a UDP packet with data and its destination ip & port
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, broadcastPort);
Log.d("UDP", "C: Sending: '" + new String(buf) + "'");
// send the UDP packet
socket.send(packet);
socket.close();
Log.d("UDP", "C: Sent.");
Log.d("UDP", "C: Done.");
}
catch (Exception e) {
Log.e("UDP", "C: Error", e);
}
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendUdp = false;
}
}
}
});
create a method to call everytime you want to send some udp data:
public void sendUdp(String udpMsg) {
udpOutputData = udpMsg;
sendUdp = true;
}
call the method and pass a string for the output data everytime you want to send a udp packet:
String s = "hello from app";
sendUdp(s);
Have 2 problems with your code
Work with Network on Main thread (UI Thread)
09-17 23:49:59.590: E/AndroidRuntime(5892): FATAL EXCEPTION: main
09-17 23:49:59.590: E/AndroidRuntime(5892):
android.os.NetworkOnMainThreadException
Loop while(true) on the Main thread:
while(true) {
s.receive(p);
String text = new String (message,0,p.getLength());
txt.setText(text);
}

connecting clients to server with emulator on different computers

I am writing an application that communicates using sockets. I have a server running on one android emulator on a computer, then i have 2 other clients running on android emulators on 2 other computers. I am trying to get the 2 clients to connect to the server.
This works when i run the server and clients on the same computer, but when i attempt to do this on the same wifi network and on separate computers it gives me the following error. The client and server code is posted below. A lot is stripped out just to show the important stuff. Also, after the server starts i telnet into the server and run these commands redir add tcp:5000:6000 (i have also tried without doing the redir but it still says the same thing). Then i start the clients and get the error. Thanks for the help!
Both the 5000 port and 6000 port are open on my router. And i have windows firewall disabled on the computer hosting the server.
11-27 18:54:02.274: W/ActivityManager(60): Activity idle timeout for HistoryRecord{44cf0a30 school.cpe434.ClassAidClient/school.cpe434.ClassAid.ClassAidClient4Activity}
11-27 18:57:02.424: W/System.err(205): java.net.SocketException: The operation timed out
11-27 18:57:02.454: W/System.err(205): at org.apache.harmony.luni.platform.OSNetworkSystem.connectSocketImpl(Native Method)
11-27 18:57:02.454: W/System.err(205): at org.apache.harmony.luni.platform.OSNetworkSystem.connect(OSNetworkSystem.java:114)
11-27 18:57:02.465: W/System.err(205): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:245)
11-27 18:57:02.465: W/System.err(205): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:220)
11-27 18:57:02.465: W/System.err(205): at java.net.Socket.startupSocket(Socket.java:780)
11-27 18:57:02.465: W/System.err(205): at java.net.Socket.<init>(Socket.java:314)
11-27 18:57:02.465: W/System.err(205): at school.cpe434.ClassAid.ClassAidClient4Activity.onCreate(ClassAidClient4Activity.java:102)
11-27 18:57:02.474: W/System.err(205): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-27 18:57:02.474: W/System.err(205): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
11-27 18:57:02.474: W/System.err(205): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
11-27 18:57:02.474: W/System.err(205): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
11-27 18:57:02.474: W/System.err(205): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
11-27 18:57:02.474: W/System.err(205): at android.os.Handler.dispatchMessage(Handler.java:99)
11-27 18:57:02.474: W/System.err(205): at android.os.Looper.loop(Looper.java:123)
11-27 18:57:02.486: W/System.err(205): at android.app.ActivityThread.main(ActivityThread.java:4363)
11-27 18:57:02.486: W/System.err(205): at java.lang.reflect.Method.invokeNative(Native Method)
11-27 18:57:02.486: W/System.err(205): at java.lang.reflect.Method.invoke(Method.java:521)
11-27 18:57:02.486: W/System.err(205): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
11-27 18:57:02.486: W/System.err(205): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
11-27 18:57:02.486: W/System.err(205): at dalvik.system.NativeStart.main(Native Method)
The server code
public class ClassAidServer4Activity extends Activity {
ServerSocket ss = null;
String mClientMsg = "";
String mClientExtraMsg = "";
Thread myCommsThread = null;
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.textView1);
tv.setText("Nothing from client yet");
this.myCommsThread = new Thread(new CommsThread());
this.myCommsThread.start();
}
class CommsThread implements Runnable {
public void run() {
// Socket s = null;
try {
ss = new ServerSocket(SERVERPORT );
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(true) {
try {
Socket socket = ss.accept();
connectedDeviceCount++;
Thread lThread = new Thread(new ListeningThread(socket));
lThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class ListeningThread implements Runnable {
private Socket s = null;
public ListeningThread(Socket socket) {
// TODO Auto-generated constructor stub
this.s = socket;
}
#Override
public void run() {
// TODO Auto-generated method stub
while (!Thread.currentThread().isInterrupted()) {
Message m = new Message();
// m.what = QUESTION_ID;
try {
if (s == null)
s = ss.accept();
BufferedReader input = new BufferedReader(
new InputStreamReader(s.getInputStream()));
String st = null;
st = input.readLine();
String[] temp = parseReadMessage(st);
mClientMsg = temp[1];
if(temp.length > 2) {
mClientExtraMsg = temp[2];
}
m.what = Integer.parseInt(temp[0]);
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
The client code
public class ClassAidClient4Activity extends Activity {
//telnet localhost 5554
//redir add tcp:5000:6000
private Socket socket;
private String serverIpAddress = "192.168.1.102";
// if "redir add" is disabled this should be 6000
private static final int REDIRECTED_SERVERPORT = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
mQuestionAdapter.add("UnknownHostException");
e1.printStackTrace();
} catch (IOException e1) {
mQuestionAdapter.add("IOException");
e1.printStackTrace();
}
}
}
I figured it out. I needed to create a proxy. I used this SO post as a reference. And heavily modified this code to work for multiple connections. It is working now. HOORAY!

Categories