将数组传递给Asynctask

时间:2014-06-14 01:43:39

标签: android android-asynctask android-async-http

我可以将字符串值传递给Asynctask,但我无法传递数组。

任何人都可以通知我,我该怎么做?

我想把那个数组传递给服务器(//printwriter.write(messsages);)...我怎么能通过这个?

{
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 []。但没有有效的结果。

2 个答案:

答案 0 :(得分:0)

一个简单的解决方案就是创建一个新的构造函数:

public class Asynctask1 extends AsyncTask<Void, Void, Void> {
    private String[] mMessages;

    public Asynctask1(String[] messages) {
        mMessages = messages;
    }

    // ...
}                                      

答案 1 :(得分:0)

尝试将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;
    }
}

此外,PrintWriter的write()方法不允许您发送数组,您必须通过字符串发送它