I have some code give here
public void doScan() {
Log.i(LOG_TAG, "Start scanning");
ExecutorService executor = Executors.newFixedThreadPool(NB_THREADS);
for(int dest=0; dest<255; dest++) {
String host = "192.168.5." + dest; //add net address instead of hardcoding
executor.execute(pingRunnable(host));
}
Log.i(LOG_TAG, "Waiting for executor to terminate...");
executor.shutdown();
try { executor.awaitTermination(10*1000, TimeUnit.MILLISECONDS); } catch (InterruptedException ignored) { }
Log.i(LOG_TAG, "Scan finished");
}
private Runnable pingRunnable(final String host) {
return new Runnable() {
public void run() {
Log.v(LOG_TAG, "Pinging " + host + "...");
try {
Socket s = null;
s = new Socket(InetAddress.getByName(host), ACES_PORT);
Log.v(LOG_TAG, "conn:"+s.toString());
if(s.isConnected()){
Log.v(LOG_TAG, "connected " + host);
foundDevicesArray.add(host);
}
} catch (UnknownHostException e) {
Log.e(LOG_TAG, "Not found", e);
} catch (IOException e) {
Log.e(LOG_TAG, "IO Error", e);
}
}
};
}
I am trying to save the host if it connects inside the thread.
I have a global (I’m new to android so I’m not sure if that is what it called) ArrayList that inside the thread I do ArrayList.add(host) and it crashes on me I’m not sure how to get a usual error message from the crash.
You need to initialize the variable as follows to give it a non null value:
Note however that arraylists are not thread safe so you should use a thread-safe collection instead, such as CopyOnWriteArrayList for example, in order to avoid concurrency issues.
Because that collection also implements the
Listinterface, you simply need to change the declaration and you can leave the rest of your code as it is:Finally, CopyOnWriteArrayList achieves thread safety by making copies of the underlying array each time it is modified. If your array is often modified but is not highly contended (you don’t have many threads trying to access it at exactly the same time), a synchronized list would possibly be a better choice from a memory usage perspective – you should try both and measure performance vs. memory usage to make an informed decision: