Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
In my application, I want to download all images from the database.

For single image, the code is working fine. For multiple images, out of memory error is showing.

Here is my code:
public class GalleryFragment extends Fragment {
	
	ProgressBar progressBar;
	TextView progressText;
	
	 JSONParser jsonParser = new JSONParser();
	    
	 private static String url_download_photo = Global.url+"/clubs/download_photo.php";
	    
	 private static final String TAG_SUCCESS = "success";
	 private static final String TAG_CLUBS = "clubs";
	 private static final String TAG_PHOTO = "photo";

	JSONArray clubs = null;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
		
        progressText = (TextView) rootView.findViewById(R.id.textView1);

		progressBar = (ProgressBar) rootView.findViewById( R.id.progressBar1); 
		
		new DownloadPhoto().execute();
	
	return rootView;
	}
	
    class DownloadPhoto extends AsyncTask<String, String, String> {
		
        protected String doInBackground(String... args) {
        	
        	Log.v("DownloadPhoto","doInBackground");

            try {
            	
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("club_id", ClubActivity.club_id));
     
                JSONObject json = jsonParser.makeHttpRequest(url_download_photo,"GET", params);

                Log.d("Download Image", json.toString());
                
                int success = json.getInt(TAG_SUCCESS);
 
                if (success == 1) {       
                	
               	 getActivity().runOnUiThread(new Runnable() {
          		    public void run() {
          		       progressBar.setVisibility(View.VISIBLE);
          		    }
          		});
                	
                	clubs = json.getJSONArray(TAG_CLUBS);
               	 
               	 	progressBar.setMax(clubs.length());

                    for (int i = 0; i < clubs.length(); i++) {
                   	 JSONObject c = clubs.getJSONObject(i);
                 
                        // Storing each json item in variable
                        String photo = c.getString(TAG_PHOTO);
                   
            			progressBar.setProgress(i+1);
            			
            			Log.v("Photo "+i,""+photo);
                    }
                    
                    getActivity().runOnUiThread(new Runnable() {
              		    public void run() {
              		    	 progressBar.setVisibility(View.INVISIBLE);
              		    }
              		});
                }
                else 
                {
                	
                }
            
            } catch (JSONException e) {
            	problem();
                e.printStackTrace();             
            }
            catch(Exception e)
            {
            	problem();
            	Log.v("Exception",""+e);           	
            }
       
            return null;
        }
    }

	void problem()
	{
		getActivity().runOnUiThread(new Runnable() {
		    public void run() {
		    	 Toast.makeText(getActivity(), "Something went wrong! Try again!",Toast.LENGTH_LONG).show();
		    	progressBar.setVisibility(View.INVISIBLE);
				progressText.setVisibility(View.INVISIBLE);
			    }
			});
	}
}

download_photo.php
<?php
 
// array for JSON response
$response = array();
 
// include db connect class
require_once __DIR__ . '/db_connect.php';
 
// connecting to db
$db = new DB_CONNECT();

// check for post data
if (isset($_GET["club_id"])) {
    $club_id = $_GET['club_id'];

	$result = mysql_query("SELECT photo FROM gallery WHERE club_id = '$club_id'") or die(mysql_error());
 
	if (!empty($result)) {
		// check for empty result
		if (mysql_num_rows($result) > 0) {
			
			$response["clubs"] = array();
 
			while ($row = mysql_fetch_array($result)) {
				$clubs = array();
				$clubs["photo"] = $row["photo"];
				
				array_push($response["clubs"], $clubs);
			}
			// success
			$response["success"] = 1;
 

			echo json_encode($response);
		}
		else {
			$response["success"] = 0;
			$response["message"] = "Not found";
 
			echo json_encode($response);
		}
	}
	else {
		$response["success"] = 0;
		$response["message"] = "Not found";
 
		echo json_encode($response);
	}
}
else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
    echo json_encode($response);
}
?>

Error
07-01 17:56:40.360: E/dalvikvm-heap(6962): Out of memory on a 1490086-byte allocation.
07-01 17:56:40.400: E/AndroidRuntime(6962): FATAL EXCEPTION: AsyncTask #1
07-01 17:56:40.400: E/AndroidRuntime(6962): Process: com.daceshine.clubs, PID: 6962
07-01 17:56:40.400: E/AndroidRuntime(6962): java.lang.RuntimeException: An error occured while executing doInBackground()
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at android.os.AsyncTask$3.done(AsyncTask.java:300)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at java.util.concurrent.FutureTask.run(FutureTask.java:242)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at java.lang.Thread.run(Thread.java:841)
07-01 17:56:40.400: E/AndroidRuntime(6962): Caused by: java.lang.OutOfMemoryError
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:94)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:132)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at java.lang.StringBuilder.append(StringBuilder.java:124)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at org.json.JSONStringer.string(JSONStringer.java:344)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at org.json.JSONStringer.value(JSONStringer.java:252)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at org.json.JSONObject.writeTo(JSONObject.java:672)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at org.json.JSONStringer.value(JSONStringer.java:237)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at org.json.JSONArray.writeTo(JSONArray.java:602)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at org.json.JSONStringer.value(JSONStringer.java:233)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at org.json.JSONObject.writeTo(JSONObject.java:672)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at org.json.JSONObject.toString(JSONObject.java:641)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at com.daceshine.clubs.GalleryFragment$DownloadPhoto.doInBackground(GalleryFragment.java:71)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at com.daceshine.clubs.GalleryFragment$DownloadPhoto.doInBackground(GalleryFragment.java:1)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-01 17:56:40.400: E/AndroidRuntime(6962): 	... 4 more


What should I change? Is there any other method for doing it?
Posted
Updated 1-Jul-14 4:02am
v3
Comments
Sergey Alexandrovich Kryukov 1-Jul-14 10:49am    
What is the language in the first fragment? Java? And you never mentioned that. In what line the exception is thrown? Not line number; where is that code? You need to formulate questions more accurately.
—SA

1 solution

Changed my codes and now no out of memory error
public class GalleryFragment extends Fragment {
	
	ProgressBar progressBar;
	TextView progressText;
	
	 JSONParser jsonParser = new JSONParser();
	    
	 private static String url_download_photo_id = Global.url+"/clubs/download_photo_id.php";
	 private static String url_download_photo = Global.url+"/clubs/download_photo.php";
	 
	 private static final String TAG_SUCCESS = "success";
	 private static final String TAG_CLUBS = "clubs";
	 private static final String TAG_PHOTO = "photo";
	 private static final String TAG_PHOTO_ID = "photo_id";
	 
	 // News JSONArray
	JSONArray clubs = null;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
		
        progressText = (TextView) rootView.findViewById(R.id.textView1);

	    //Progress Bar
		progressBar = (ProgressBar) rootView.findViewById( R.id.progressBar1); 
		
		new DownloadPhotoId().execute();
	
	return rootView;
	}
	
    class DownloadPhotoId extends AsyncTask<string,> {
		
        protected String doInBackground(String... args) {
        	
        	Log.v("DownloadPhotoId","doInBackground");
  
            // check for success tag
            try {
            	
                // Building Parameters
                List<namevaluepair> params = new ArrayList<namevaluepair>();
                params.add(new BasicNameValuePair("club_id", ClubActivity.club_id));
     
                JSONObject json = jsonParser.makeHttpRequest(url_download_photo_id,"GET", params);
     
                // check log cat for response
                Log.d("Download Image Id", json.toString());
                
                int success = json.getInt(TAG_SUCCESS);
 
                if (success == 1) {       
                	
               	 getActivity().runOnUiThread(new Runnable() {
          		    public void run() {
          		       progressBar.setVisibility(View.VISIBLE);
          		    }
          		});
                	
                	clubs = json.getJSONArray(TAG_CLUBS);
               	 
               	 	progressBar.setMax(clubs.length());

                    for (int i = 0; i < clubs.length(); i++) {
                   	 JSONObject c = clubs.getJSONObject(i);
                 
                        // Storing each json item in variable
                        String photo_id = c.getString(TAG_PHOTO_ID);
                   
            			progressBar.setProgress(i+1);
            			
            			Log.v("Photo id"+i,""+photo_id);
            			
            			new DownloadPhoto(photo_id).execute();
                    }
                    
                    getActivity().runOnUiThread(new Runnable() {
              		    public void run() {
              		    	 progressBar.setVisibility(View.INVISIBLE);
              		    }
              		});
                }
                else 
                {
                	
                }
            
            } catch (JSONException e) {
            	problem();
                e.printStackTrace();             
            }
            catch(Exception e)
            {
            	problem();
            	Log.v("Exception",""+e);           	
            }
       
            return null;
        }
 
        protected void onPostExecute(String file_url) {

        }
    }
    
