android - 将参数传递给Asynctask

时间:2014-02-23 06:36:47

标签: android android-asynctask fileinputstream

我正在使用AsyncTask将文件发送到服务器.Asynctask是一个不在MainActivity内部的不同类文件。我面临的问题是当我在MainActivity类中编写AsyncTask时。一切都很好。但是当我通过从MainActivity访问这个类来编写不同的java类并发送参数时,我得到了这些错误

02-23 01:06:46.995: I/System.out(1191): path is[Ljava.lang.String;@b1dccd40
02-23 01:06:47.125: E/Debug(1191): error: /[Ljava.lang.String;@b1dccd40: open failed: ENOENT (No such file or directory)
02-23 01:06:47.125: E/Debug(1191): java.io.FileNotFoundException: /[Ljava.lang.String;@b1dccd40: open failed: ENOENT (No such file or directory)

这是我的代码

public class ASync extends AsyncTask<String, Void, String>
{

    protected String doInBackground(String... path) {
         System.out.println("path is" + path);
         HttpURLConnection conn = null;
         DataOutputStream dos = null;
         DataInputStream inStream = null;
         String lineEnd = "\r\n";
         String twoHyphens = "--";
         String boundary =  "*****";
         int bytesRead, bytesAvailable, bufferSize;
         byte[] buffer;
         int maxBufferSize = 4*1024*1024;
         String responseFromServer = "";
         String urlString = "http://path";
         try
         {
   /*----- i think this line is causing an error */
       FileInputStream fileInputStream =  new FileInputStream(new File(path.toString()) );
       /**----/       
             // open a URL connection to the Servlet
          URL url = new URL(urlString);
          // Open a HTTP connection to the URL
          conn = (HttpURLConnection) url.openConnection();
          conn.setConnectTimeout(7000);
          // Allow Inputs
          conn.setDoInput(true);
          // Allow Outputs
          conn.setDoOutput(true);
          // Don't use a cached copy.
          conn.setUseCaches(false);
          // Use a post method.
          conn.setRequestMethod("POST");
          conn.setRequestProperty("Connection", "Keep-Alive");
          conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
          dos = new DataOutputStream( conn.getOutputStream() );
          dos.writeBytes(twoHyphens + boundary + lineEnd);
          dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + path + "\"" + lineEnd);
          dos.writeBytes(lineEnd);
          // create a buffer of maximum size
          bytesAvailable = fileInputStream.available();
          bufferSize = Math.min(bytesAvailable, maxBufferSize);
          buffer = new byte[bufferSize];
          // read file and write it into form...
          bytesRead = fileInputStream.read(buffer, 0, bufferSize);
          while (bytesRead > 0)
          {
           dos.write(buffer, 0, bufferSize);
           bytesAvailable = fileInputStream.available();
           bufferSize = Math.min(bytesAvailable, maxBufferSize);
           bytesRead = fileInputStream.read(buffer, 0, bufferSize);
          }
          // send multipart form data necesssary after file data...
          dos.writeBytes(lineEnd);
          dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
          // close streams
          Log.e("Debug","File is written");
          fileInputStream.close();
          dos.flush();
          dos.close();
         }
         catch (MalformedURLException ex)
         {
              Log.e("Debug", "error: " + ex.getMessage(), ex);
         }
         catch (IOException ioe)
         {
              Log.e("Debug", "error: " + ioe.getMessage(), ioe);
         }
         //------------------ read the SERVER RESPONSE
         try {
               inStream = new DataInputStream ( conn.getInputStream() );
               String str;

               while (( str = inStream.readLine()) != null)
               {
                    Log.e("Debug","Server Response "+str);
               }
               inStream.close();

         }
         catch (IOException ioex){
              Log.e("Debug", "error: " + ioex.getMessage(), ioex);
         }

        return null;
    }
    @Override
    protected void onPostExecute(String result) { 

    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }

    }

两个类之间的唯一区别(如果我在MainActivity中编写asyncTask类,一个,如果我编写单独的class.java文件)就是这一行

MainActivity中的AsyncTask :(此代码工作正常)

FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
//calling and passing parameter  like it.  
 new ASync().execute(selectedPath );

AsyncTask在单独的Java文件中(不工作)

   FileInputStream fileInputStream =  new FileInputStream(new File(path.toString()) );
     //calling and passing parameter  like it. 
       AudioSync sync = new AudioSync(); 
      sync.execute(getPath(selectedPath);

可能是参数传递问题。我是否以正确的方式使用FileInputStream并正确传递参数?请参阅代码段。谢谢 请告诉我如何通过在单独的类中声明来使代码工作。

2 个答案:

答案 0 :(得分:1)

将参数传递给AsyncTask的构造函数,如:

new ASync(selectedPath).execute(selectedPath);

并实施AsyncTask之类的:

public class ASync extends AsyncTask<String, Void, String> 
{
 String pathstr="";

 public ASync(String str){
  this.pathstr=str;
  }

}

答案 1 :(得分:0)

您的代码无效,因为它以错误的方式访问路径。

doInBackground(Params... params)使用varargs。所以基本上这个方法是接受一个数组,而不是一个变量。

如果您的方法是doInBackground(String... paths),则可以使用paths[0]获取第一个(有时是唯一的)路径。您可能需要事先检查paths是否为null