问题描述
我正在尝试编写代码以从异步任务的输出中的一个类填充数组。
现在,代码为我提供了null引用。
数组类:
public class ClientDiscovery {
public static ArrayList<InetAddress> clientes;
public static void addclient(InetAddress address)
{
clientes.add(address);
}
public static void removeclient(InetAddress address)
{
clientes.remove(address);
}
public static ArrayList<InetAddress>getclient()
{
Set<InetAddress> noduplicate = new HashSet<>();
if (!(clientes ==null)) {
noduplicate.addAll(clientes);
clientes.clear();
clientes.addAll(noduplicate);
}
return clientes;
}
}
异步任务填充数组
public class RequestDiscoveryAsyncTask extends AsyncTask<Void,Void,Void>{
Context context;
public RequestDiscoveryAsyncTask(Context context) {
this.context = context.getApplicationContext();
}
@Override
protected Void doInBackground(Void...voids) {
///HERE I INITIALIZE THE SOCKETS ****INTENTIONALLY OMITED TO EASY READING***
/*HERE I INTENT TO GET THE ACK BACK FROM THE CLIENTES "MY CUSTOM ACK"*/
while(!timeout) {
byte[] ready = new byte[5];
DatagramPacket pkgready = new DatagramPacket(ready, 0, 5);
socket.receive(pkgready);
if (new String(pkgready.getData()).contains("READY"))
ClientDiscovery.addclient(pkgready.getAddress());
}
}
return null;
}
}
为了便于阅读,省略了套接字初始化和捕获异常。
LOGCAT:
07-18 21:50:43.889 4327-5025/fr.xplod.focal E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
Caused by: java.lang.NullPointerException
at org.cyanogenmod.focal.ClientDiscovery.addclient(ClientDiscovery.java:16)
at org.cyanogenmod.focal.RequestDiscoveryAsyncTask.doInBackground(RequestDiscoveryAsyncTask.java:68)
at org.cyanogenmod.focal.RequestDiscoveryAsyncTask.doInBackground(RequestDiscoveryAsyncTask.java:23)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
atjava.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
1楼
仅创建对象,当前ArrayList对象不存在添加此行: public static ArrayList<InetAddress> clientes = new ArrayList<InetAddress>();