I'm uploading multiple images one by one to server. I'm getting OOM error in the line bm = BitmapFactory.decodeFile(imagepath);
. I recycled bitmap after uploading each image file but still the error is showing. Is there something wrong in my code? Also, is there any better way of uploading multiple images one by one from ArrayList?
private void loadNext() {
System.out.println("sammy_reached_loadNext");
if(finalImages.size()>0){
System.out.println("sammys_imagelist_after: "+finalImages.size());
String path = finalImages.get(0);
System.out.println("sammys_current_pic_path "+path);
new UploadSingleImage(path).execute();
}else{
File dir = new File(file_path);
if (dir.isDirectory()){
String[] children = dir.list();
if(children!=null){
for (int i = 0; i < children.length; i++){
new File(dir, children[i]).delete();
}
}
}
pd.dismiss();
Toast.makeText(getActivity(), "Upload Successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), AfterPostActivity.class);
intent.putExtra("prdid",post_id);
startActivity(intent);
getActivity().finish();
}
}
private class UploadSingleImage extends AsyncTask<Void, Void, String> {
private HttpClient httpClient;
private HttpPost postRequest;
private MultipartEntity reqEntity;
StringBuilder s;
String imagepath;
Bitmap bm=null;
UploadSingleImage(String imagepath) {
this.imagepath = imagepath;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pd.setMessage("Please wait..");
pd.show();
}
@Override
protected String doInBackground(Void... urls) {
try {
httpClient = new DefaultHttpClient();
postRequest = new HttpPost(Utility.POSTPRODIMAGES);
reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("id", new StringBody(post_id));
Log.e("sammy_inParam_post_id", "******" + post_id);
bm = BitmapFactory.decodeFile(imagepath);
if (bm != null) {
ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bos1);
byte[] data1 = bos1.toByteArray();
String imgName = "myprod.jpg";
ByteArrayBody bab = new ByteArrayBody(data1, imgName);
reqEntity.addPart("image" , bab);
}
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
//System.out.println("sammy_Multiupload_doinback_Response: " + s);
} catch (Exception e) {
System.out.println("sammy_multiimage_doinback_excep "+e);
}
return s.toString();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("sammys_Multiupload_onpostexec_Response: " + result);
try {
JSONObject jObj = new JSONObject(result);
if (jObj.getString("ACK").equals("1")) {
bm.recycle();
finalImages.remove(0);
loadNext();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}