class DownloadPhoto extends AsyncTask<string,> {
	
	String photo_id = null;
	DownloadPhoto(String pId)
	{
		photo_id = pId;
	}
		
        protected String doInBackground(String... args) {
        	
        	Log.v("DownloadPhoto","doInBackground");
  
            // check for success tag
            try {
            	
                // Building Parameters
                List<namevaluepair> params = new ArrayList<namevaluepair>();
                params.add(new BasicNameValuePair("photo_id", photo_id));
     
                JSONObject json = jsonParser.makeHttpRequest(url_download_photo,"GET", params);
     
                // check log cat for response
                Log.d("Download Image Id", json.toString());
                
                int success = json.getInt(TAG_SUCCESS);
 
                if (success == 1) {       
                	
                	clubs = json.getJSONArray(TAG_CLUBS);

                   	 JSONObject c = clubs.getJSONObject(0);
                 
                        // Storing each json item in variable
                        String photo = c.getString(TAG_PHOTO);

            			Log.v("Photo id "+photo_id,""+photo);
                }
                else 
                {
                	
                }
            
            } catch (JSONException e) {
            	problem();
                e.printStackTrace();             
            }
            catch(Exception e)
            {
            	problem();
            	Log.v("Exception",""+e);           	
            }
       
            return null;
        }
 
        protected void onPostExecute(String file_url) {

        }
    }

	void problem()
	{
		getActivity().runOnUiThread(new Runnable() {
		    public void run() {
		    	 Toast.makeText(getActivity(), "Something went wrong! Try again!",Toast.LENGTH_LONG).show();
		    	progressBar.setVisibility(View.INVISIBLE);
				progressText.setVisibility(View.INVISIBLE);
			    }
			});
	}
}

download_photo_id.php
$response = array();
 
// include db connect class
require_once __DIR__ . '/db_connect.php';
 
// connecting to db
$db = new DB_CONNECT();

// check for post data
if (isset($_GET["club_id"])) {
    $club_id = $_GET['club_id'];

	$result = mysql_query("SELECT photo_id FROM gallery WHERE club_id = '$club_id'") or die(mysql_error());
 
	if (!empty($result)) {
		// check for empty result
		if (mysql_num_rows($result) > 0) {

			$response["clubs"] = array();
 
			while ($row = mysql_fetch_array($result)) {

				$clubs = array();
				$clubs["photo_id"] = $row["photo_id"];
				
				array_push($response["clubs"], $clubs);
			}
			// success
			$response["success"] = 1;
 
			// echoing JSON response
			echo json_encode($response);
		}
		else {
			$response["success"] = 0;
			$response["message"] = "Not found";
 
			// echo no users JSON
			echo json_encode($response);
		}
	}
	else {
		$response["success"] = 0;
		$response["message"] = "Not found";
 
		// echo no clubs JSON
		echo json_encode($response);
	}
}
else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
    // echoing clubs response
    echo json_encode($response);
}
?>

download_photo.php
$response = array();
 
// include db connect class
require_once __DIR__ . '/db_connect.php';
 
// connecting to db
$db = new DB_CONNECT();

// check for post data
if (isset($_GET["photo_id"])) {
    $photo_id = $_GET['photo_id'];

	$result = mysql_query("SELECT photo FROM gallery WHERE photo_id = '$photo_id'") or die(mysql_error());
 
	if (!empty($result)) {
		// check for empty result
		if (mysql_num_rows($result) > 0) {
			$response["clubs"] = array();
 
			while ($row = mysql_fetch_array($result)) {
				$clubs = array();
				$clubs["photo"] = $row["photo"];
				
				array_push($response["clubs"], $clubs);
			}
			// success
			$response["success"] = 1;
 
			// echoing JSON response
			echo json_encode($response);
		}
		else {
			$response["success"] = 0;
			$response["message"] = "Not found";
 
			// echo no users JSON
			echo json_encode($response);
		}
	}
	else {
		$response["success"] = 0;
		$response["message"] = "Not found";
 
		// echo no clubs JSON
		echo json_encode($response);
	}
}
else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
    // echoing clubs response
    echo json_encode($response);
}
?>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900