2012-11-06 112 views
0

我使用FTPClient將文件(由用戶選擇)上傳到我的FTPServer。 而上傳代碼正在工作。 :) 但是,當我添加一個「上傳...」對話框的AsyncTask,它向用戶顯示它正在上傳。 它顯示在我的應用程序上傳對話框它的崩潰和隨後上傳對話框不會消失....如何在文件上傳到FTP服務器時使用AsyncTask

跟隨誤差從logcat的:

11-06 12:01:05.153: I/System.out(27121): ARGUMENT :: /storage/sdcard0/data-app/Z29sb2NrZXJpbmRlcGVuZGVudHZlcnNpb24 
11-06 12:01:05.188: D/dalvikvm(27121):  GC_CONCURRENT freed 107K, 9% free 12896K/14151K, paused 1ms+1ms, total 13ms 
11-06 12:01:13.923: I/System.out(27121): status :: 211-Status of 'ProFTPD' 

11-06 12:01:13.923: I/System.out(27121): Connected from 109.164.221.167 (109.164.221.167) 

11-06 12:01:13.923: I/System.out(27121): Logged in as ftp031220 

11-06 12:01:13.923: I/System.out(27121): TYPE: BINARY, STRUcture: File, Mode: Stream 

11-06 12:01:13.923: I/System.out(27121): No data connection 

11-06 12:01:13.923: I/System.out(27121): 211 End of status 

11-06 12:01:25.988: W/System.err(27121): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 
11-06 12:01:25.988: W/System.err(27121): at android.os.Handler.<init>(Handler.java:121) 
11-06 12:01:25.988: W/System.err(27121): at android.app.Dialog.<init>(Dialog.java:107) 
11-06 12:01:25.988: W/System.err(27121): at android.app.AlertDialog.<init>(AlertDialog.java:114) 
11-06 12:01:25.993: W/System.err(27121): at android.app.AlertDialog$Builder.create(AlertDialog.java:913) 
11-06 12:01:25.993: W/System.err(27121): at android.app.AlertDialog$Builder.show(AlertDialog.java:931) 
11-06 12:01:25.993: W/System.err(27121): at com.mseiz.give.your.apps.upload.upload(upload.java:124) 
11-06 12:01:25.993: W/System.err(27121): at com.mseiz.give.your.apps.upload$DownloadFilesTask.doInBackground(upload.java:153) 
11-06 12:01:25.993: W/System.err(27121): at com.mseiz.give.your.apps.upload$DownloadFilesTask.doInBackground(upload.java:1) 
11-06 12:01:25.993: W/System.err(27121): at android.os.AsyncTask$2.call(AsyncTask.java:287) 
11-06 12:01:25.993: W/System.err(27121): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 
11-06 12:01:25.993: W/System.err(27121): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
11-06 12:01:25.993: W/System.err(27121): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
11-06 12:01:25.993: W/System.err(27121): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
11-06 12:01:25.993: W/System.err(27121): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
11-06 12:01:25.993: W/System.err(27121): at java.lang.Thread.run(Thread.java:856) 

====在項目點擊。 .. ====

 @Override 
protected void onListItemClick(ListView l, View v, int position, long id) { 
    // TODO Auto-generated method stub 
    File file = new File(path.get(position)); 

    if (file.isDirectory()) 
    { 
    if(file.canRead()){ 
    getDir(path.get(position)); 
    }else{ 
    new AlertDialog.Builder(this) 
    .setIcon(R.drawable.ic_launcher) 
    .setTitle("[" + file.getName() + "] folder can't be read!") 
    .setPositiveButton("OK", null).show(); 
    } 
    }else { 
     new DownloadFilesTask().execute(path.get(position), file.getName()); 
    } 
} 

==== ====的AsyncTask

private class DownloadFilesTask extends AsyncTask<String, Integer, String> { 
    ProgressDialog dialog; 

