2017-04-24 94 views
0

我已經看了其他問題,但這個錯誤似乎代碼特定,所以我有點沮喪。我一直在一個應用程序,簡單地反向谷歌搜索某個圖像。AsynckTask運行時異常doInBackground

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)  

代碼可凌亂一點,因爲我嘗試過許多其他的東西,deleted.At錯誤就結束說引起:java.lang.NoClassDefFoundError:org.apache.http.entity.ContentType,但我不知道如果這與它有任何關係。我將活動意圖改爲發佈執行,(在UI中,UI代碼可能很危險),但它沒有幫助。我真的很感謝任何幫助/指導,我對Android編程很陌生如果可能有簡單的錯誤。

謝謝!

+0

你能編輯你原來的帖子來包含你的Logcat輸出嗎? –

+1

'NoClassDefFoundError'表示您正在引用無法找到的類。由於Android 5(我認爲)'org.apache.http'中的所有內容都被棄用了。但是,在聲明AsyncTask時,您禁止棄用警告:'@SuppressWarnings(「deprecation」)'。你可以在依賴關係範圍內添加到你的gradle文件中,我認爲這是你可以嘗試的方法:'useLibrary'org.apache.http.legacy''。我會建議,儘管停止使用這些類,並轉到「HttpConnection」 – 0xDEADC0DE

+0

@德魯哦,對不起。現在編輯 –

回答

0

您嘗試訪問org.apache.http.entity.ContentType並使用至少包含它的android API版本。可以用新的和支持的(首選)替換這個類,或者降低最小/目標API級別。