Jack
Jack

Reputation: 2053

Closing Input Stream to stop resource leaking

I have recently ran into the problem of "A resource was acquired at attached stack trace but never released"

I have read up you need to close the connection after it has been used. I can't find any questions that would help me out here so I am writing my own one.

How would I close my input stream after it had been used to prevent this happening?

class:

public class SetWallpaperAsync extends AsyncTask<String, String, String> {
private Context context;
private ProgressDialog pDialog;
String image_url;
URL mImageUrl;
String myFileUrl;
Bitmap bmImg = null;

public SetWallpaperAsync(Context context) {
this.context = context;
} 

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub

super.onPreExecute();

pDialog = new ProgressDialog(context);
pDialog.setMessage("Setting Wallpaper...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();

}

@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub

try {

    mImageUrl = new URL(args[0]);


    HttpURLConnection conn = (HttpURLConnection) mImageUrl
            .openConnection();
    conn.setDoInput(true);
    conn.connect();
    InputStream is = conn.getInputStream();



    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Config.RGB_565;
    Bitmap bmImag = BitmapFactory.decodeStream(is, null, options);





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

return null;
}

@Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
WallpaperManager wpm = WallpaperManager.getInstance(context);
try {
    wpm.setBitmap(bmImg);
} catch (IOException e) {

    // TODO Auto-generated catch block
    e.printStackTrace();
}
pDialog.dismiss();

}

}

Upvotes: 0

Views: 325

Answers (1)

Chris
Chris

Reputation: 23181

You need to call the close method on the input stream. Ideally, this should be in a finally block so it gets called even when there is an exception. To achieve this, move your InputStream declaration outside the try:

InputStream is = null;

then you can do this inside the try block: is = conn.getInputStream();

then, after your catch block, include a finally:

 finally{
      if(is != null){
          try{
            is.close();
          }catch(Exception e){}
      }
    }

Upvotes: 1

Related Questions