    @Override 
    protected void onPreExecute() { 
     dialog = new ProgressDialog(upload.this); 
     dialog.setIcon(R.drawable.ic_launcher); 
     dialog.setTitle("Datei wird hochgeladen..."); 
     dialog.setMessage("Bitte warten..."); 
     dialog.setIndeterminate(true); 
     dialog.show(); 
    } 

    protected String doInBackground(String... args){ 
     System.out.println("ARGUMENT :: " + args[0]); 
     upload(args[0], args[1]); 
     return root; 

    } 

    protected void onPostExecute(Void unused) { 
     dialog.dismiss(); 
    } 
} 

====上傳功能====

public void upload(String upload, String datei) 
{ 
    try { 
     connectFTP("176.28.25.46"); 

    // Prepare file to be uploaded to FTP Server 
    File file = new File(upload); 
    FileInputStream ifile = new FileInputStream(file); 

    // Upload file to FTP Server 
    if(ftpClient.storeFile("/subdomains/giveyourapps/httpdocs/apps/"+datei, ifile)){ 
     new AlertDialog.Builder(this) 
     .setIcon(R.drawable.ic_launcher) 
     .setTitle("Datei wurde hochgeladen!") 
     .setPositiveButton("OK", null).show(); 
    } else { 
     new AlertDialog.Builder(this) 
     .setIcon(R.drawable.ic_launcher) 
     .setTitle("Fehler!") 
     .setPositiveButton("OK", null).show(); 
    } 
    ftpClient.disconnect(); 
}catch (Exception e) { 
    e.printStackTrace(); 
} 
} 
+0

什麼是在'upload.java'線124和153行? – dumbfingers

+0

line 124:.setPositiveButton(「OK」,null).show(); 第153行:upload(args [0],args [1]); –

回答

3

你不能顯示你的任務對話框。事實上,您不能在主(UI)線程之外執行任何UI更改。有關更多信息,請參見Processes and Threads reference

在你的Asynctask中,你應該使用publishProgress()onProgressUpdate()來執行UI更新。

閱讀AsyncTask reference瞭解更多詳情。

0

您無法在upload()中顯示對話框。該方法在doInBackground中調用,該方法在後臺線程中運行,而不在UI線程中運行。

檢查AsyncTask文檔,瞭解哪個線程以及哪個線程中允許和禁止哪些線程執行的AsyncTask方法的說明。

0

嘗試這個

public class loadVideo extends AsyncTask<Void, Integer, Void> { 

