获得致命异常:使用 Async 类的 AsyncTask #1

Posted

技术标签:

【中文标题】获得致命异常:使用 Async 类的 AsyncTask #1【英文标题】:Getting FATAL exception: AsyncTask #1 on using Async class 【发布时间】:2015-11-16 19:21:05 【问题描述】:

我是安卓新手。我已经导入了一个项目,该项目从我的手机拍摄照片,并且应该将它上传到我笔记本电脑的本地主机上。两者都连接到同一个WiFi,它会一直运行,直到我拍照并点击上传,但是当我点击上传时,它崩溃了。这些是我在 log-cat 中遇到的错误。谁能帮我解决一下?

08-22 12:00:43.871: E/androidRuntime(2491): FATAL EXCEPTION: AsyncTask #1

08-22 12:00:43.871: E/AndroidRuntime(2491): java.lang.RuntimeException: An error occured while executing doInBackground()

08-22 12:00:43.871: E/AndroidRuntime(2491):     at android.os.AsyncTask$3.done(AsyncTask.java:278)

08-22 12:00:43.871: E/AndroidRuntime(2491):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)

08-22 12:00:43.871: E/AndroidRuntime(2491):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)

08-22 12:00:43.871: E/AndroidRuntime(2491):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)

08-22 12:00:43.871: E/AndroidRuntime(2491):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)

08-22 12:00:43.871: E/AndroidRuntime(2491):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)

08-22 12:00:43.871: E/AndroidRuntime(2491):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-22 12:00:43.871: E/AndroidRuntime(2491):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)

08-22 12:00:43.871: E/AndroidRuntime(2491):     at java.lang.Thread.run(Thread.java:856)

08-22 12:00:43.871: E/AndroidRuntime(2491): Caused by: java.lang.NoClassDefFoundError: info.androidhive.camerafileupload.AndroidMultiPartEntity

08-22 12:00:43.871: E/AndroidRuntime(2491):     at info.androidhive.camerafileupload.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:156)

08-22 12:00:43.871: E/AndroidRuntime(2491):     at info.androidhive.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:145)

08-22 12:00:43.871: E/AndroidRuntime(2491):     at info.androidhive.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:1)

08-22 12:00:43.871: E/AndroidRuntime(2491):     at android.os.AsyncTask$2.call(AsyncTask.java:264)

08-22 12:00:43.871: E/AndroidRuntime(2491):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

08-22 12:00:43.871: E/AndroidRuntime(2491):     ... 5 more

包信息.androidhive.camerafileupload;

   import  info.androidhive.camerafileupload.AndroidMultiPartEntity.ProgressListener;

  import java.io.File;
  import java.io.IOException;

  import org.apache.http.HttpEntity;
  import org.apache.http.HttpResponse;
  import org.apache.http.client.ClientProtocolException;
  import org.apache.http.client.HttpClient;
  import org.apache.http.client.methods.HttpPost;
  import org.apache.http.entity.mime.content.FileBody;
  import org.apache.http.entity.mime.content.StringBody;
  import org.apache.http.impl.client.DefaultHttpClient;
  import org.apache.http.util.EntityUtils;

  import android.app.Activity;
  import android.app.AlertDialog;
  import android.content.DialogInterface;
  import android.content.Intent;
  import android.graphics.Bitmap;
  import android.graphics.BitmapFactory;
  import android.graphics.Color;
  import android.graphics.drawable.ColorDrawable;
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.util.Log;
  import android.view.View;
  import android.widget.Button;
  import android.widget.ImageView;
  import android.widget.ProgressBar;
  import android.widget.TextView;
  import android.widget.Toast;
  import android.widget.VideoView;

     public class UploadActivity extends Activity 
      // LogCat tag
     private static final String TAG = MainActivity.class.getSimpleName();

     private ProgressBar progressBar;
     private String filePath = null;
     private TextView txtPercentage;
     private ImageView imgPreview;
     private VideoView vidPreview;
     private Button btnUpload;
      long totalSize = 0;

     @Override
     protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload);
    txtPercentage = (TextView) findViewById(R.id.txtPercentage);
    btnUpload = (Button) findViewById(R.id.btnUpload);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    imgPreview = (ImageView) findViewById(R.id.imgPreview);
    vidPreview = (VideoView) findViewById(R.id.videoPreview);

    // Changing action bar background color
    getActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor(getResources().getString(
                    R.color.action_bar))));

    // Receiving the data from previous activity
    Intent i = getIntent();

    // image or video path that is captured in previous activity
    filePath = i.getStringExtra("filePath");

    // boolean flag to identify the media type, image or video
    boolean isImage = i.getBooleanExtra("isImage", true);

    if (filePath != null) 
        // Displaying the image or video on the screen
        previewMedia(isImage);
     else 
        Toast.makeText(getApplicationContext(),
                "Sorry, file path is missing!", Toast.LENGTH_LONG).show();
    

       btnUpload.setOnClickListener(new View.OnClickListener() 

        @Override
        public void onClick(View v) 
            // uploading the file to server
            new UploadFileToServer().execute();
        
    );

      

          /**
         * Displaying captured image/video on the screen
            * */
        private void previewMedia(boolean isImage) 
        // Checking whether captured media is image or video
        if (isImage) 
        imgPreview.setVisibility(View.VISIBLE);
        vidPreview.setVisibility(View.GONE);
        // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // down sizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;

        final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

        imgPreview.setImageBitmap(bitmap);
        else 
        imgPreview.setVisibility(View.GONE);
        vidPreview.setVisibility(View.VISIBLE);
        vidPreview.setVideoPath(filePath);
        // start playing
        vidPreview.start();
    
     

   /**
   * Uploading the file to server
    * */
   private class UploadFileToServer extends AsyncTask<Void, Integer, String>    
     

        @Override
         protected void onPreExecute() 
        // setting progress bar to zero
        progressBar.setProgress(0);
        super.onPreExecute();
        

            @Override
            protected void onProgressUpdate(Integer... progress) 
            // Making progress bar visible
            progressBar.setVisibility(View.VISIBLE);

            // updating progress bar value
            progressBar.setProgress(progress[0]);

          // updating percentage value
          txtPercentage.setText(String.valueOf(progress[0]) + "%");
          

         @Override
         protected String doInBackground(Void... params) 
         return uploadFile();
         

         @SuppressWarnings("deprecation")
         private String uploadFile() 
        String responseString = null;

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);

         try 
            AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                    new ProgressListener() 

                        @Override
                        public void transferred(long num) 
                publishProgress((int) ((num / (float) totalSize) * 100));
                        
                    );

            File sourceFile = new File(filePath);

            // Adding file data to http body
            entity.addPart("image", new FileBody(sourceFile));

            // Extra parameters if you want to pass to server
            entity.addPart("website",
                    new StringBody("www.androidhive.info"));
            entity.addPart("email", new StringBody("abc@gmail.com"));

            totalSize = entity.getContentLength();
            httppost.setEntity(entity);

            // Making server call
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) 
                // Server response
                responseString = EntityUtils.toString(r_entity);
             else 
                responseString = "Error occurred! Http Status Code: "
                        + statusCode;
            

         catch (ClientProtocolException e) 
            responseString = e.toString();
         catch (IOException e) 
            responseString = e.toString();
        

        return responseString;

        

        @Override
        protected void onPostExecute(String result) 
        Log.e(TAG, "Response from server: " + result);

        // showing the server response in an alert dialog
        showAlert(result);

        super.onPostExecute(result);
    

   

   /**
   * Method to show alert dialog
   * */
 private void showAlert(String message) 
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message).setTitle("Response from Servers")
            .setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() 
                public void onClick(DialogInterface dialog, int id) 
                    // do nothing
                
            );
    AlertDialog alert = builder.create();
    alert.show();


