1

in my application i'm wrote simole download manager to download files via internet. but HttpURLConnection getContentLength() return wrong result such as -1, i'm testing this image file. file exist and doesnt have problem but i have problem to get file size. my simplified code:

URL url = new URL(downloadPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();

final int fileSize = connection.getContentLength();

FileOutputStream outputStream = new FileOutputStream(filepath);

InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[G.DOWNLOAD_BUFFER_SIZE];
int len = 0;
int downloadedSize = 0;
while ((len = inputStream.read(buffer)) > 0) {
    outputStream.write(buffer, 0, len);
    downloadedSize += len;

    final float downloadPercent = 100.0f * (float) downloadedSize / fileSize;
    if (listener != null) {
    }
}
outputStream.close();
connection.disconnect();

Permissions:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

1 Answers1

0

It looks like the main problem in your code is the call to connection.setDoOutput(true);.

With that call included, I got a return value of -1 from getContentLength(), and it also didn't download the image successfully.

When I removed the call to connection.setDoOutput(true); it started to work just fine and return valid values, and also successfully download the image.

Here is the code that worked for me, I added code to show a toast with the return value of getContentLength() after the download has completed:

class PostAsync extends AsyncTask<String, String, Integer> {

    private ProgressDialog pDialog;

    private static final String sourcepath = "http://www.planwallpaper.com/static/images/supranatural-3d-wallpaper-images.jpg";

    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Attempting download...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected Integer doInBackground(String... args) {

        int fileSize = 0;

        try {
            URL url = new URL(sourcepath);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            fileSize = connection.getContentLength();

            InputStream inputStream = connection.getInputStream();

            bmp = BitmapFactory.decodeStream(inputStream);

            inputStream.close();
            connection.disconnect();

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

        return fileSize;
    }

    protected void onPostExecute(Integer fileSize) {

        pDialog.dismiss();

        MainActivity.this.image.setImageBitmap(bmp);

        Toast.makeText(MainActivity.this, "file size: " +  fileSize, Toast.LENGTH_LONG).show();

    }
}

I tested with two different images just to make sure that it returned different values.

First, with the image in your question:

enter image description here

And with a different image:

enter image description here

Full MainActivity class:

public class MainActivity extends ActionBarActivity {

    private ImageView image;
    private Bitmap bmp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        image = (ImageView) findViewById(R.id.imageView);

        new PostAsync().execute();
    }


    @Override
    protected void onResume() {
        super.onResume();

        //put on resume functionality here....

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    class PostAsync extends AsyncTask<String, String, Integer> {

        private ProgressDialog pDialog;

        private static final String sourcepath = "http://www.planwallpaper.com/static/images/supranatural-3d-wallpaper-images.jpg";

        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Attempting download...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected Integer doInBackground(String... args) {

            int fileSize = 0;

            try {
                URL url = new URL(sourcepath);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();

                fileSize = connection.getContentLength();

                InputStream inputStream = connection.getInputStream();

                bmp = BitmapFactory.decodeStream(inputStream);

                inputStream.close();
                connection.disconnect();

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

            return fileSize;
        }

        protected void onPostExecute(Integer fileSize) {

            pDialog.dismiss();

            MainActivity.this.image.setImageBitmap(bmp);

            Toast.makeText(MainActivity.this, "file size: " +  fileSize, Toast.LENGTH_LONG).show();

        }
    }

}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <ImageView android:id="@+id/imageView" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
  • @mahdipishguy No problem! I just added the full MainActivity code and the layout xml file as well in the answer. – Daniel Nugent Jul 02 '15 at 06:30
  • very thanks. by the way sir. how to add resum ability for your code? can you work with that? –  Jul 02 '15 at 06:43
  • @mahdipishguy Sure, this is just a simple example so I didn't have `onResume()` in there. I just added a placeholder `onResume()` to the full class code, just add whatever functionality you need there. – Daniel Nugent Jul 02 '15 at 06:49
  • thanks sir. unfortunately i dont whats resume functionality and how to do that. can you more help me? –  Jul 02 '15 at 07:00
  • @mahdipishguy What exactly do you want to do in `onResume()`? It's late here and I'm going to sleep now, but I'll check back in the morning and see if I can help. – Daniel Nugent Jul 02 '15 at 07:17
  • Oh sir i'm sorry . `resume ability for download manager` :) please see this link : http://stackoverflow.com/questions/31177949/android-prepare-resume-ability-to-download-manager –  Jul 02 '15 at 07:25