    int progress = 0; 
    long duration; 
    Notification notification; 
    NotificationManager notificationManager; 
    int id = 10; 
    long pk; 
    protected void onPreExecute() { 
     Toast.makeText(getApplicationContext(), 
       "Check upload Status in the Notification Bar", 1).show(); 
     Intent intent = new Intent(); 
     final PendingIntent pendingIntent = PendingIntent.getActivity(
       getApplicationContext(), 0, intent, 0); 
     notification = new Notification(R.drawable.ic_launcher, 
       "Uploading file", System.currentTimeMillis()); 
     notification.flags = notification.flags 
       | Notification.FLAG_ONGOING_EVENT; 
     notification.contentView = new RemoteViews(getApplicationContext() 
       .getPackageName(), R.layout.upload_progress_bar); 
     notification.contentIntent = pendingIntent; 
     notification.contentView.setImageViewResource(R.id.imageView1, 
       R.drawable.ic_launcher); 
     notification.contentView.setTextViewText(R.id.textView1, 
       "Uploading..."); 
     // notification.contentView.setProgressBar(R.id.progressBar1, 100, 
     // progress[0], false); 
     getApplicationContext(); 
     notificationManager = (NotificationManager) getApplicationContext() 
       .getSystemService(Context.NOTIFICATION_SERVICE); 
     notificationManager.notify(id, notification); 
     System.out.println("DOMAIN...+" + str_edt_domain_name 
       + "DOMAINPASSWORD..." + str_edt_username + "PASSOWRD" 
       + str_edt_password); 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     int count = 0; 
     FTPClient ObjFtpCon = new FTPClient(); 
     // Toast.makeText(con, "FTPasync doInBackground() is called" 
     // ,Toast.LENGTH_SHORT).show(); 
     try { 
      runOnUiThread(new Runnable() { 
       public void run() { 
        System.out.println("man 0"); 
        // bar.setProgress(0); 
        // real_time.setText(0 + " secs"); 
        // test_avg.setText(0+ " kbps"); 
        // peak.setText(0+" kbps"); 
       } 
      }); 
      // updateUI(pp, R.drawable.pause); 
      // ObjFtpCon.connect("ftp.customhdclips.com"); 
      ObjFtpCon.connect("domainname"); 
      // updateUI(status, "Connecting"); 
      System.out.println("man connecting"); 

      // if (ObjFtpCon.login("[email protected]", "fstech123")) 
      // { 
      if (ObjFtpCon.login("username", "password")) { 
       // updateUI(status, "Connected"); 
       System.out.println("man CONNECTED"); 

       // toast("Connected to FTP Server : ftp.customhdclips.com"); 
       ObjFtpCon.enterLocalPassiveMode(); // important! 
       //ObjFtpCon.cwd("/");// to send the FTP CWD command to the 
            // server, receive the reply, and return 
            // the reply code. 

       // ObjFtpCon.connect("ftp."+map.get("url").toString()); 
       // updateUI(status, "Connecting"); 
       // 
       // ObjFtpCon.login(map.get("username").toString(), 
       // map.get("password").toString()); 
       // ObjFtpCon.enterLocalPassiveMode(); 
       // ObjFtpCon.cwd("/var/www/html/BevdogAnd"); 

       ObjFtpCon.setFileType(FTP.BINARY_FILE_TYPE); 

       final long started = System.currentTimeMillis(); 
       long sleepingTime = 0; 
       // String sourceFileUri 
       // =extStorageDirectory+"/zkfile"+filename; 
       File file = new File(path); 
       long fileSize = file.length(); 
       int sentBytes = 0; 
       InputStream inputStream = new FileInputStream(file); 

       System.out.println("Start uploading second file"); 
       OutputStream outputStream = ObjFtpCon 
         .storeFileStream("Meera Nandan at 60th Filmfare Awards 2013 _99_.jpg"); 
       byte[] bytesIn = new byte[512]; 
       int read = 0; 
       while ((read = inputStream.read(bytesIn)) != -1) { 
        //updateUI(status, "Uploading"); 
        System.out.println("man Uploading"); 

        outputStream.write(bytesIn, 0, read); 
        sentBytes += read; 
        final int progress = (int) ((sentBytes * 100)/fileSize); 
        final long speed = sentBytes; 

        duration = ((System.currentTimeMillis() - started) - sleepingTime)/1000; 
        runOnUiThread(new Runnable() { 
         public void run() { 

         // bar.setProgress(progress); 
          if (duration != 0) { 
           // test_avg.setText((((speed/
           // duration)*1000)*0.0078125) + " kbps"); 
    //         test_avg.setText((speed/duration)/1024 
//           + " kbps"); 
          System.out.println("MAN spped"+(speed/duration)/1024 
             + " kbps"+"and "+progress); 
           if (pk <= (speed/duration)/1024) { 
            pk = (speed/duration)/1024; 
           } 
           /* 
           * if (pk <= ((speed/
           * duration)*1000)*0.0078125) { pk = 
           * (long)(((speed/
           * duration)*1000)*0.0078125); } 
           */ 
           // peak.setText(pk + " kbps"); 

          } 
         } 
        }); 
       } 
       inputStream.close(); 
       outputStream.close(); 

       boolean completed = ObjFtpCon.completePendingCommand(); 
//     updateUI(status, "Completed"); 
       System.out.println("MAN completed"); 
       if (completed) { 

       } 

      } 

      /*-------------------------------------------------------------*/ 
      /* 
      * URL url = new URL(map.get("url").toString()); URLConnection 
      * conexion = url.openConnection(); conexion.connect(); 
      * updateUI(status, "Connected"); 
      * 
      * final int lenghtOfFile = conexion.getContentLength(); 
      * InputStream input = new 
      * BufferedInputStream(url.openStream()); OutputStream output = 
      * new FileOutputStream(
      * Environment.getExternalStorageDirectory() + File.separator + 
      * Info.getInfo(con).HTTP_DOWNLOAD_FILE_NAME); byte data[] = new 
      * byte[1024]; long total = 0; final long started = 
      * System.currentTimeMillis(); long sleepingTime= 0; 
      * System.out.println("started time --"+started); 
      * updateUI(status, "Downloading"); while ((count = 
      * input.read(data)) != -1) { while (sleep) { 
      * Thread.sleep(1000); sleepingTime +=1000; } total += count; 
      * final int progress = (int) ((total * 100)/lenghtOfFile); 
      * final long speed = total; duration = 
      * ((System.currentTimeMillis() - started)-sleepingTime)/1000; 
      * runOnUiThread(new Runnable() { public void run() { 
      * bar.setProgress(progress); 
      */ 

      /*-----------------------------------------------------------------------*/ 

      else { 
       System.out.println("password entered is incorrect"); 
       // Toast.makeText(con, 
       // "Username or/and password is incorrect", 
       // Toast.LENGTH_SHORT).show(); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
      // toast(e.getLocalizedMessage()); 
     } 

     try { 
      ObjFtpCon.logout(); 
      ObjFtpCon.disconnect(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      // toast(e.getLocalizedMessage()); 
     } 
     return null; 
    } 

    // @Override 
    // protected void onProgressUpdate(Integer... progress) { 
    // 
    // Intent intent = new Intent(); 
    // final PendingIntent pendingIntent = PendingIntent.getActivity(
    // getApplicationContext(), 0, intent, 0); 
    // notification = new Notification(R.drawable.ic_launcher, 
    // "Uploading file", System.currentTimeMillis()); 
    // notification.flags = notification.flags 
    // | Notification.FLAG_ONGOING_EVENT; 
    // notification.contentView = new RemoteViews(getApplicationContext() 
    // .getPackageName(), R.layout.upload_progress_bar); 
    // notification.contentIntent = pendingIntent; 
    // notification.contentView.setImageViewResource(R.id.imageView1, 
    // R.drawable.ic_launcher); 
    // notification.contentView.setTextViewText(R.id.textView1, 
    // "Uploading..."); 
    // notification.contentView.setProgressBar(R.id.progressBar1, 100, 
    // progress[0], false); 
    // getApplicationContext(); 
    // notificationManager = (NotificationManager) getApplicationContext() 
    // .getSystemService(Context.NOTIFICATION_SERVICE); 
    // notificationManager.notify(id, notification); 
    // } 

    protected void onPostExecute(Void result) { 
     System.out.println("status_string.." + status_string); 
     Notification notification = new Notification(); 
     Intent intent1 = new Intent(MainActivity.this, MainActivity.class); 
     final PendingIntent pendingIntent = PendingIntent.getActivity(
       getApplicationContext(), 0, intent1, 0); 
     int icon = R.drawable.ic_launcher; // icon from resources 
     CharSequence tickerText = "Video Uploaded Successfully"; // ticker-text 
     CharSequence contentTitle = getResources().getString(
       R.string.app_name); // expanded message 
     // title 
     CharSequence contentText = ""; // expanded 
     if (upload_result == true && status_string.equals("1")) { 

      contentText = "Video Uploaded Successfully"; 
      // message 
     } else { 
      contentText = "Video Uploaded Failed"; 

     } 
     long when = System.currentTimeMillis(); // notification time 
     Context context = getApplicationContext(); // application 
                 // Context 
     notification = new Notification(icon, tickerText, when); 
     notification.flags |= Notification.FLAG_AUTO_CANCEL; 
     notification.setLatestEventInfo(context, contentTitle, contentText, 
       pendingIntent); 
     String notificationService = Context.NOTIFICATION_SERVICE; 
     notificationManager = (NotificationManager) context 
       .getSystemService(notificationService); 
     notificationManager.notify(id, notification); 
    } 
}