这是 AndroidMultiPart 类

   package info.androidhive.camerafileupload;

   import java.io.FilterOutputStream;
   import java.io.IOException;
   import java.io.OutputStream; 
   import java.nio.charset.Charset;

   import org.apache.http.entity.mime.HttpMultipartMode;
   import org.apache.http.entity.mime.MultipartEntity;

   @SuppressWarnings("deprecation")
   public class AndroidMultiPartEntity extends MultipartEntity

   

    private final ProgressListener listener;

    public AndroidMultiPartEntity(final ProgressListener listener) 
    super();
    this.listener = listener;
   

    public AndroidMultiPartEntity(final HttpMultipartMode mode,
        final ProgressListener listener) 
    super(mode);
    this.listener = listener;
    

    public AndroidMultiPartEntity(HttpMultipartMode mode, final String  boundary,
        final Charset charset, final ProgressListener listener) 
    super(mode, boundary, charset);
    this.listener = listener;
    

    @Override
    public void writeTo(final OutputStream outstream) throws IOException 
    super.writeTo(new CountingOutputStream(outstream, this.listener));
    

    public static interface ProgressListener 
    void transferred(long num);
   

   public static class CountingOutputStream extends FilterOutputStream 

    private final ProgressListener listener;
    private long transferred;

    public CountingOutputStream(final OutputStream out,
            final ProgressListener listener) 
        super(out);
        this.listener = listener;
        this.transferred = 0;
    

    public void write(byte[] b, int off, int len) throws IOException 
        out.write(b, off, len);
        this.transferred += len;
        this.listener.transferred(this.transferred);
    

        public void write(int b) throws IOException 
        out.write(b);
        this.transferred++;
        this.listener.transferred(this.transferred);
    
  
  

【问题讨论】:

你能分享一些错误发生的地方吗? (第 156 行的 UploadActivity) 第 156 行在尝试后开始,即 protected String doInBackground(Void... params) return uploadFile(); @SuppressWarnings("deprecation") private String uploadFile() String responseString = null; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = 新 HttpPost(Config.FILE_UPLOAD_URL);尝试 AndroidMultiPartEntity entity = new AndroidMultiPartEntity( new ProgressListener() @Override public void transfer(long num) publishProgress((int) ((num / (float) totalSize) * 100)); ); 它找不到AndroidMultiPartEntity类,尝试清理然后重建它。 我也添加了那个类 【参考方案1】:

虽然特定的 jar/aar 可能会添加到项目中,但仍必须告知 Android Studio 其存在。您是否在应用的 build.gradle 文件中添加了依赖项并单击了“同步 gradle”?

编辑

关于 Eclipse 中的 NoClassDefFoundError,我刚刚发现 this article 可能很有趣。

【讨论】:

哦,我错过了。在那种情况下,我的遮阳篷就没用了。【参考方案2】:

我看到一个 NoClassDefFoundError,你在编译之前尝试过旧的“清洁项目”吗?

【讨论】:

以上是关于获得致命异常:使用 Async 类的 AsyncTask #1的主要内容,如果未能解决你的问题,请参考以下文章

遇到致命异常时如何让 php 返回 500?

android.content.res.Resources$NotFoundException: Main 中的字符串资源 ID 致命异常

Java中的异常处理

使用 c++ async 进行并行编程

如何使用 Firebase (Crashlytics) 记录非致命(捕获)异常

使用 async/await 锁定资源