我可以传递字符串值给Asynctask,但我无法传递数组。
谁能告诉我,我该怎么做?
我想把这个数组传递给服务器(//printwwriter .write(messages);)…我怎样才能传递这个?
{
String[] trymessage = new String[3];
for(int x=0;x<3;x++)
{
trymessage[x]= Integer.toString(x);
}
new Asynctask1().execute(trymesssage);
}
public class Asynctask1 extends AsyncTask<String, Void, Void> {
private PrintWriter printwriter;
protected Void doInBackground(String... messages) {
final String IP_ADDRESS = "192.168.0.4";
final int DEST_PORT = 4444;
try {
Socket client = new Socket(IP_ADDRESS, DEST_PORT); // connect to server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsages); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close();
}
}
else{}
return null;
}
}
我想改变Asynctask1参数为String, void, String[]。
一个简单的解决方案就是创建一个新的构造函数:
public class Asynctask1 extends AsyncTask<Void, Void, Void> {
private String[] mMessages;
public Asynctask1(String[] messages) {
mMessages = messages;
}
// ...
}
尝试将AsyncTask的参数更改为String[], Void, Void.
第一个参数表示将发送给doInBackground()的参数类型。
第三个参数表示将发送给onPostExecute()的形参类型。
试试这个:
for(int x=0;x<3;x++)
{
trymessage[x]= Integer.toString(x);
}
new Asynctask1().execute(trymessage);
}
public class Asynctask1 extends AsyncTask<String[], Void, Void> {
private PrintWriter printwriter;
protected Void doInBackground(String[]... messages) {
final String IP_ADDRESS = "192.168.0.4";
final int DEST_PORT = 4444;
String[] messageList = messages[0];
if (messageList != null) {
try {
Socket client = new Socket(IP_ADDRESS, DEST_PORT); // connect to server
for (String message : messageList) {
System.out.println(message);
}
printwriter = new PrintWriter(client.getOutputStream(), true);
for (String message : messageList) {
printwriter.write(message); // write the message to output stream
}
printwriter.flush();
printwriter.close();
client.close();
} catch (Exception e) {
Log.e("Asynctask1@doInBackground", e.getMessage(), e);
}
}
return null;
}
}
另外,printwwriter的write()方法不允许你发送数组,你必须一个字符串一个字符串地发送