doInBackground的AsynckTask运行时异常

时间:2017-04-24 12:57:09

标签: java android android-asynctask

我已经查看了其他问题,但这个错误似乎是特定于代码的,所以我有点沮丧。我一直在开发一款只需反转Google搜索特定图片的应用。

MainActivity

    package com.example.ygoc95.myapplication;
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.net.Uri;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.provider.Settings;
    import android.support.annotation.NonNull;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.TextView;



    import org.json.JSONObject;

    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.InetAddress;
    import java.net.MalformedURLException;
    import java.net.URL;

    import static android.R.attr.bitmap;
    import org.jibble.simpleftp.*;

    public class MainActivity extends AppCompatActivity  {

private File resim;
private String path,yol;
private ImageView iv;
private Bitmap bm;
private Button send;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    send = (Button) findViewById(R.id.uploadButton);

    iv = (ImageView) findViewById(R.id.resim);
    Bitmap bm = BitmapFactory.decodeResource(this.getResources(), R.drawable.url);
    iv.setImageBitmap(bm);
    path = Environment.getExternalStorageDirectory().toString();
    resim = new File(path, "url.jpg");

    OutputStream fOut = null;
    try {
        fOut = new FileOutputStream(resim);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
    try {
        fOut.flush();
        fOut.close();
    } catch (IOException e) {
        e.printStackTrace();
    }


}




@Override
protected void onStart() {
    super.onStart();
    send.setOnClickListener((new View.OnClickListener() {

        @Override
        public void onClick(View paramV) {
            Context a=getApplicationContext();
            new async(a).execute(resim);


        }
    }));


}

       }

AsyckTask

 package com.example.ygoc95.myapplication;

 import android.content.Context;
 import android.content.Intent;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 import android.net.Uri;
 import android.os.AsyncTask;
 import android.os.Environment;
 import android.support.annotation.NonNull;


 import org.apache.http.HttpResponse;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.client.params.HttpClientParams;
 import org.apache.http.entity.mime.content.FileBody;
 import org.apache.http.entity.mime.content.StringBody;
 import org.apache.http.impl.client.DefaultHttpClient;


 import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.math.MathContext;


 @SuppressWarnings("deprecation")
 public class async extends AsyncTask<File,File,File> {
private static final String UPLOAD_IMAGE_URL =           "https://www.google.ca/searchbyimage/upload";
private Context mContext;
public  String resultsURL;
public async(Context a) {
    mContext=a;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();

}

private HttpResponse uploadImage(File imageFile) throws IOException {
    HttpPost post = new HttpPost(UPLOAD_IMAGE_URL);

    HttpClientParams.setRedirecting(post.getParams(), false);


    org.apache.http.entity.mime.MultipartEntity entity = new org.apache.http.entity.mime.MultipartEntity();
    entity.addPart("encoded_image", new FileBody(imageFile));
    entity.addPart("image_url",new StringBody(""));
    entity.addPart("image_content",new StringBody(""));
    entity.addPart("filename",new StringBody(""));
    entity.addPart("h1",new StringBody("en"));
    entity.addPart("bih",new StringBody("179"));
    entity.addPart("biw",new StringBody("1600"));


    post.setEntity(entity);

    HttpResponse response = new DefaultHttpClient().execute(post);

    return response;


}
private File exportToInternalStorage(Bitmap bitmap, String name) {

    File resizedImageFile = new File(Environment.getExternalStorageDirectory().toString(),"face.png");

    try {
        FileOutputStream fOut = new FileOutputStream(resizedImageFile);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
    } catch (Exception e) { // TODO
        e.printStackTrace();
    }

    return resizedImageFile;

}



private String getResultsURL(HttpResponse response) throws IOException {
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String resultsURL = "";
    try {

        String line;
        while ((line = rd.readLine()) != null) {
            if (line.indexOf("https://www.google.ca/search?tbs=sbi") > 0) {
                resultsURL = line.substring(9, line.length() - 12);
                continue;
            }
        }
    } finally {
        rd.close();
    }

    return resultsURL;
}



private void openResultsPage(String resultsURL) {
    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(resultsURL));
    mContext.startActivity(browserIntent);
}



@Override
protected File doInBackground(File... params) {

    File image =params[0];
    String fileyol=image.getAbsolutePath();
    Bitmap shrunkBitmap= BitmapFactory.decodeFile(fileyol);
    File resizedImage = exportToInternalStorage(shrunkBitmap, "resized_" + System.currentTimeMillis());
    String path = resizedImage.getAbsolutePath();

    HttpResponse response = null;
    try {
        response = uploadImage(resizedImage);
        resultsURL = getResultsURL(response);

    } catch (IOException e) {
        e.printStackTrace();
    }



    return null;
}

@Override
protected void onPostExecute(File file) {
    super.onPostExecute(file);
    openResultsPage(resultsURL);



}
 }

logcat的

04-24 15:19:32.538 5194-5344/com.example.ygoc95.myapplication E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                                            java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                                at android.os.AsyncTask$3.done(AsyncTask.java:299)
                                                                                at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
                                                                                at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
                                                                                at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:137)
                                                                                at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
                                                                                at java.lang.Thread.run(Thread.java:856)
                                                                             Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.ContentType
                                                                                at org.apache.http.entity.mime.content.FileBody.<init>(FileBody.java:89)
                                                                                at com.example.ygoc95.myapplication.async.uploadImage(async.java:60)
                                                                                at com.example.ygoc95.myapplication.async.doInBackground(async.java:135)
                                                                                at com.example.ygoc95.myapplication.async.doInBackground(async.java:38)
                                                                                at android.os.AsyncTask$2.call(AsyncTask.java:287)
                                                                                at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
                                                                                at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
                                                                                at java.lang.Thread.run(Thread.java:856) 

代码可能有点凌乱,因为我尝试了很多其他东西并删除了。在错误结束时它表示引起:java.lang.NoClassDefFoundError:org.apache.http.entity.ContentType但是我没有&#39;我知道这是否与它有关。我将活动意图改为post post,(认为UI代码在doInbackground中可能很危险),但它没有帮助。我非常感谢任何帮助/指导,我对Android编程有点新鲜,很抱歉如果可能有简单的错误。

谢谢!

1 个答案:

答案 0 :(得分:0)

您尝试使用不再包含它的最小Android API版本访问org.apache.http.entity.ContentType。将此类替换为新的和受支持的(首选),或者降低最低/目标API级别。