我正在使用AsyncTask类从服务器下载。有时我的代码工作正常,有时它会引发异常。
这是我的logcat:
06-29 17:29:01.123: E/AndroidRuntime(321): FATAL EXCEPTION: AsyncTask #5
06-29 17:29:01.123: E/AndroidRuntime(321): java.lang.RuntimeException: An error occured while executing doInBackground()
06-29 17:29:01.123: E/AndroidRuntime(321): at android.os.AsyncTask$3.done(AsyncTask.java:200)
06-29 17:29:01.123: E/AndroidRuntime(321): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-29 17:29:01.123: E/AndroidRuntime(321): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-29 17:29:01.123: E/AndroidRuntime(321): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-29 17:29:01.123: E/AndroidRuntime(321): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-29 17:29:01.123: E/AndroidRuntime(321): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
06-29 17:29:01.123: E/AndroidRuntime(321): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
06-29 17:29:01.123: E/AndroidRuntime(321): at java.lang.Thread.run(Thread.java:1096)
06-29 17:29:01.123: E/AndroidRuntime(321): Caused by: java.lang.IllegalStateException: No wrapped connection.
06-29 17:29:01.123: E/AndroidRuntime(321): at org.apache.http.impl.conn.AbstractClientConnAdapter.assertValid(AbstractClientConnAdapter.java:163)
06-29 17:29:01.123: E/AndroidRuntime(321): at org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseEntity(AbstractClientConnAdapter.java:243)
06-29 17:29:01.123: E/AndroidRuntime(321): at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:281)
06-29 17:29:01.123: E/AndroidRuntime(321): at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:121)
06-29 17:29:01.123: E/AndroidRuntime(321): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:410)
06-29 17:29:01.123: E/AndroidRuntime(321): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
06-29 17:29:01.123: E/AndroidRuntime(321): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
06-29 17:29:01.123: E/AndroidRuntime(321): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
06-29 17:29:01.123: E/AndroidRuntime(321): at com.pumpkynhead.ebookportal.ebook.HomeScreen$Asynch_Download_Book.doInBackground(HomeScreen.java:967)
06-29 17:29:01.123: E/AndroidRuntime(321): at com.pumpkynhead.ebookportal.ebook.HomeScreen$Asynch_Download_Book.doInBackground(HomeScreen.java:1)
06-29 17:29:01.123: E/AndroidRuntime(321): at android.os.AsyncTask$2.call(AsyncTask.java:185)
06-29 17:29:01.123: E/AndroidRuntime(321): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-29 17:29:01.123: E/AndroidRuntime(321): ... 4 more
这是我的代码。
private static class Asynch_Download_Book extends AsyncTask<String,Void,Void>{
@Override
protected Void doInBackground(String... urls) {
// TODO Auto-generated method stub
String result;
String URL = urls[0];
HttpGet urlConnection = new HttpGet(URL);
//DefaultHttpClient httpClient=new DefaultHttpClient();
try {
HttpResponse httpresp = Login.httpClient.execute(urlConnection);
HttpEntity entity = httpresp.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 1024 * 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
System.out.println("result........" +result);
jsonParsingdownload(result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private void jsonParsingdownload(String result1) {
try {
JSONObject jsonObject = new JSONObject(result1);
JSONObject resuJsonObject = jsonObject.getJSONObject("Result");
JSONArray dataArray = resuJsonObject.getJSONArray("Data");
//{"Result":{"Data":[{"file_id":"20","file_ref_id":"5","file_path":"james.zip"}]}}
for (int i = 0; i < dataArray.length(); i++) {
HashMap<String, String> map1 = new HashMap<String, String>();
JSONObject e = dataArray.getJSONObject(i);
//Message myMessage=new Message();
// Bundle resBundle = new Bundle();
//map1.put("file_id", e.get("file_id").toString());
String File__Book_Name = e.getString("file_path").toString();
String FILE_IDD=e.getString("file_id").toString();
Log.d(FILE_IDD, FILE_IDD);
// http://www.tritoneit.com/index.php?option=com_hikashop&ctrl=product&task=download&file_id=20&Itemid=585
String File_Path_Book = "http://www.tritoneit.com/index.php?option=com_hikashop&ctrl=product&task=download&"+"FILE_IDD&Itemid=585";
Log.d(File__Book_Name, File__Book_Name);
Log.d(File_Path_Book, File_Path_Book);
map1.put("File_Path_Book", File_Path_Book);
map1.put("File__Book_Name", File__Book_Name);
map1.put("FILE_IDD", FILE_IDD);
map1.put("File_Path_Book", File_Path_Book);
new DownloadTask().execute(map1);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data" + e.toString());
}
}
}
// Async Class to Download a book from url recevied from the server
static class DownloadTask extends AsyncTask<Map, Void, Void> {
// Use this class to download the image, save the image in SD card
// and
// Also to update the respective record in the database with the new
// path in SD card.
@Override
protected Void doInBackground(Map... downLoadBook) {
synchronized (this) {
// Make HTTP Connection
// Get the image bytes
// Write the image to SD card location.
// run SQL query Update table... to update the respective
// column with the image path in sd card.
String FileID = (String) downLoadBook[0]
.get((String) "FILE_IDD");
System.out.println("File Id oF download book" +FileID);
String ImagePath = (String) downLoadBook[0]
.get((String) "File_Path_Book");
System.out.println("ImagePath oF download book" +ImagePath);
String BookName=(String) downLoadBook[0]
.get((String) "File__Book_Name");
System.out.println("BookName oF download book" +BookName);
String File_Path_B=(String) downLoadBook[0]
.get((String) "File_Path_Book");
System.out.println("File_Path_B oF download book" +File_Path_B);
// String url=File_Path_B;
log("Retrieving Image from URL :" + File_Path_B);
try {
File ebooksDir = new File(
Environment.getExternalStorageDirectory(), "BookName");
String targetPrependPathstore = ebooksDir.getAbsolutePath();
// String imageOnSDCard = targetPrependPathstore
//+ "/store/images/" + bookId + "/"
//+ storeBookData[0].get("file_path");
String imageOnSDCard = targetPrependPathstore+"/ebooks/"
+ downLoadBook[0].get(BookName);
log("Image being saved on SD card is :" + imageOnSDCard);
URL url = new URL(File_Path_B);
System.out.println("Path url of download book" +url);
new File(imageOnSDCard.substring(0,
imageOnSDCard.lastIndexOf("/"))).mkdirs();
BufferedInputStream serverBook = new BufferedInputStream(
url.openConnection().getInputStream(), 1024 * 8);
BufferedOutputStream imageStreamOnSDCard = new BufferedOutputStream(
new FileOutputStream(imageOnSDCard), 1024 * 8);
byte imageBytes[] = new byte[2048 * 2];
int n;
while ((n = serverBook.read(imageBytes, 0, (2048 * 2))) >= 0) {
imageStreamOnSDCard.write(imageBytes, 0, n);
}
imageStreamOnSDCard.close();
serverBook.close();
// ImageStore=bitmap.toString();
// Have to change this.
//_self.sqlHelper.updateStoreCacheWithLocalImageLocation(
// imageOnSDCard, ImagePath);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}